diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a81d2f..4b50f89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,14 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ### Fixes +- AI tasks: while a step waits for your confirmation you can take over first (to look or change something); the question stays, and can be answered while you're in control or after handing back (#201). +- The control page no longer stays on "running" when a task's event stream is closed for good: it follows the task again if it is still there, or marks it stopped. Reconnecting or reloading the page no longer redraws old gesture marks (#201). +- A page or `task events` that fell behind a busy task no longer misses its end and stays open; a task's end stops every step still under way (a step asking to leave the task's scope, and its question, are two), so none keeps spinning; nothing is recorded after the end (#201). +- `task run` waits for what the command started to stop (killing what ignores SIGTERM) before it exits; stopping a group no longer sends a late SIGKILL to a group number that may have been reused (#201). +- The picture of a phone driven by WebDriverAgent ends when you switch to another device, instead of showing the old one (#201). +- The H.264 copy of the phone's own video counts a crashed ffmpeg as a failure and moves on to the next encoder, instead of restarting it for ever (#201). +- `task run --url` stops within 10 seconds of Ctrl-C even if the viewer doesn't answer, and gives up an event stream that goes silent or sends an endless event (#201). +- Only one daemon runs per socket, even when two start at once, and the socket is private from the moment it is created; a lock that can't be taken at all is reported as such instead of as another daemon (#201). - When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200). - A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200). - Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 9bf9f9b..6ccdee0 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -16,6 +16,14 @@ ### 修复 +- AI 任务:某一步在等你确认时,可以先接管(看看或改一下);问题会一直留着,接管时或交还后都能回答(#201)。 +- 任务的事件流被彻底关掉时,控制台不再一直停在「执行中」:任务还在就重新跟上,不在了就标成已停止。重连或刷新页面时也不会再把以前的手势标记重画一遍(#201)。 +- 跟着一个忙碌任务的页面或 `task events` 跟不上时,不再错过任务结束而一直挂着;任务结束时把还在进行的步骤都停下(要越出任务范围的一步和它的提问是两步),不会再有一直转圈的步骤;结束后也不会再记任何事件(#201)。 +- `task run` 退出前会等命令启动的进程都停下(不理 SIGTERM 的会被强制结束);停进程组时不再在几秒后对可能已被复用的组号补发 SIGKILL(#201)。 +- 用 WebDriverAgent 控制的手机,切换到别的设备后,原来的画面流会结束,不再一直显示旧设备(#201)。 +- 手机原生视频转成 H.264 时,ffmpeg 崩溃算作失败,换下一个编码器,不再无休止地重启(#201)。 +- `task run --url` 在控制台不应答时,按 Ctrl-C 后 10 秒内也能停下;事件流长时间没动静或发来没有结尾的事件时会放弃(#201)。 +- 一个 socket 只会有一个守护进程在跑,两个同时启动也一样;socket 从创建那一刻起就只有自己能访问;根本拿不到锁时如实报错,不再说成已有守护进程(#201)。 - 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。 - 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。 - 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。 diff --git a/apps/iphone-control/src/procgroup.rs b/apps/iphone-control/src/procgroup.rs index 762cb5e..addacb1 100644 --- a/apps/iphone-control/src/procgroup.rs +++ b/apps/iphone-control/src/procgroup.rs @@ -7,7 +7,17 @@ use std::time::Duration; /// How long a group has after SIGTERM before SIGKILL pub const GRACE: Duration = Duration::from_secs(3); -/// SIGTERM to the group led by `pid`, SIGKILL [`GRACE`] later if it is still there +/// How often a stopped group is looked for while it has [`GRACE`] +const POLL: Duration = Duration::from_millis(100); + +/// Whether any process of the group is left (zombies count until reaped) +fn alive(pgid: libc::pid_t) -> bool { + unsafe { libc::kill(-pgid, 0) == 0 } +} + +/// SIGTERM to the group led by `pid`, SIGKILL [`GRACE`] later if it is still there. Looked for every [`POLL`] and +/// left alone once gone: the system doesn't give a group's number to another process while the group exists, but +/// may once it is gone, and a SIGKILL sent blindly 3 s later could then hit someone else's group pub fn stop(pid: u32) { let Ok(pgid) = libc::pid_t::try_from(pid) else { return }; if pgid <= 1 { @@ -16,31 +26,60 @@ pub fn stop(pid: u32) { } unsafe { libc::kill(-pgid, libc::SIGTERM) }; tokio::spawn(async move { - tokio::time::sleep(GRACE).await; - unsafe { libc::kill(-pgid, libc::SIGKILL) }; + let deadline = tokio::time::Instant::now() + GRACE; + while tokio::time::Instant::now() < deadline { + if !alive(pgid) { + return; + } + tokio::time::sleep(POLL).await; + } + if alive(pgid) { + unsafe { libc::kill(-pgid, libc::SIGKILL) }; + } }); } +/// Whether the group led by `pid` still has a process in it +pub fn any_left(pid: u32) -> bool { + libc::pid_t::try_from(pid).is_ok_and(|g| g > 1 && alive(g)) +} + /// [`stop`] for several groups, waiting for them here instead of in a task (the program is about to exit, which a /// task wouldn't outlive): SIGTERM to each, then SIGKILL to those still there after [`GRACE`] pub async fn stop_and_wait(leaders: &[u32]) { - let groups: Vec = + let mut groups: Vec = leaders.iter().filter_map(|&p| libc::pid_t::try_from(p).ok()).filter(|&g| g > 1).collect(); for &g in &groups { unsafe { libc::kill(-g, libc::SIGTERM) }; } - let alive = |g: libc::pid_t| unsafe { libc::kill(-g, 0) } == 0; let deadline = tokio::time::Instant::now() + GRACE; - while groups.iter().any(|&g| alive(g)) && tokio::time::Instant::now() < deadline { + loop { + // a group seen gone is dropped at once: its number may go to another group while the others still have time + groups.retain(|&g| alive(g)); + if groups.is_empty() || tokio::time::Instant::now() >= deadline { + break; + } tokio::time::sleep(Duration::from_millis(50)).await; } - for &g in groups.iter().filter(|&&g| alive(g)) { + for &g in &groups { unsafe { libc::kill(-g, libc::SIGKILL) }; } } #[cfg(test)] mod tests { + /// A group is seen while anything of it runs, and not once it is gone (then `stop` sends no SIGKILL) + #[tokio::test] + async fn a_group_is_seen_until_it_is_gone() { + use std::os::unix::process::CommandExt; + let mut leader = std::process::Command::new("sleep").arg("30").process_group(0).spawn().unwrap(); + assert!(super::any_left(leader.id())); + super::stop(leader.id()); + leader.wait().unwrap(); + assert!(!super::any_left(leader.id()), "reaped and gone"); + assert!(!super::any_left(0) && !super::any_left(1), "never this process's own group, or every process"); + } + #[tokio::test] async fn stopping_the_group_stops_what_it_started() { use std::os::unix::process::CommandExt; diff --git a/apps/iphone-control/src/remote.rs b/apps/iphone-control/src/remote.rs index 4eda2d4..9ccc8ed 100644 --- a/apps/iphone-control/src/remote.rs +++ b/apps/iphone-control/src/remote.rs @@ -151,7 +151,9 @@ impl Remote { /// Stops the task (the platform's Ctrl-C); whether the viewer took it pub async fn stop(&self, id: &str) -> bool { - let r = self.post(&format!("/api/agent/tasks/{id}/stop"), &json!({})).send().await; + // Ctrl-C waits for this: a viewer that doesn't answer mustn't keep `task run` from stopping + let r = + self.post(&format!("/api/agent/tasks/{id}/stop"), &json!({})).timeout(Duration::from_secs(10)).send().await; r.is_ok_and(|r| r.status().is_success()) } @@ -241,14 +243,24 @@ impl Events { } continue; } - match self.resp.chunk().await { - Ok(Some(c)) => self.buf.extend_from_slice(&c), + // nothing at all for this long, not even the viewer's ping every 15 s: it is gone; an event that never ends + // (no blank line in a megabyte) isn't one + if self.buf.len() > MAX_EVENT { + return None; + } + match tokio::time::timeout(EVENT_SILENCE, self.resp.chunk()).await { + Ok(Ok(Some(c))) => self.buf.extend_from_slice(&c), _ => return None, } } } } +/// How long a task's event stream may stay silent: the viewer sends a ping every 15 s +const EVENT_SILENCE: Duration = Duration::from_secs(60); +/// The longest event taken: the viewer's are a few kilobytes at most +const MAX_EVENT: usize = 1024 * 1024; + /// Where the first event in `buf` ends, and where the next one starts fn event_end(buf: &[u8]) -> Option<(usize, usize)> { let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| (i, i + 2)); @@ -301,6 +313,38 @@ mod tests { assert_eq!(event_end("data: \"设".as_bytes()), None, "not yet"); } + /// An event that never ends (no blank line in more than a megabyte) ends the stream instead of growing for ever + #[tokio::test] + async fn an_event_without_end_ends_the_stream() { + use tokio::io::AsyncWriteExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut s, _) = listener.accept().await.unwrap(); + let mut head = [0u8; 1024]; + let _ = tokio::io::AsyncReadExt::read(&mut s, &mut head).await; + s.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\nevent: step\ndata: ") + .await + .unwrap(); + let chunk = vec![b'x'; 64 * 1024]; + for _ in 0..32 { + if s.write_all(&chunk).await.is_err() { + break; + } + } + }); + // as `Remote::new` does: a client built without a crypto provider panics, unless another test happened to + // install one first in this process + let _ = rustls::crypto::ring::default_provider().install_default(); + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + let resp = client.get(format!("http://{addr}/")).send().await.unwrap(); + let mut events = Events::new(resp); + let next = tokio::time::timeout(Duration::from_secs(10), events.next_raw()).await.expect("not waited for"); + assert_eq!(next, None); + assert!(events.buf.len() <= MAX_EVENT + 64 * 1024, "{}", events.buf.len()); + server.abort(); + } + #[test] fn the_address_is_the_viewer_s() { let r = Remote::new("https://nas.local:8202/mcp/", None, None).unwrap(); diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs index cfc988b..a88c779 100644 --- a/apps/iphone-control/src/task.rs +++ b/apps/iphone-control/src/task.rs @@ -359,6 +359,14 @@ async fn run_command( _ = term.recv() => stop_here(backend, &opened.id, pid).await, } }; + // the command is gone, but what it started may not be (an MCP server that ignores SIGTERM): stopped right away, + // while the group still holds its number (the leader was just reaped: once the group is empty the number may go + // to another process), and waited for before exiting, as exiting would take the delayed SIGKILL of `stop_group` + // with it. Its grace runs alongside telling the daemon, which unlocks the phone + let leftovers = pid + .and_then(|p| u32::try_from(p).ok()) + .filter(|&p| crate::procgroup::any_left(p)) + .map(|p| tokio::spawn(async move { crate::procgroup::stop_and_wait(&[p]).await })); if !ended { // the command may have ended the task itself (`task finish`); then this changes nothing backend.finish(&opened.token, status.success(), "").await; @@ -368,6 +376,9 @@ async fn run_command( None => backend.state(&opened.id).await.unwrap_or_default(), }; eprintln!("{}", ictl_l10n::trf!("任务 {} 结束:{outcome}", "Task {} ended: {outcome}", opened.id)); + if let Some(h) = leftovers { + let _ = h.await; + } drop(lease); std::process::exit(exit_code(status.code(), &outcome)); } diff --git a/apps/iphone-control/src/video/ffmpeg.rs b/apps/iphone-control/src/video/ffmpeg.rs index 5ee4752..c413f17 100644 --- a/apps/iphone-control/src/video/ffmpeg.rs +++ b/apps/iphone-control/src/video/ffmpeg.rs @@ -444,6 +444,15 @@ pub struct Encoders { picking: tokio::sync::Mutex<()>, } +/// How to turn the phone's HEVC into H.264 ([`Encoders::hevc_command`]) +pub struct HevcCommand { + pub ffmpeg: PathBuf, + pub args: Vec, + pub label: &'static str, + /// The encoder in use, when it is the one ffmpeg runs here (its index, for [`Encoders::give_up`]) + pub encoder: Option, +} + impl Encoders { /// Finds and checks an encoder. `Err`: why the page keeps MJPEG (no ffmpeg, none works, or turned off) pub async fn detect() -> Result, String> { @@ -546,22 +555,20 @@ impl Encoders { /// ffmpeg and its command line for transcoding the phone's own HEVC video with the encoder in use /// ([`hevc_args`]); the native encoder (JPEG only) is replaced by VideoToolbox through ffmpeg. `Err` without /// ffmpeg or a working encoder - pub fn hevc_command( - &self, - points: Option<(f64, f64)>, - qp: u8, - ) -> Result<(PathBuf, Vec, &'static str), String> { + pub fn hevc_command(&self, points: Option<(f64, f64)>, qp: u8) -> Result { let c = self.current().ok_or_else(|| ictl_l10n::tr!("没有可用的编码器", "no working encoder").to_owned())?; let ffmpeg = self.ffmpeg.clone().ok_or_else(|| { ictl_l10n::tr!("没有 ffmpeg,转不了手机的 HEVC 画面", "no ffmpeg to transcode the phone's HEVC picture") .to_owned() })?; - let kind = match &self.list[c.index] { - Kind::Native => &Kind::VideoToolbox, - k => k, + let (kind, stand_in) = match &self.list[c.index] { + Kind::Native => (&Kind::VideoToolbox, true), + k => (k, false), }; let args = hevc_args(kind, points, qp, self.old).ok_or("no encoder for HEVC input")?; - Ok((ffmpeg, args, kind.label())) + // the encoder in use, unless ffmpeg stands in for it (the built-in one takes JPEG only): only then is a failure + // here that encoder's, to give up ([`Self::give_up`]) + Ok(HevcCommand { ffmpeg, args, label: kind.label(), encoder: (!stand_in).then_some(c.index) }) } /// The quantizer set for the picture (`IPHONE_CONTROL_VIEWER_QP`) @@ -697,7 +704,7 @@ async fn native_sample() -> Result, String> { async fn version_line(ffmpeg: &Path) -> Option { let out = tokio::time::timeout( Duration::from_secs(10), - Command::new(ffmpeg).arg("-version").stdin(Stdio::null()).stderr(Stdio::null()).output(), + Command::new(ffmpeg).arg("-version").stdin(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).output(), ) .await .ok()? @@ -714,6 +721,7 @@ async fn sample_jpeg(ffmpeg: &Path) -> Result, String> { .args(["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", &size, "-frames:v", "1"]) .args(["-c:v", "mjpeg", "-pix_fmt", "yuvj420p", "-q:v", "5", "-f", "mjpeg", "pipe:1"]) .stdin(Stdio::null()) + .kill_on_drop(true) .output(), ) .await diff --git a/apps/iphone-control/src/video/transcode.rs b/apps/iphone-control/src/video/transcode.rs index 06e5919..4057bd8 100644 --- a/apps/iphone-control/src/video/transcode.rs +++ b/apps/iphone-control/src/video/transcode.rs @@ -172,6 +172,30 @@ async fn next_packet(t: &mut Option) -> Option, + qp: u8, + failures: &mut usize, +) -> bool { + let Some(index) = cmd.encoder else { return false }; + if !enc.give_up(index).await { + return false; + } + match enc.hevc_command(points, qp) { + Ok(c) => { + *cmd = c; + *failures = 0; + true + } + Err(_) => false, + } +} + /// Sends the phone's video from the daemon's screen stream (`src`, `daemon_w` to ask for keyframes) to `client` as /// H.264, until either ends. `points`: the screen in points (its padding is cut off by it). The HTTP head is already /// sent @@ -184,7 +208,7 @@ pub async fn serve( mut daemon_w: tokio::net::unix::OwnedWriteHalf, client: impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, ) { - let (ffmpeg, args, label) = match enc.hevc_command(points, qp) { + let mut cmd = match enc.hevc_command(points, qp) { Ok(c) => c, Err(e) => { tracing::debug!("no H.264 of the phone's video: {e}"); @@ -219,7 +243,7 @@ pub async fn serve( let mut session: Option = None; // frames out of the current ffmpeg; one that fails before any is not the stream's fault let mut produced = false; - let mut failures = 0; + let mut failures: usize = 0; // stopped: the page is behind or its queue was full; a keyframe and a new ffmpeg once it caught up let mut stopped = false; // when a keyframe was last asked for; asked again every [`ASK_EVERY`] until ffmpeg runs @@ -248,7 +272,7 @@ pub async fn serve( if !key { continue; } - match Transcoder::spawn(&ffmpeg, &args) { + match Transcoder::spawn(&cmd.ffmpeg, &cmd.args) { Ok(t) => { session = Some(t); produced = false; @@ -260,18 +284,33 @@ pub async fn serve( } } let Some(t) = &session else { continue }; - if t.input.try_send(body).is_err() { + match t.input.try_send(body) { + Ok(()) => {} // ffmpeg can't keep up: start over from a keyframe - session = None; - if !ask(&mut daemon_w, &mut asked).await { - return; + Err(mpsc::error::TrySendError::Full(_)) => { + session = None; + if !ask(&mut daemon_w, &mut asked).await { + return; + } + } + // its input is gone: ffmpeg ended, a failure like any other (it was started again for ever) + Err(mpsc::error::TrySendError::Closed(_)) => { + let why = session.take().as_ref().map(Transcoder::error).unwrap_or_default(); + tracing::debug!("HEVC to H.264 ended: {why}"); + failures += 1; + if !produced && failures >= TRIES && !next_encoder(&enc, &mut cmd, points, qp, &mut failures).await { + return; + } + if !ask(&mut daemon_w, &mut asked).await { + return; + } } } } p = next_packet(&mut session) => match p { Some(Ok(Packet::Config(avcc))) => { let size = points.map_or((0, 0), |(w, h)| (w.min(h) as u32, w.max(h) as u32)); - let Some(m) = config_message(&avcc, size, label, &ack_guard.id) else { continue }; + let Some(m) = config_message(&avcc, size, cmd.label, &ack_guard.id) else { continue }; flow.sent(m.len(), Instant::now()); if out_tx.send(m).await.is_err() { return; @@ -300,7 +339,7 @@ pub async fn serve( tracing::debug!("HEVC to H.264 ended: {why}"); session = None; failures += 1; - if !produced && failures >= TRIES { + if !produced && failures >= TRIES && !next_encoder(&enc, &mut cmd, points, qp, &mut failures).await { return; } if !ask(&mut daemon_w, &mut asked).await { diff --git a/apps/iphone-control/web/js/i18n.js b/apps/iphone-control/web/js/i18n.js index c8d25f0..1660617 100644 --- a/apps/iphone-control/web/js/i18n.js +++ b/apps/iphone-control/web/js/i18n.js @@ -10,7 +10,7 @@ const LANG = (() => { return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh'; })(); document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN'; -const EN = {"登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","
键盘
":"
Keyboard
","
  • 打开这一页时会读取已安装的 App。
  • ":"
  • The installed apps are read when this tab opens.
  • ","
  • 正在读取 App 列表…
  • ":"
  • Reading the app list…
  • ","
  • 正在读取元素…
  • ":"
  • Reading elements…
  • ","":"","

    正在连接 iphone-control 服务…

    ":"

    Connecting to the iphone-control service…

    ","演示模式":"Demo","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","原生":"Native","正在准备设备(挂载开发者镜像、连接无障碍服务)…":"Preparing the device (mounting the developer disk image, connecting to the accessibility service)…",":准备设备失败,会自动重试":": preparing the device failed, retrying automatically","开发者镜像、无障碍服务":"Developer disk image, accessibility service","正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。":"Mounting the developer disk image and connecting to the accessibility service, usually a few seconds to half a minute.","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 iphone-control sign,用免费 Apple ID 签名并安装。":"Run iphone-control sign to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。":"Run iphone-control setup --reconfigure, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"}; +const EN = {"和这个任务的事件流断开了,页面不再跟踪它的进度。":"The task's event stream was lost; this page no longer follows its progress.","AI 在等你确认一步操作。要自己操作,先点「接管」。":"The AI is waiting for you to confirm a step. To act yourself, tap “Take over” first.","要先自己看看或改一下,可以接管;问题会一直留着。":"To look or change something first, take over; the question stays.","登录已过期":"Login expired","只读登录":"Read-only login",":能看画面、设备状态和任务,不能操作手机,也不能开始、暂停或确认任务。":": you can watch the picture, the device's state and tasks, but not act on the phone or start, pause or confirm tasks.","只读":"Read-only","只读登录:只能看,不能操作":"Read-only login: you can watch, not act","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","
    键盘
    ":"
    Keyboard
    ","
  • 打开这一页时会读取已安装的 App。
  • ":"
  • The installed apps are read when this tab opens.
  • ","
  • 正在读取 App 列表…
  • ":"
  • Reading the app list…
  • ","
  • 正在读取元素…
  • ":"
  • Reading elements…
  • ","":"","

    正在连接 iphone-control 服务…

    ":"

    Connecting to the iphone-control service…

    ","演示模式":"Demo","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","原生":"Native","正在准备设备(挂载开发者镜像、连接无障碍服务)…":"Preparing the device (mounting the developer disk image, connecting to the accessibility service)…",":准备设备失败,会自动重试":": preparing the device failed, retrying automatically","开发者镜像、无障碍服务":"Developer disk image, accessibility service","正在挂开发者镜像、连接无障碍服务,通常几秒到半分钟。":"Mounting the developer disk image and connecting to the accessibility service, usually a few seconds to half a minute.","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已批准,交还 AI 后继续执行":"Approved; the AI continues when you hand back","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 iphone-control sign,用免费 Apple ID 签名并安装。":"Run iphone-control sign to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 iphone-control setup --reconfigure 选「手机」,在设备上点「信任」。":"Run iphone-control setup --reconfigure, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress","弱网模式":"Low-bandwidth mode","画面流量减少约一半,帧率不变,适合外网或信号差时用;画面动起来时会略糊。手机自己的画面(HEVC)只有一路,开着时所有在看这台手机的页面都会一起降,切换时画面会断开半秒左右。":"About half the picture's traffic at the same frame rate, for use over the internet or a weak signal; moving content gets a little blurry. The phone's own picture (HEVC) is one stream, so while this is on every page watching this phone gets it too, and switching interrupts the picture for about half a second.","已开启弱网模式,正在重新连接画面…":"Low-bandwidth mode on, reconnecting the picture…","已关闭弱网模式,正在重新连接画面…":"Low-bandwidth mode off, reconnecting the picture…"}; Object.assign(EN, { '未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device', '外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large', diff --git a/apps/iphone-control/web/js/layout.js b/apps/iphone-control/web/js/layout.js index 42f99ae..d851a3e 100644 --- a/apps/iphone-control/web/js/layout.js +++ b/apps/iphone-control/web/js/layout.js @@ -299,7 +299,7 @@ const TASKS_KEY = 'ictl.tasks', MAX_TASKS = 50; function serializeTasks(withThumbs) { return JSON.stringify(S.tasks.slice(-MAX_TASKS).map(t => ({ id: t.id, prompt: t.prompt, status: t.status, source: t.source, agent: t.agent, apps: t.apps, startedAt: t.startedAt, endedAt: t.endedAt, summary: t.summary, remoteId: t.remoteId, - steps: t.steps.map(st => ({ id: st.id, n: st.n, thought: st.thought, tool: st.tool, args: st.args, status: st.status, ms: st.ms, result: st.result, confirm: st.confirm })) + steps: t.steps.map(st => ({ id: st.id, n: st.n, thought: st.thought, tool: st.tool, args: st.args, status: st.status, ms: st.ms, result: st.result, confirm: st.confirm, gesture: st.gesture })) }))); } let saveTimer = 0; diff --git a/apps/iphone-control/web/js/screen.js b/apps/iphone-control/web/js/screen.js index 9e7c86d..b950ec9 100644 --- a/apps/iphone-control/web/js/screen.js +++ b/apps/iphone-control/web/js/screen.js @@ -114,7 +114,7 @@ function nudgeGuard() { const g = $('#guard'); g.classList.remove('nudge'); void g.offsetWidth; g.classList.add('nudge'); const t = activeTask(); - show(t && t.status === 'waiting' ? tr('AI 在等你确认一步操作,确认前画面保持锁定。') : tr('AI 正在操作这台设备。要自己操作,先点「接管」。'), 'warn'); + show(t && t.status === 'waiting' ? tr('AI 在等你确认一步操作。要自己操作,先点「接管」。') : tr('AI 正在操作这台设备。要自己操作,先点「接管」。'), 'warn'); } /* 画面外的点夹到屏幕边上(拖动时手指不会离开屏幕) */ function pointsPerPx() { diff --git a/apps/iphone-control/web/js/state.js b/apps/iphone-control/web/js/state.js index c800b3a..552bebb 100644 --- a/apps/iphone-control/web/js/state.js +++ b/apps/iphone-control/web/js/state.js @@ -8,6 +8,8 @@ const TASK_STATUS = { failed: { label: tr('没有完成'), tone: 'danger', icon: 'x' }, stopped: { label: tr('已停止'), tone: 'muted', icon: 'stop' } }; +/* 任务状态的显示;认不出的(新版本服务端多出来的状态)照原样写出来,不至于渲染出错 */ +function taskStatus(s) { return TASK_STATUS[s] || { label: String(s ?? ''), tone: 'muted', icon: 'dot' }; } const STEP_STATUS = { running: { label: tr('执行中'), tone: 'accent', icon: 'loader' }, ok: { label: tr('完成'), tone: 'ok', icon: 'check' }, diff --git a/apps/iphone-control/web/js/tasks.js b/apps/iphone-control/web/js/tasks.js index 6c1d320..7b80bc0 100644 --- a/apps/iphone-control/web/js/tasks.js +++ b/apps/iphone-control/web/js/tasks.js @@ -94,7 +94,9 @@ async function runStep(task, spec) { task.confirmResolve = null; if (task.stopped) throw STOP; if (!ok) { step.status = 'rejected'; step.result = tr('你拒绝了这一步,没有执行。'); finish(task, 'stopped', spec.rejectSummary); throw STOP; } - step.status = 'running'; task.status = 'running'; renderAll(); await sleep(400); + // answered while taken over: the task stays with the user until handed back + step.status = 'running'; if (task.status === 'waiting') task.status = 'running'; renderAll(); await sleep(400); + await gate(task); } const r = spec.exec() || {}; step.ms = performance.now() - t0; step.status = r.error ? 'error' : 'ok'; step.result = r.text; @@ -109,6 +111,8 @@ async function runDemo(task) { } function finish(task, status, summary) { task.status = status; task.endedAt = Date.now(); task.summary = summary; task.es?.close(); + // a step still open when the task ends was cut off (an older daemon doesn't close them all before done) + task.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; }); S.expanded.delete(task.id); // 完成后步骤自动收起,用户可以手动展开 renderAll(); scrollConvo(); show(status === 'success' ? tr('AI 任务已完成') : status === 'failed' ? tr('AI 任务没有完成') : tr('AI 任务已停止'), status === 'failed' ? 'err' : null); @@ -135,16 +139,44 @@ function follow(task, id) { task.remoteId = id; const es = new EventSource(`/api/agent/tasks/${encodeURIComponent(id)}/events`); task.es = es; - es.addEventListener('step', e => { const d = JSON.parse(e.data); upsertStep(task, d); if (d.gesture) { const g = d.gesture; drawMark(g.kind, 'ai', { x: g.x, y: g.y }, g.x2 != null ? { x: g.x2, y: g.y2 } : null); } renderTurns(true); }); + // a step's mark is drawn once: the stream replays the whole task on each (re)connection + const marked = new Set(task.steps.filter(s => s.gesture && s.id != null).map(s => s.id)); + es.addEventListener('step', e => { + const d = JSON.parse(e.data); upsertStep(task, d); + if (d.gesture && !marked.has(d.id)) { marked.add(d.id); const g = d.gesture; drawMark(g.kind, 'ai', { x: g.x, y: g.y }, g.x2 != null ? { x: g.x2, y: g.y2 } : null); } + renderTurns(true); + }); es.addEventListener('confirm', e => { const d = JSON.parse(e.data); upsertStep(task, { id: d.step, status: 'waiting', confirm: d }); task.status = 'waiting'; renderAll(); scrollConvo(); }); - es.addEventListener('state', e => { const d = JSON.parse(e.data); if (ACTIVE.includes(task.status)) { task.status = d.state; renderAll(); } }); + // a state this page doesn't know (a newer daemon's) is left alone: the task keeps the last one it knows + es.addEventListener('state', e => { const d = JSON.parse(e.data); if (ACTIVE.includes(task.status) && ACTIVE.includes(d.state)) { task.status = d.state; renderAll(); } }); es.addEventListener('done', e => { const d = JSON.parse(e.data); finish(task, d.ok ? 'success' : d.stopped ? 'stopped' : 'failed', d.summary || ''); refreshStatusSoon(); }); - es.onerror = () => { if (ACTIVE.includes(task.status)) show(tr('AI 任务的事件流断开了,正在重连…'), 'warn'); }; + es.onerror = () => { + if (!ACTIVE.includes(task.status) || task.es !== es) return; + show(tr('AI 任务的事件流断开了,正在重连…'), 'warn'); + // the browser gave up (an error answer, not a dropped connection): it won't reconnect by itself + if (es.readyState === EventSource.CLOSED) streamClosed(task, id); + }; +} +/* 浏览器不再自动重连的事件流:问服务端这个任务还在不在,在就重新跟上(回放会带来它现在的状态),不在了就标成停止; + * 问不到(服务正在重启)过一会儿再问,几次都不行就不再跟 */ +const REFOLLOW_MS = 3000, REFOLLOW_TRIES = 5; +const LOST_STREAM = () => tr('和这个任务的事件流断开了,页面不再跟踪它的进度。'); +async function streamClosed(task, id, tries = 0) { + await sleep(REFOLLOW_MS); + if (!ACTIVE.includes(task.status) || task.remoteId !== id) return; + let list; + try { list = (await api('/api/agent/tasks')).tasks || []; } + catch { + if (tries + 1 < REFOLLOW_TRIES) return streamClosed(task, id, tries + 1); + lostTask(task, LOST_STREAM()); renderAll(); return; + } + if (list.some(x => x.id === id)) follow(task, id); + else { lostTask(task, LOST_STREAM()); renderAll(); } } /* 页面已经跟不上的任务(守护进程不记得了,或者没连上服务) */ -function lostTask(t) { - t.reattach = false; t.status = 'stopped'; t.endedAt = t.endedAt || Date.now(); - t.summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。'); +function lostTask(t, summary = tr('页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。')) { + t.reattach = false; t.status = 'stopped'; t.endedAt = t.endedAt || Date.now(); t.es?.close(); + t.summary = summary; t.steps.forEach(st => { if (st.status === 'running' || st.status === 'waiting') st.status = 'stopped'; }); } /* 正在进行、但这个页面还没跟着的任务(页面刷新过,或者是在别处开的):接上,事件会从头重放。 @@ -251,18 +283,22 @@ function control(action) { if (action === 'pause') { t.status = 'paused'; show(tr('AI 已暂停')); } if (action === 'resume') { t.status = 'running'; show(tr('AI 继续执行')); } if (action === 'takeover') { t.status = 'takeover'; show(tr('你已接管:现在可以直接在画面上操作。')); } - if (action === 'handback') { t.status = 'running'; t.recheck = true; show(tr('已交还 AI,它会先重新看一遍屏幕')); } + if (action === 'handback') { t.status = pendingConfirm(t) ? 'waiting' : 'running'; t.recheck = true; show(tr('已交还 AI,它会先重新看一遍屏幕')); } renderAll(); } +/* 在等确认的那一步(接管时问题也还留着) */ +function pendingConfirm(t) { return t.steps.find(x => x.status === 'waiting' && x.confirm); } function answerConfirm(approve) { - const t = activeTask(); if (!t || t.status !== 'waiting') return; + const t = activeTask(); if (!t || !(t.status === 'waiting' || (t.status === 'takeover' && pendingConfirm(t)))) return; + const held = t.status === 'takeover'; if (t.source === 'live') { const s = t.steps.find(x => x.status === 'waiting'); liveControl(t, 'confirm', { step: s?.id, approve }); if (s) s.status = approve ? 'running' : 'rejected'; - t.status = 'running'; renderAll(); + if (t.status === 'waiting') t.status = 'running'; + renderAll(); } else t.confirmResolve?.(approve); - show(approve ? tr('已批准,AI 继续执行') : tr('已拒绝这一步')); + show(!approve ? tr('已拒绝这一步') : held ? tr('已批准,交还 AI 后继续执行') : tr('已批准,AI 继续执行')); } function stopTask() { const t = activeTask(); if (!t) return; @@ -348,7 +384,7 @@ function agentLabel(t) { function turnHtml(t) { // the id is the page's own (`t`), but read back from localStorage: escaped like everything else put in HTML const id = esc(t.id); - const st = TASK_STATUS[t.status], active = ACTIVE.includes(t.status), open = S.expanded.has(t.id) || active; + const st = taskStatus(t.status), active = ACTIVE.includes(t.status), open = S.expanded.has(t.id) || active; const busy = !!activeTask(); const actions = active ? '' : S.pendingDelete === t.id ? `` @@ -379,11 +415,12 @@ function renderRunbar() { const btn = (a, l, i, cls = '') => ``; if (!t) { bar.hidden = true; bar.innerHTML = ''; } else { - const st = TASK_STATUS[t.status], b = []; + const st = taskStatus(t.status), b = []; if (t.status === 'running') b.push(btn('pause', tr('暂停'), 'pause'), btn('takeover', tr('接管'), 'cursor')); if (t.status === 'paused') b.push(btn('resume', tr('继续'), 'play', 'btn-primary'), btn('takeover', tr('接管'), 'cursor')); if (t.status === 'takeover') b.push(btn('handback', tr('交还 AI'), 'play', 'btn-primary')); - if (t.status === 'waiting') b.push(btn('goto-confirm', tr('去确认'), 'arrow', 'btn-primary')); + if (t.status === 'waiting' || (t.status === 'takeover' && pendingConfirm(t))) b.push(btn('goto-confirm', tr('去确认'), 'arrow', t.status === 'waiting' ? 'btn-primary' : '')); + if (t.status === 'waiting') b.push(btn('takeover', tr('接管'), 'cursor')); b.push(btn('stop', tr('停止'), 'stop', 'btn-danger')); bar.innerHTML = `${icon(st.icon, st.icon === 'loader' ? 'spin' : '')}${st.label}${mmss(Date.now() - t.startedAt)}${b.join('')}`; bar.hidden = false; @@ -393,7 +430,7 @@ function renderRunbar() { promptEl.placeholder = busy ? tr('当前任务结束后可以发新任务') : tr('想让设备做什么?'); const clear = $('#clear-btn'); clear.hidden = !S.tasks.length || busy; - $('#agent-badge').innerHTML = badge(t ? TASK_STATUS[t.status] : { label: S.mode === 'demo' ? tr('演示模式') : tr('空闲'), tone: S.mode === 'demo' ? 'warn' : 'muted', icon: S.mode === 'demo' ? 'info' : 'dot' }); + $('#agent-badge').innerHTML = badge(t ? taskStatus(t.status) : { label: S.mode === 'demo' ? tr('演示模式') : tr('空闲'), tone: S.mode === 'demo' ? 'warn' : 'muted', icon: S.mode === 'demo' ? 'info' : 'dot' }); } function renderGuard() { const t = activeTask(), g = $('#guard'); @@ -410,7 +447,7 @@ function renderGuard() { const cfg = { running: { tone: 'accent', ic: 'loader', title: ext ? tr('外部任务正在操作这台设备') : tr('AI 正在操作这台设备'), sub: ext ? tr('手动操作已锁定,避免和它同时点击。') : tr('手动操作已锁定,避免和 AI 同时点击。'), btns: [['takeover', tr('接管'), 'cursor']] }, paused: { tone: 'warn', ic: 'pause', title: ext ? tr('外部任务已暂停') : tr('AI 已暂停'), sub: ext ? tr('画面仍为这个任务保留,要自己操作先接管。') : tr('画面仍为 AI 保留,要自己操作先接管。'), btns: [['resume', tr('继续'), 'play'], ['takeover', tr('接管'), 'cursor']] }, - waiting: { tone: 'warn', ic: 'alert', title: ext ? tr('外部任务在等你确认一步操作') : tr('AI 在等你确认一步操作'), sub: tr('确认前画面保持锁定。'), btns: [['goto-confirm', tr('去确认'), 'arrow']] }, + waiting: { tone: 'warn', ic: 'alert', title: ext ? tr('外部任务在等你确认一步操作') : tr('AI 在等你确认一步操作'), sub: tr('要先自己看看或改一下,可以接管;问题会一直留着。'), btns: [['goto-confirm', tr('去确认'), 'arrow'], ['takeover', tr('接管'), 'cursor']] }, takeover: { tone: 'user', ic: 'cursor', title: tr('你在接管'), sub: tr('AI 已暂停。交还后它会先重新看一遍屏幕。'), btns: [['handback', tr('交还 AI'), 'play']] } }[t.status]; g.className = `guard glass tone-${cfg.tone}`; @@ -429,7 +466,7 @@ function renderManual() { pickerSync.device(); $$('#nav-devices button').forEach(row => { row.disabled = lock || S.switching || !!S.devicesFixed; }); const t = activeTask(); - $('#vt-agent-label').textContent = t ? `AI · ${{ running: tr('执行中'), waiting: tr('待确认'), paused: tr('已暂停'), takeover: tr('接管中') }[t.status]}` : tr('AI 助手'); + $('#vt-agent-label').textContent = t ? `AI · ${{ running: tr('执行中'), waiting: tr('待确认'), paused: tr('已暂停'), takeover: tr('接管中') }[t.status] ?? taskStatus(t.status).label}` : tr('AI 助手'); } /* 系统弹窗(权限请求之类):手机自己的视频里可能看不到(定位授权弹窗只剩变暗的屏幕),画面用它时问守护进程有没有,有就在 * 画面上方显示弹窗的文字和按钮。点按钮是按坐标点手机上的那个按钮:按名字点会把「允许」点到「不允许」上。 diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 9b991ae..19c8266 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -931,6 +931,17 @@ impl Daemon { self.snap.borrow().device.as_ref().map(|d| d.udid.clone()).filter(|u| !u.is_empty()) } + /// Returns once the daemon no longer controls `udid` (another device was selected, or this one went away) + pub(crate) async fn controlled_changes_from(&self, udid: &str) { + let mut snap = self.snap.subscribe(); + loop { + let now = snap.borrow_and_update().device.as_ref().map(|d| d.udid.clone()).filter(|u| !u.is_empty()); + if !now.is_some_and(|u| u.eq_ignore_ascii_case(udid)) || snap.changed().await.is_err() { + return; + } + } + } + /// Tests: pretend the daemon controls `udid` #[cfg(test)] pub(crate) fn fake_controlled(&self, udid: &str) { diff --git a/crates/ictl-daemon/src/doctor.rs b/crates/ictl-daemon/src/doctor.rs index 1041c11..273e4aa 100644 --- a/crates/ictl-daemon/src/doctor.rs +++ b/crates/ictl-daemon/src/doctor.rs @@ -330,7 +330,12 @@ async fn viewer_picture() -> String { } let mut version = None; for p in crate::config::ffmpeg_paths() { - let run = tokio::process::Command::new(&p).arg("-version").stdin(std::process::Stdio::null()).output(); + // killed if it doesn't answer in time (the timeout drops it; without this it would run on) + let run = tokio::process::Command::new(&p) + .arg("-version") + .stdin(std::process::Stdio::null()) + .kill_on_drop(true) + .output(); if let Ok(Ok(o)) = tokio::time::timeout(Duration::from_secs(5), run).await && o.status.success() { diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs index e4c5abe..3607c17 100644 --- a/crates/ictl-daemon/src/lib.rs +++ b/crates/ictl-daemon/src/lib.rs @@ -48,9 +48,16 @@ const MAX_REQUEST_LINE: u64 = 1024 * 1024; pub async fn run(cfg: Config) -> anyhow::Result<()> { cfg.prepare_dirs()?; let socket = cfg.socket.clone(); - if let Some(dir) = socket.parent() { - std::fs::create_dir_all(dir)?; + if let Some(dir) = socket.parent() + && !dir.exists() + { + // made here: this user's alone (a directory that was there, such as /tmp, is left as it is) + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; } + // one daemon per socket, for as long as it runs: two started at once both found no one answering and bound in + // turn, the second taking the socket from the first + let _instance = single_instance(&socket, INSTANCE_WAIT).await?; // 已有守护进程在用这个 socket 就退出:两个守护进程会争 usbmuxd、WDA 和 HID if tokio::net::UnixStream::connect(&socket).await.is_ok() { bail!( @@ -59,7 +66,11 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> { ); } let _ = std::fs::remove_file(&socket); - let listener = tokio::net::UnixListener::bind(&socket)?; + // created 0600 from the start (the umask for the bind alone): set afterwards, others could connect in between + let old = unsafe { libc::umask(0o077) }; + let bound = tokio::net::UnixListener::bind(&socket); + unsafe { libc::umask(old) }; + let listener = bound?; { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?; @@ -73,6 +84,43 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> { r } +/// How long a starting daemon waits for the one before it to let go of the socket (it may still be stopping) +const INSTANCE_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// The lock beside the socket (`ctl.lock`), held while the daemon runs; waits up to `wait` for another daemon that is +/// stopping, and gives up at once when one answers on the socket +async fn single_instance(socket: &std::path::Path, wait: std::time::Duration) -> anyhow::Result { + use std::os::fd::AsRawFd; + use std::os::unix::fs::OpenOptionsExt; + let path = socket.with_extension("lock"); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&path)?; + let deadline = Instant::now() + wait; + loop { + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + return Ok(file); + } + // held by another daemon (or interrupted): wait for it below. Anything else (a file system without flock) + // won't change by waiting, and isn't another daemon + let e = std::io::Error::last_os_error(); + if !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted) { + return Err(anyhow::Error::new(e).context(path.display().to_string())); + } + let running = + || ictl_l10n::trf!("已经有守护进程在运行({})", "A daemon is already running ({})", socket.display()); + if tokio::net::UnixStream::connect(socket).await.is_ok() || Instant::now() >= deadline { + bail!("{}", running()); + } + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } +} + /// A supervision round asked for that couldn't take the device is asked for again this much later const RETRY_ROUND: std::time::Duration = std::time::Duration::from_millis(200); /// Clients served at once on the control socket; more wait in its queue @@ -332,11 +380,14 @@ async fn task_stream( for e in &log { ok = ok && send(&mut w, e).await; } + // events sent so far: the task's log is complete, so a reader that fell behind catches up from it + let mut sent = log.len(); if ok && !ended { loop { tokio::select! { e = rx.recv() => match e { Ok(e) => { + sent += 1; let done = e.event == "done"; if !send(&mut w, &e).await { break; @@ -345,7 +396,25 @@ async fn task_stream( return; } } - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + // fell behind and missed some, maybe `done` (then nothing more would come, and the connection would + // stay open for good): what was missed comes from the log, then events again from there + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + let (log, again, ended) = task.subscribe(); + for e in log.iter().skip(sent) { + if !send(&mut w, e).await { + ok = false; + break; + } + } + sent = sent.max(log.len()); + rx = again; + if !ok { + break; + } + if ended { + return; + } + } Err(tokio::sync::broadcast::error::RecvError::Closed) => return, }, () = wait_closed(&mut reader) => break, @@ -440,6 +509,62 @@ mod tests { .await; } + /// A follower that falls behind (its socket full while thousands of events go by) still gets every event and + /// `done`: before, the missed `done` left it open for good + #[tokio::test] + async fn a_follower_that_fell_behind_catches_up_and_ends() { + use tokio::io::AsyncBufReadExt; + let local = tokio::task::LocalSet::new(); + local + .run_until(async { + let (d, dir) = core::tests::test_daemon("lagged"); + let t = d.tasks.open("x", "test", Some("phone"), Vec::new(), None).unwrap(); + let (ours, theirs) = tokio::net::UnixStream::pair().unwrap(); + let (r, w) = ours.into_split(); + let (daemon, id) = (d.clone(), t.id.clone()); + let follow = tokio::task::spawn_local(async move { + task_stream(&daemon, BufReader::new(r), w, protocol::Request::TaskEvents { id }, None).await + }); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + // more than the channel holds, while nobody reads the socket + for _ in 0..3000 { + t.control_as_user("pause").unwrap(); + t.control_as_user("resume").unwrap(); + } + t.end(tasks::End::Cancelled, "stopped"); + let mut lines = tokio::io::BufReader::new(theirs).lines(); + let mut got = Vec::new(); + while let Ok(Ok(Some(l))) = + tokio::time::timeout(std::time::Duration::from_secs(10), lines.next_line()).await + { + got.push(l); + } + tokio::time::timeout(std::time::Duration::from_secs(5), follow) + .await + .expect("the stream ended") + .unwrap(); + let (log, _, _) = t.subscribe(); + assert_eq!(got.len(), 1 + log.len(), "the answer line, then every event once"); + assert!(got.last().unwrap().contains("\"done\""), "{}", got.last().unwrap()); + std::fs::remove_dir_all(dir).unwrap(); + }) + .await; + } + + /// One daemon per socket: a second is refused while the first holds the lock, and gets it once that one is gone + #[tokio::test] + async fn only_one_daemon_holds_a_socket() { + let dir = std::env::temp_dir().join(format!("ictl-instance-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let socket = dir.join("ctl.sock"); + let first = single_instance(&socket, std::time::Duration::ZERO).await.unwrap(); + let e = single_instance(&socket, std::time::Duration::from_millis(300)).await.unwrap_err(); + assert!(e.to_string().contains("running") || e.to_string().contains("运行"), "{e}"); + drop(first); + assert!(single_instance(&socket, std::time::Duration::ZERO).await.is_ok(), "free again"); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn request_options_are_taken_out_before_parsing() { use ictl_l10n::Lang; diff --git a/crates/ictl-daemon/src/mjpeg.rs b/crates/ictl-daemon/src/mjpeg.rs index 73927c9..4ac1005 100644 --- a/crates/ictl-daemon/src/mjpeg.rs +++ b/crates/ictl-daemon/src/mjpeg.rs @@ -27,7 +27,7 @@ pub(crate) async fn stream( mut w: OwnedWriteHalf, expect_udid: Option, ) { - let phone = match tokio::time::timeout(OPEN_TIMEOUT, open(d, expect_udid.as_deref())).await { + let (phone, udid) = match tokio::time::timeout(OPEN_TIMEOUT, open(d, expect_udid.as_deref())).await { Ok(Ok(p)) => p, Ok(Err(e)) => return answer(&mut w, Response::error(e)).await, Err(_) => { @@ -40,7 +40,8 @@ pub(crate) async fn stream( if w.write_all(line.as_bytes()).await.is_err() { return; } - relay(phone, reader, w).await; + // ends when the daemon switches to another device: the page then asks for that one's picture + relay(phone, reader, w, d.controlled_changes_from(&udid)).await; } async fn answer(w: &mut OwnedWriteHalf, r: Response) { @@ -50,7 +51,7 @@ async fn answer(w: &mut OwnedWriteHalf, r: Response) { } /// The controlled phone's MJPEG stream, asked for: the device the page shows (`expect_udid`) or else none -async fn open(d: &Daemon, expect_udid: Option<&str>) -> Result { +async fn open(d: &Daemon, expect_udid: Option<&str>) -> Result<(impl AsyncRead + AsyncWrite + Unpin, String), String> { let udid = d.controlled_udid().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?; if expect_udid.is_some_and(|u| !u.eq_ignore_ascii_case(&udid)) { return Err(ictl_l10n::tr!("正在控制的设备变了", "The controlled device changed").into()); @@ -58,18 +59,21 @@ async fn open(d: &Daemon, expect_udid: Option<&str>) -> Result, ) { let (mut from_phone, _to_phone) = tokio::io::split(phone); tokio::select! { + () = until => {} _ = tokio::io::copy(&mut from_phone, &mut client_w) => {} _ = async { let mut b = [0u8; 64]; @@ -89,7 +93,7 @@ mod tests { let (mut phone, phone_end) = tokio::io::duplex(1024); let (client, mut page) = tokio::io::duplex(1024); let (client_r, client_w) = tokio::io::split(client); - let relayed = tokio::spawn(relay(phone_end, client_r, client_w)); + let relayed = tokio::spawn(relay(phone_end, client_r, client_w, std::future::pending())); let part = b"HTTP/1.1 200 OK\r\n\r\n--wda\r\nContent-Length: 4\r\n\r\n\xff\xd8\xff\xd9\r\n"; phone.write_all(part).await.unwrap(); let mut got = vec![0u8; part.len()]; @@ -100,6 +104,22 @@ mod tests { assert_eq!(phone.read(&mut [0]).await.unwrap(), 0, "the phone's side is closed"); } + /// The daemon switching to another device ends the relay (the page asks again, for the new one) + #[tokio::test] + async fn a_switch_to_another_device_ends_the_stream() { + let (d, dir) = crate::core::tests::test_daemon("mjpeg-switch"); + d.fake_controlled("phone"); + let (_phone, phone_end) = tokio::io::duplex(1024); + let (client, _page) = tokio::io::duplex(1024); + let (client_r, client_w) = tokio::io::split(client); + let relayed = relay(phone_end, client_r, client_w, d.controlled_changes_from("phone")); + tokio::pin!(relayed); + assert!(tokio::time::timeout(Duration::from_millis(50), &mut relayed).await.is_err(), "same device: goes on"); + d.fake_controlled("tablet"); + tokio::time::timeout(Duration::from_secs(1), relayed).await.expect("ended by the switch"); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Asked for a device the daemon doesn't control (the page hasn't noticed a switch): refused, nothing opened #[tokio::test] async fn another_device_than_the_controlled_one_is_refused() { diff --git a/crates/ictl-daemon/src/screen.rs b/crates/ictl-daemon/src/screen.rs index dd9530c..4f22fed 100644 --- a/crates/ictl-daemon/src/screen.rs +++ b/crates/ictl-daemon/src/screen.rs @@ -59,7 +59,10 @@ struct Viewer(Arc, bool); impl Drop for Viewer { fn drop(&mut self) { let (d, low) = (self.0.clone(), self.1); - tokio::spawn(async move { + // on the daemon's LocalSet like the connection it ends (`screen_stream`, the only place a Viewer is made): a task + // of the runtime's own outlived the LocalSet when the daemon stopped, and could close the HID session again + // after `Daemon::shutdown` + tokio::task::spawn_local(async move { let mut g = d.inner.lock().await; g.screen_viewers = g.screen_viewers.saturating_sub(1); if low { diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs index 313ff01..e0cdefc 100644 --- a/crates/ictl-daemon/src/tasks.rs +++ b/crates/ictl-daemon/src/tasks.rs @@ -94,6 +94,9 @@ struct TaskState { thought: Option, /// The latest step: id, when it started, still running, has a thought last: Option<(u64, Instant, bool, bool)>, + /// Steps started and not yet finished, oldest first: a tool call and the question it asks are both under way, + /// and so are calls an agent makes at once. The task's end stops them all + in_flight: Vec, /// Steps whose tool taps by text: where it tapped comes with the result taps_by_text: Vec, /// The screen may have changed under the agent (the user acted, or handed back): look before acting @@ -378,6 +381,10 @@ impl Task { } fn emit(&self, st: &mut TaskState, name: &str, data: Value) { + // `done` is the last event: readers stop at it (the page, `task events`), and a log replayed later ends there + if !st.status.active() && name != "done" { + return; + } let e = TaskEvent { event: name.into(), data }; if let Some(f) = &self.file { append(f, &e); @@ -408,6 +415,11 @@ impl Task { if !st.status.active() { return false; } + // the steps under way end with the task, said before `done` (nothing is written after it) + st.last = None; + for id in std::mem::take(&mut st.in_flight) { + self.emit(&mut st, "step", json!({"id": id, "status": "stopped"})); + } st.status = Status::Ended(end); st.ended = Some(now_ms()); if let Some((_, tx)) = st.confirm.take() { @@ -480,6 +492,7 @@ impl Task { st.next_step += 1; let thought = st.thought.take(); st.last = Some((id, Instant::now(), true, thought.is_some())); + st.in_flight.push(id); let mut d = json!({"id": id, "tool": tool, "args": args, "status": status}); if let Some(t) = thought { d["thought"] = t.into(); @@ -515,6 +528,7 @@ impl Task { { st.last = Some((last, at, false, th)); } + st.in_flight.retain(|&s| s != id); // the user said no to going outside the scope: that's a choice, not something that went wrong let declined = st.declined.iter().position(|&s| s == id).map(|i| st.declined.swap_remove(i)).is_some(); let status = match (ok, declined) { @@ -566,6 +580,7 @@ impl Task { }; let mut st = self.lock(); st.last = None; + st.in_flight.retain(|&s| s != id); let ended = !st.status.active(); let (asked, status, result) = match (answer, ended) { (_, true) => (Asked::Ended, "stopped", ictl_l10n::tr!("任务已停止。", "The task was stopped.")), @@ -706,12 +721,17 @@ impl Task { match (action, st.status) { ("pause", Status::Running) => self.set_status(&mut st, Status::Paused), ("resume", Status::Paused) => self.set_status(&mut st, Status::Running), - ("takeover", Status::Running | Status::Paused) => self.set_status(&mut st, Status::Takeover), + // also while a step waits for the user: they may want to look or change something before answering; the + // question stays, to be answered under takeover or after handing back + ("takeover", Status::Running | Status::Paused | Status::Waiting) => { + self.set_status(&mut st, Status::Takeover) + } ("handback", Status::Takeover) => { st.recheck = true; - self.set_status(&mut st, Status::Running); + let back = if st.confirm.is_some() { Status::Waiting } else { Status::Running }; + self.set_status(&mut st, back); } - ("confirm", Status::Waiting) => match st.confirm.take() { + ("confirm", Status::Waiting | Status::Takeover) => match st.confirm.take() { Some((waiting, tx)) if step.is_none_or(|s| s == waiting) => { what["step"] = json!(waiting); what["approve"] = json!(approve); @@ -848,6 +868,7 @@ impl Tasks { next_step: 1, thought: None, last: None, + in_flight: Vec::new(), taps_by_text: Vec::new(), recheck: false, confirm: None, @@ -1150,6 +1171,7 @@ fn restore(file: &Path) -> Option { next_step: steps.unwrap_or(0) + 1, thought: None, last: None, + in_flight: Vec::new(), taps_by_text: Vec::new(), recheck: false, confirm: None, @@ -1523,6 +1545,87 @@ mod tests { assert_eq!(t.info().state, "running"); } + /// `done` is the last event: a step under way is stopped before it, and nothing that comes after is written + #[tokio::test] + async fn nothing_follows_done() { + let ts = Arc::new(tasks()); + let t = open(&ts); + let asked = ask(&ts, &t); + tokio::time::sleep(Duration::from_millis(20)).await; + t.end(End::Cancelled, "stopped"); + let _ = asked.await.unwrap(); + t.observed(); + let (log, _, ended) = t.subscribe(); + assert!(ended); + let names: Vec<&str> = log.iter().map(|e| e.event.as_str()).collect(); + assert_eq!(names.last(), Some(&"done"), "{names:?}"); + let stopped = &log[log.len() - 2]; + assert_eq!((stopped.event.as_str(), stopped.data["status"].as_str()), ("step", Some("stopped"))); + } + + /// A tool call asking to leave the task's scope is two steps under way (the call, and the question); one the + /// agent made alongside is a third. Stopping the task ends them all before `done`, and the call's result coming in + /// after it is not written + #[tokio::test] + async fn every_step_under_way_is_stopped_before_done() { + let ts = Arc::new(tasks()); + let t = ts.open("改设置", "test", Some(PHONE), scope(&["com.apple.Preferences"]), None).unwrap(); + let req = |tool: &str| Request::TaskStep { tool: tool.into(), args: json!({}) }; + let r = ts.handle(&req("iphone_screenshot"), Some(&t.token), None, &mut None).await; + assert_eq!(r, Some(Response::text("1"))); + let r = ts.handle(&req("iphone_launch_app"), Some(&t.token), None, &mut None).await; + assert_eq!(r, Some(Response::text("2"))); + let asking = { + let t = t.clone(); + tokio::spawn(async move { + t.check_scope(&Target::Launch("com.apple.MobileSMS".into()), Some(2), &mut None).await + }) + }; + while t.info().state != "waiting" { + tokio::time::sleep(Duration::from_millis(5)).await; + } + t.end(End::Cancelled, "stopped"); + assert!(asking.await.unwrap().is_err()); + t.step_done(2, false, 5, "refused", None); + t.step_done(1, true, 5, "late", None); + let (log, _, _) = t.subscribe(); + assert_eq!(log.last().map(|e| e.event.as_str()), Some("done")); + let last_status = |id: u64| { + log.iter().rev().find(|e| e.event == "step" && e.data["id"] == id).map(|e| e.data["status"].clone()) + }; + for id in 1..=3 { + assert_eq!(last_status(id), Some(json!("stopped")), "step {id}: {log:?}"); + } + } + + /// While a step waits for the user, they can take over (to look or change something first): the question stays, + /// answered under takeover (the task stays with the user) or after handing back (it waits again) + #[tokio::test] + async fn the_user_can_take_over_while_a_step_waits_for_them() { + let ts = Arc::new(tasks()); + let t = open(&ts); + let asked = ask(&ts, &t); + tokio::time::sleep(Duration::from_millis(20)).await; + assert_eq!(t.info().state, "waiting"); + t.control("takeover", None, false, None).unwrap(); + assert_eq!(t.info().state, "takeover"); + assert!(matches!(admit(&ts, &tap(), None).await, Ok((Admission::Supervisor(_), _)))); + t.control("confirm", None, true, None).unwrap(); + assert!(matches!(asked.await.unwrap(), Response::Text { .. })); + assert_eq!(t.info().state, "takeover", "answered, but still the user's until handed back"); + t.control("handback", None, false, None).unwrap(); + assert_eq!(t.info().state, "running"); + + // handed back before answering: the question is still there + let asked = ask(&ts, &t); + tokio::time::sleep(Duration::from_millis(20)).await; + t.control("takeover", None, false, None).unwrap(); + t.control("handback", None, false, None).unwrap(); + assert_eq!(t.info().state, "waiting"); + t.control("confirm", None, false, None).unwrap(); + assert!(matches!(asked.await.unwrap(), Response::Error { .. }), "rejected"); + } + /// Two questions at once are asked one after the other, each answered on its own #[tokio::test] async fn two_questions_at_once_are_asked_in_turn() { diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index d2f7bd4..b0eb756 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -211,3 +211,11 @@ | 205 | `Touch` 的 `Prepare`(控制台在手指按下前先开 HID 会话)算作设备操作:任务进行中被拒,接管时被当成用户在操作,还会清掉元素缓存、让后台检查等着 | `is_device_action` 对 `Prepare` 返回 false;手指抬起成功后才清 `touch_rotation`(参数被拒的抬起后手指还能抬起) | 单测 `getting_ready_for_a_touch_is_not_acting`、`others_may_look_but_not_act_until_the_user_takes_over` + 真机 | | 206 | `ScrollCollect` 带 `deny_unknown_fields`:所有请求共用的顶层键(`lang`、`watched`……)和它的字段在同一层,新客户端加一个新键,旧守护进程就只拒这一种请求 | 去掉 `deny_unknown_fields`,和其他请求一样忽略不认识的字段;字段类型不对仍报错 | 单测 `raw_scroll_collect_validates_scope_and_bounds`(原来断言未知字段报错,改成断言被忽略:这是有意放宽) | | 207 | 存的锁屏密码只查是不是纯数字,手改成不足 4 位也照用(输入逻辑以至少 4 位为前提);`Persisted::save` 序列化失败时写入空文件替换 `state.json`;`NotifyConfig` 派生 `Debug`,打印配置会带出通知密钥 | 不足 4 位报 `NotDigits`;序列化失败什么都不写;`NotifyConfig` 手写 `Debug`,密钥只显示有没有设 | 单测 `notification_keys_stay_out_of_debug_output`、`missing_or_non_digit_passcode`(加了 3 位的情况) | +| 208 | 任务在等用户确认(`waiting`)时不能接管:用户想先看看或改一下再回答,只能先答 | 等确认时也能接管;问题留着,接管时可以回答(答完仍是接管,交还后才继续),交还时还没答就回到等确认;页面在等确认时多一个「接管」,接管时还有「去确认」 | 单测 `the_user_can_take_over_while_a_step_waits_for_them`、页面测试 `a step waiting for the user can be answered after taking over` + 真机 | +| 209 | 任务结束(`done`)之后还会写 `step` 等事件(还在等的提问被叫醒、执行中的请求做完):日志和回放在 `done` 之后还有东西;订阅者落后(`Lagged`)可能刚好错过 `done`,广播通道又不会关,连接永远挂着 | 结束时先把所有进行中的步骤(`in_flight`:越出范围的工具调用和它的提问、并发的调用)记为 stopped 再发 `done`,之后什么都不写;页面收到 `done` 时也把残留的执行中、等确认的步骤收成停止;落后时从任务日志补发错过的事件再接着订阅 | 单测 `nothing_follows_done`、`every_step_under_way_is_stopped_before_done`、`a_follower_that_fell_behind_catches_up_and_ends`(改回旧代码会失败)、页面测试 `steps still open when a task ends are stopped` | +| 210 | 控制台任务事件流被浏览器彻底关掉(404、401)后页面一直停在「执行中」;每次重连回放整个任务,以前的手势标记全部重画;不认识的状态 `TASK_STATUS[...]` 取到 undefined | 关掉后问服务端:任务还在就重新跟上,没了就标成停止,问不到重试 5 次;标记按步骤只画一次(刷新前已有的不画:存到本地的步骤带着 `gesture`);不认识的状态原样显示、不覆盖已知的 | 页面测试 `a stream the browser gave up on is followed again if the task is still there, else marked stopped`、`a step mark is drawn once however often the stream replays it`、`a mark drawn before a reload is not drawn again after it`、`an unknown task state is shown as it is and does not replace a known one` | +| 211 | 停进程组:SIGTERM 后 3 秒盲发 `kill(-pgid, SIGKILL)`,组早就没了、组号被复用时会杀错;`task run` 在命令退出后立刻 `exit`,延迟的 SIGKILL 随之失效,不理 SIGTERM 的后台进程留下;`doctor`、ffmpeg 的带超时命令超时后进程还在 | 等的时候每 100 毫秒看一次,组没了就不再发(停几个组时,先没了的那个立刻移出,不跟着别的组等满 3 秒);`task run` 在命令退出(领头进程刚被回收)后立刻看组里还有没有进程,有就马上停,宽限期和通知守护进程同时进行,退出前等它们;超时的命令加 `kill_on_drop` | 单测 `a_group_is_seen_until_it_is_gone`、原有的 `stopping_the_group_stops_what_it_started` + 真机 | +| 212 | 守护进程中转 WDA 的 MJPEG 时不管设备切换:切到另一台后旧手机的画面一直在转;`Viewer::drop` 用 `tokio::spawn`,脱离 LocalSet,停机后还可能再关一次 HID | 中转时盯着正在控制的设备,变了就结束;`Viewer::drop` 改用 `spawn_local` | 单测 `a_switch_to_another_device_ends_the_stream` + 真机 | +| 213 | 原生 HEVC 转 H.264:ffmpeg 崩了导致输入通道关闭(`try_send` 的 `Closed`)被当成「跟不上」,不计失败、无限重启;连续失败也不换编码器 | `Closed` 记一次失败;连续 3 次没出帧就像 MJPEG 一样 `give_up` 换下一个编码器(只有 ffmpeg 替内置编码器跑时不换,那不是它的问题) | 代码审查(单测需要真编码器;真机上没有能让 ffmpeg 崩的条件) | +| 214 | `task run --url`:Ctrl-C 时 `stop()` 没有超时,控制台不应答就一直等;SSE 读取没有静默超时,缓冲没有上限 | `stop()` 限时 10 秒;60 秒什么都没收到(控制台每 15 秒发 ping)就当断开;一个事件超过 1 MB 还没结束就放弃 | 单测 `an_event_without_end_ends_the_stream` | +| 215 | 守护进程只靠「连不上 socket」判断没有别的实例:两个同时启动都连不上,先后 bind,后一个把前一个的 socket 抢走;bind 和 chmod 0600 之间 socket 是 umask 的权限 | socket 旁边的 `ctl.lock` 加 `flock`,守护进程一直拿着(等前一个最多 15 秒,有人在服务就立即退出;`flock` 报的不是「被占用」或「被打断」就直接报错,不白等);bind 时 umask 077;自己新建的 socket 目录是 0700 | 单测 `only_one_daemon_holds_a_socket` + 真机 | diff --git a/tests/viewer/summary.test.mjs b/tests/viewer/summary.test.mjs index 6393603..b372998 100644 --- a/tests/viewer/summary.test.mjs +++ b/tests/viewer/summary.test.mjs @@ -53,6 +53,7 @@ test('a task id from storage stays inside its attributes', () => { const fns = [/^const esc = .*$/m, /^function turnHtml\([^]*?^}/m].map(pick).join('\n'); const ctx = { TASK_STATUS: { done: { tone: 'ok', icon: 'check', label: 'done' } }, ACTIVE: ['running'], BUILTIN_AGENTS: {}, + taskStatus: s => ({ done: { tone: 'ok', icon: 'check', label: 'done' } })[s], S: { expanded: new Set(), pendingDelete: null, agents: [] }, activeTask: () => null, isExternal: () => false, icon: () => '', tr: String, hhmm: () => '00:00', mmss: () => '0:00', badge: () => '', mdLite: String, agentLabel: () => 'AI', scopeText: () => '', stepHtml: () => '
  • ', diff --git a/tests/viewer/tasks.test.mjs b/tests/viewer/tasks.test.mjs index b193022..86c1181 100644 --- a/tests/viewer/tasks.test.mjs +++ b/tests/viewer/tasks.test.mjs @@ -109,3 +109,117 @@ test('a task list from the info poll is used as it is', async () => { assert.deepEqual(followed.map(([, id]) => id), ['xyz']); assert.equal(wantsTasks(), false, 'following one now: the poll stops asking'); }); + +// While a step waits for the user they can take over first; the question stays and can be answered then or after +test('a step waiting for the user can be answered after taking over', () => { + const step = { id: 3, status: 'waiting', confirm: { action: '发送消息' } }; + const t = { id: 't1', source: 'live', status: 'waiting', steps: [{ id: 1, status: 'ok' }, step] }; + const S = { tasks: [t] }, sent = [], shown = []; + const context = { + S, ACTIVE, tr: String, renderAll: noop, show: m => shown.push(m), + activeTask: () => S.tasks.find(x => ACTIVE.includes(x.status)), + liveControl: (task, action, body) => sent.push([action, body]), + }; + const { control, answerConfirm } = handlers(['pendingConfirm', 'control', 'answerConfirm'], context); + control('takeover'); + assert.equal(t.status, 'takeover'); + control('handback'); + assert.equal(t.status, 'waiting', 'handed back with the question unanswered: waiting again'); + control('takeover'); + answerConfirm(true); + assert.equal(JSON.stringify(sent.at(-1)), JSON.stringify(['confirm', { step: 3, approve: true }])); + assert.equal(step.status, 'running'); + assert.equal(t.status, 'takeover', 'answered, but still the user\'s until handed back'); + assert.equal(shown.at(-1), '已批准,交还 AI 后继续执行', 'says it goes on only once handed back'); + control('handback'); + assert.equal(t.status, 'running'); +}); + +// The event stream replays the whole task on each connection: a step's mark is drawn once, not again on reconnecting +function streams() { + const made = []; + class FakeES { + static CLOSED = 2; + constructor(url) { this.url = url; this.on = {}; this.readyState = 0; made.push(this); } + addEventListener(name, f) { this.on[name] = f; } + close() { this.readyState = 2; } + emit(name, data) { this.on[name]({ data: JSON.stringify(data) }); } + } + return { made, FakeES }; +} + +test('a step mark is drawn once however often the stream replays it', () => { + const { made, FakeES } = streams(); + const marks = []; + const task = { id: 't1', status: 'running', steps: [] }; + const context = { ACTIVE, EventSource: FakeES, tr: String, show: noop, renderAll: noop, renderTurns: noop, scrollConvo: noop, refreshStatusSoon: noop, + drawMark: (...a) => marks.push(a), finish: noop, streamClosed: noop }; + const { follow } = handlers(['upsertStep', 'follow'], context); + const tap = { id: 1, tool: 'iphone_tap', status: 'running', gesture: { kind: 'tap', x: 1, y: 2 } }; + follow(task, 'abc'); + made[0].emit('step', tap); + follow(task, 'abc'); // reconnected: the same step replayed + made[1].emit('step', tap); + made[1].emit('step', { ...tap, id: 2 }); + assert.equal(marks.length, 2, 'step 1 once, step 2 once'); +}); + +// The steps saved before a reload keep their gestures, so the replayed stream doesn't draw them again +test('a mark drawn before a reload is not drawn again after it', () => { + const { made, FakeES } = streams(); + const marks = []; + const S = { tasks: [{ id: 't1', status: 'running', remoteId: 'abc', steps: [] }] }; + const context = { S, MAX_TASKS: 50, ACTIVE, EventSource: FakeES, tr: String, show: noop, renderAll: noop, renderTurns: noop, scrollConvo: noop, + refreshStatusSoon: noop, drawMark: (...a) => marks.push(a), finish: noop, streamClosed: noop }; + const { follow, serializeTasks } = handlers(['upsertStep', 'follow', 'serializeTasks'], context); + const tap = { id: 1, tool: 'iphone_tap', status: 'ok', gesture: { kind: 'tap', x: 1, y: 2 } }; + follow(S.tasks[0], 'abc'); + made[0].emit('step', tap); + assert.equal(marks.length, 1); + const [saved] = JSON.parse(serializeTasks(false)); // the page reloads + follow(saved, 'abc'); + made[1].emit('step', tap); + assert.equal(marks.length, 1, 'known before the reload'); + made[1].emit('step', { ...tap, id: 2 }); + assert.equal(marks.length, 2, 'a new one is drawn'); +}); + +// A task that ends leaves no step spinning: an older daemon sends done with a step still open +test('steps still open when a task ends are stopped', () => { + const task = { id: 't1', status: 'running', steps: [{ id: 1, status: 'ok' }, { id: 2, status: 'running' }, { id: 3, status: 'waiting' }] }; + const context = { S: { expanded: new Set() }, tr: String, show: noop, renderAll: noop, scrollConvo: noop }; + const { finish } = handlers(['finish'], context); + finish(task, 'stopped', ''); + assert.deepEqual(task.steps.map(s => s.status), ['ok', 'stopped', 'stopped']); +}); + +test('an unknown task state is shown as it is and does not replace a known one', () => { + const { made, FakeES } = streams(); + const task = { id: 't1', status: 'running', steps: [] }; + const context = { ACTIVE, EventSource: FakeES, tr: String, show: noop, renderAll: noop, renderTurns: noop, scrollConvo: noop, refreshStatusSoon: noop, drawMark: noop, finish: noop, streamClosed: noop }; + const { follow } = handlers(['upsertStep', 'follow'], context); + follow(task, 'abc'); + made[0].emit('state', { state: 'something-new' }); + assert.equal(task.status, 'running'); + made[0].emit('state', { state: 'paused' }); + assert.equal(task.status, 'paused'); + const state = html.match(/^function taskStatus\([^]*?^}/m) || html.match(/^function taskStatus.*$/m); + const ts = runInNewContext(html.match(/^const TASK_STATUS = \{[^]*?^\};/m)[0] + '\n' + state[0] + '\ntaskStatus', { tr: String }); + assert.equal(ts('something-new').label, 'something-new'); + assert.equal(ts('paused').label, '已暂停'); +}); + +test('a stream the browser gave up on is followed again if the task is still there, else marked stopped', async () => { + const { made, FakeES } = streams(); + for (const [server, want] of [[[{ id: 'abc', state: 'running' }], 'followed'], [[], 'stopped']]) { + made.length = 0; + const task = { id: 't1', status: 'running', steps: [{ id: 1, status: 'running' }], remoteId: 'abc' }; + const context = { ACTIVE, EventSource: FakeES, tr: String, show: noop, renderAll: noop, renderTurns: noop, scrollConvo: noop, refreshStatusSoon: noop, drawMark: noop, finish: noop, + sleep: async () => {}, api: async () => ({ tasks: server }) }; + const h = handlers(['upsertStep', 'follow', 'lostTask', 'streamClosed'], context); + runInNewContext(html.match(/^const REFOLLOW_MS = .*$/m)[0] + '\n' + html.match(/^const LOST_STREAM = .*$/m)[0] + '\nthis.REFOLLOW_MS = REFOLLOW_MS; this.REFOLLOW_TRIES = REFOLLOW_TRIES; this.LOST_STREAM = LOST_STREAM;', context); + context.follow = h.follow; context.lostTask = h.lostTask; context.streamClosed = h.streamClosed; + await h.streamClosed(task, 'abc'); + assert.equal(want === 'followed' ? made.length : task.status, want === 'followed' ? 1 : 'stopped', want); + } +});