From c9ca39e3336cea925c62f11fcfe489d5d9142ed9 Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 12:33:19 +0900 Subject: [PATCH 1/7] feat: let a tunnel connection reset on drop instead of closing A dropped stream sends a FIN and forgets the connection. A peer that only writes never reads that FIN. It keeps sending into a port that no longer answers until it gives up, about 30 s later. The phone's log relay serves no new client in the meantime. `StreamHandle::reset_on_drop()` marks a stream so that dropping it sends a RST for its own connection instead, on whatever path the stream ends: a library that keeps the stream drops it on an error, a timeout or a normal end alike. The returned `Reset` can also send it earlier, with `now()`, for an owner that must not wait for that drop, and `sent()` resolves once it has gone out. Either way the connection gets one reset: whichever comes first sends it and the other sends nothing, so it never reaches a port that a later connection has reused. Unmarked streams still close with a FIN. Co-Authored-By: Claude Opus 5.5 --- src/tcp/adapter.rs | 123 +++++++++++++++++++++++++++++++++++++++++++++ src/tcp/handle.rs | 72 ++++++++++++++++++++++++-- 2 files changed, 191 insertions(+), 4 deletions(-) diff --git a/src/tcp/adapter.rs b/src/tcp/adapter.rs index ddb1bd7..f177d91 100644 --- a/src/tcp/adapter.rs +++ b/src/tcp/adapter.rs @@ -330,6 +330,33 @@ impl Adapter { } } + /// Reset the connection: the peer drops it at once, unlike a FIN, which + /// a peer that never reads does not notice. + pub(crate) async fn abort(&mut self, host_port: u16) -> Result<(), std::io::Error> { + let Some(state) = self.states.remove(&host_port) else { + return Err(std::io::Error::new(ErrorKind::NotConnected, "not connected")); + }; + let tcp = TcpPacket::create( + self.host_ip, + self.peer_ip, + state.host_port, + state.peer_port, + state.seq, + state.ack, + TcpFlags { + rst: true, + ack: true, + ..Default::default() + }, + 0, + &[], + &[], + ); + let ip = self.ip_wrap(&tcp); + self.log_packet(&ip)?; + self.send_packet(ip).await + } + pub(crate) fn connection_drop(&mut self, host_port: u16) { self.dropped.push(host_port); } @@ -1579,6 +1606,102 @@ mod tests { ); } + #[tokio::test] + async fn abort_sends_a_reset_and_forgets_the_connection() { + let (adapter_end, test_end) = tokio::io::duplex(1 << 16); + let (mut test_rx, mut test_tx) = tokio::io::split(test_end); + let mut adapter = Adapter::new( + Box::new(TestTransport(adapter_end)), + IpAddr::V6(HOST_IP), + IpAddr::V6(PEER_IP), + ); + let hp = handshake(&mut adapter, &mut test_rx, &mut test_tx).await; + let data_seq = PEER_ISN + 1; + adapter + .process_tcp_packet_from_payload(&tcp_seg(hp, data_seq, 0, TcpFlags { psh: true, ack: true, ..Default::default() }, b"log")) + .await + .unwrap(); + let _ack = read_pkt(&mut test_rx).await; + + adapter.abort(hp).await.unwrap(); + let rst = read_pkt(&mut test_rx).await; + assert!(rst.flags.rst && !rst.flags.fin, "an abort resets rather than closes"); + assert_eq!(rst.source_port, hp); + assert_eq!(rst.acknowledgment_number, data_seq + 3, "the reset acknowledges what was read"); + assert!(adapter.abort(hp).await.is_err(), "the connection is gone after the reset"); + } + + /// Connect through the async handle, answering as the peer. + async fn handle_connect( + handle: &mut crate::tcp::handle::AdapterHandle, + test_rx: &mut (impl AsyncRead + Unpin), + test_tx: &mut (impl AsyncWrite + Unpin), + ) -> (crate::tcp::handle::StreamHandle, u16) { + let (stream, hp) = tokio::join!(handle.connect(PEER_PORT), async { + let syn = read_pkt(test_rx).await; + let syn_ack = TcpFlags { syn: true, ack: true, ..Default::default() }; + test_tx + .write_all(&peer_ipv6_pkt(syn.source_port, PEER_ISN, syn.sequence_number.wrapping_add(1), syn_ack, &[])) + .await + .unwrap(); + let _ack = read_pkt(test_rx).await; + syn.source_port + }); + (stream.expect("connect failed"), hp) + } + + async fn nothing_more(test_rx: &mut (impl AsyncRead + Unpin)) -> bool { + tokio::time::timeout(Duration::from_millis(300), read_pkt(test_rx)).await.is_err() + } + + #[tokio::test] + async fn a_stream_marked_reset_on_drop_resets_once_and_sends_no_fin() { + let (adapter_end, test_end) = tokio::io::duplex(1 << 16); + let (mut test_rx, mut test_tx) = tokio::io::split(test_end); + let mut handle = + Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle(); + let (mut stream, hp) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await; + let mut reset = stream.reset_on_drop(); + + drop(stream); + let rst = read_pkt(&mut test_rx).await; + assert!(rst.flags.rst && !rst.flags.fin, "a dropped stream marked reset-on-drop resets"); + assert_eq!(rst.source_port, hp); + tokio::time::timeout(Duration::from_secs(1), reset.sent()).await.expect("resolves once the reset is out"); + reset.now(); + assert!(nothing_more(&mut test_rx).await, "no FIN and no second reset"); + } + + #[tokio::test] + async fn a_stream_reset_early_sends_nothing_when_dropped() { + let (adapter_end, test_end) = tokio::io::duplex(1 << 16); + let (mut test_rx, mut test_tx) = tokio::io::split(test_end); + let mut handle = + Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle(); + let (mut stream, hp) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await; + let reset = stream.reset_on_drop(); + + reset.now(); + let rst = read_pkt(&mut test_rx).await; + assert!(rst.flags.rst && rst.source_port == hp, "the reset goes out before the stream is dropped"); + drop(stream); + assert!(nothing_more(&mut test_rx).await, "the drop sends neither a FIN nor a second reset"); + } + + #[tokio::test] + async fn a_dropped_stream_still_closes_with_a_fin() { + let (adapter_end, test_end) = tokio::io::duplex(1 << 16); + let (mut test_rx, mut test_tx) = tokio::io::split(test_end); + let mut handle = + Adapter::new(Box::new(TestTransport(adapter_end)), IpAddr::V6(HOST_IP), IpAddr::V6(PEER_IP)).to_async_handle(); + let (stream, _) = handle_connect(&mut handle, &mut test_rx, &mut test_tx).await; + + drop(stream); + let fin = read_pkt(&mut test_rx).await; + assert!(fin.flags.fin && !fin.flags.rst, "an unmarked stream closes"); + assert!(nothing_more(&mut test_rx).await, "and is not reset after"); + } + /// A duplicate segment (seq < expected, already received) is re-ACKed but /// its payload is not buffered a second time. #[tokio::test] diff --git a/src/tcp/handle.rs b/src/tcp/handle.rs index a179f0b..fcae639 100644 --- a/src/tcp/handle.rs +++ b/src/tcp/handle.rs @@ -61,6 +61,10 @@ enum HandleMessage { Close { host_port: u16, }, + Abort { + host_port: u16, + done: oneshot::Sender<()>, + }, Send { host_port: u16, data: Vec, @@ -174,6 +178,11 @@ impl AdapterHandle { handles.remove(&host_port); adapter.close(host_port).await.ok(); } + HandleMessage::Abort { host_port, done } => { + handles.remove(&host_port); + adapter.abort(host_port).await.ok(); + done.send(()).ok(); + } HandleMessage::Send { host_port, data, @@ -325,6 +334,7 @@ impl AdapterHandle { send_channel: self.sender.clone(), read_buffer: Vec::new(), pending_writes: FuturesUnordered::new(), + reset: None, }) } Ok(Err(_)) => Err(std::io::Error::new( @@ -379,7 +389,8 @@ impl AdapterHandle { /// be used anywhere a Tokio I/O stream is expected. /// /// Dropping this handle automatically sends a `Close` message to the background -/// task, which sends a TCP FIN and cleans up connection state. +/// task, which sends a TCP FIN and cleans up connection state, or an `Abort` +/// (a RST) after [`StreamHandle::reset_on_drop`]. #[derive(Debug)] pub struct StreamHandle { host_port: u16, @@ -390,14 +401,62 @@ pub struct StreamHandle { read_buffer: Vec, pending_writes: FuturesUnordered>>, + /// Set by [`StreamHandle::reset_on_drop`]; shared with the returned [`Reset`]. + reset: Option, } +/// The one reset a marked stream gets: taken by its drop or by [`Reset::now`], +/// whichever comes first. After that the connection is gone, and the other +/// sends nothing, so it can never reach a port a later connection reuses. +type ResetSlot = std::sync::Arc>>>; + impl StreamHandle { pub fn close(&mut self) { let _ = self.send_channel.send(HandleMessage::Close { host_port: self.host_port, }); } + + /// Reset the connection (RST) when this stream is dropped, instead of + /// closing it (FIN). A peer that only writes, such as the phone's log + /// relay, never reads a FIN: it keeps sending into a closed port, and + /// serves no other client until it gives up about 30 s later. + /// + /// Set it before handing the stream to a library that keeps it: the + /// reset then goes out however that library ends. + pub fn reset_on_drop(&mut self) -> Reset { + let (done, sent) = oneshot::channel(); + let slot = ResetSlot::default(); + *slot.lock().unwrap() = Some(done); + self.reset = Some(slot.clone()); + Reset { host_port: self.host_port, send_channel: self.send_channel.clone(), slot, sent: Some(sent) } + } +} + +/// The reset of a stream marked with [`StreamHandle::reset_on_drop`]. +#[derive(Debug)] +pub struct Reset { + host_port: u16, + send_channel: mpsc::UnboundedSender, + slot: ResetSlot, + sent: Option>, +} + +impl Reset { + /// Reset now instead of when the stream is dropped, for an owner that + /// cannot wait for a library to drop it, before the tunnel goes. + pub fn now(&self) { + if let Some(done) = self.slot.lock().unwrap().take() { + let _ = self.send_channel.send(HandleMessage::Abort { host_port: self.host_port, done }); + } + } + + /// Resolves once the reset has gone out, or once the tunnel is gone. + pub async fn sent(&mut self) { + if let Some(sent) = self.sent.take() { + let _ = sent.await; + } + } } impl AsyncRead for StreamHandle { @@ -504,9 +563,14 @@ impl AsyncWrite for StreamHandle { impl Drop for StreamHandle { fn drop(&mut self) { - let _ = self.send_channel.send(HandleMessage::Close { - host_port: self.host_port, - }); + let host_port = self.host_port; + let message = match &self.reset { + None => Some(HandleMessage::Close { host_port }), + Some(slot) => slot.lock().unwrap().take().map(|done| HandleMessage::Abort { host_port, done }), + }; + if let Some(message) = message { + let _ = self.send_channel.send(message); + } } } From 1f11bcf11143ef32bdd6d31101e6caaedd7a7bca Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 12:33:19 +0900 Subject: [PATCH 2/7] feat: capture the phone's log to a file with `iph syslog` `iph syslog start|stop|status` streams the phone's os_trace log into a JSON Lines file while other commands keep running, so a test or an agent can check what an app logged after a tap. Until now the only way was `sudo log collect` on the Mac. The daemon holds one capture. `start` connects the relay under the session lock and hands the stream to a task of its own that never touches the session. `--process` (executable name, survives app restarts) and `--level` filter on this side, `--pid` on the phone. The file starts with a `start` line and ends with an `end` line that names the reason: stop, a dropped connection, or the daemon exiting. `--max-mb` moves the file to `.1`. `stop --grep RE --max N` returns the latest matching entries. A capture ends by resetting its connection. Closed with a FIN, the relay kept writing into it and sent nothing to the next capture for about 30 s (measured on an iPhone 16 Pro, iOS 27.2.1). The stream is marked to reset on drop before idevice takes it, so a start that fails partway and a reader that stops on its own reset it too. A capture that is ended resets it at once, before `Session::reset` can close the tunnel under it, and `stop` waits until the reset is out. `start` opens the file only once the relay runs, so a start that fails leaves the previous capture's file as it was. The hint about a silent relay shows only while a capture without `--pid` runs. The same command is the MCP tool `iph_syslog` and the script function `syslog()`, which is not an input and cannot choose the file. Batch is left out: a capture spans requests, and a failing batch would leave it running. idevice 0.1.68 passes the device's microseconds where chrono expects nanoseconds; the entry's time puts them back as microseconds. Enables idevice's `syslog_relay` feature, which adds chrono (and its num-traits and autocfg) to Cargo.lock. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 27 ++ Cargo.toml | 1 + src/clock.rs | 2 +- src/daemon.rs | 4 + src/device/session.rs | 35 ++ src/lib.rs | 1 + src/main.rs | 34 ++ src/mcp.rs | 23 +- src/script.rs | 36 +- src/syslog.rs | 823 ++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 983 insertions(+), 3 deletions(-) create mode 100644 src/syslog.rs diff --git a/Cargo.lock b/Cargo.lock index 67878f0..e6ab7b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -101,6 +101,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "aws-lc-rs" version = "1.19.0" @@ -192,6 +198,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", + "serde", +] + [[package]] name = "clap" version = "4.6.7" @@ -516,6 +532,8 @@ checksum = "f5d7799c8497cef60ddfd38f7d92e267b9fa5d0b18e7691d31041453007400ca" dependencies = [ "async-stream", "base64 0.22.1", + "bytes", + "chrono", "flate2", "futures", "indexmap", @@ -715,6 +733,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" diff --git a/Cargo.toml b/Cargo.toml index 1591e81..268e3ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ idevice = { version = "=0.1.68", features = [ "cryptexd", "tss", "heartbeat", + "syslog_relay", ] } tokio = { version = "1", features = ["full"] } clap = { version = "4", features = ["derive"] } diff --git a/src/clock.rs b/src/clock.rs index f827ea0..edc837d 100644 --- a/src/clock.rs +++ b/src/clock.rs @@ -9,7 +9,7 @@ pub fn now_utc() -> String { format_utc(secs) } -fn format_utc(secs: i64) -> String { +pub fn format_utc(secs: i64) -> String { let days = secs.div_euclid(86_400); let rem = secs.rem_euclid(86_400); // Civil date from a day count (Howard Hinnant's algorithm). diff --git a/src/daemon.rs b/src/daemon.rs index 8ed68a8..57527ea 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -82,6 +82,7 @@ async fn dispatch(s: &mut Session, cmd: &str, args: &Value) -> Res { "script" => Box::pin(s.serve_script(args)).await, "doctor" => Box::pin(doctor::run(s, parse_args(args)?)).await, "dnd" => Box::pin(s.cmd_dnd(parse_args(args)?)).await, + "syslog" => Box::pin(s.cmd_syslog(args)).await, "status" => Ok(fields! { "udid": s.udid.clone(), "connection": s.connection(), @@ -90,6 +91,7 @@ async fn dispatch(s: &mut Session, cmd: &str, args: &Value) -> Res { "input_session": s.input.is_some(), "connects": s.connects, "ax_restarts": s.ax_restarts, + "capture": s.capture_state(), "pid": std::process::id(), "build": build_stamp(), }), @@ -147,6 +149,7 @@ async fn handle(stream: ipc::Stream, shared: Arc) -> Result<()> { "shutdown" => { log("shutdown requested"); let mut session = shared.session.lock().await; + session.end_capture_before_exit("the daemon was stopped (iph stop, or replaced by a newer build)").await; let reply = json!({ "ok": true }); write.write_all(format!("{reply}\n").as_bytes()).await?; write.shutdown().await.ok(); @@ -240,6 +243,7 @@ pub async fn run(udid: String) -> Result<()> { session.close_idle_input().await; if idle > idle_exit { log("idle, exiting"); + session.end_capture_before_exit("the daemon exited after its idle time").await; session.shutdown().await; ipc::cleanup(&keeper.udid); let _ = std::fs::remove_file(paths::daemon_pid(&keeper.udid)); diff --git a/src/device/session.rs b/src/device/session.rs index 1c93541..bf9688b 100644 --- a/src/device/session.rs +++ b/src/device/session.rs @@ -12,6 +12,7 @@ use idevice::{ AppListEntry, AppServiceClient, ImageFormat, PasteboardServiceClient, ScreenCaptureServiceClient, }, + os_trace_relay::{OsTraceRelayClient, OsTraceRelayReceiver}, }; use crate::{ @@ -27,6 +28,7 @@ use crate::{ }, i18n::t, reply::{Fail, Res}, + tcp::handle::Reset, }; const APP_SERVICE: &str = "com.apple.coredevice.appservice"; @@ -143,6 +145,8 @@ pub struct Session { system_in_front: bool, /// Do Not Disturb: whether it is on for this session and what to put back. pub dnd: crate::dnd::State, + /// `iph syslog`: the log capture, running or ended and not yet stopped. + pub capture: Option, } /// A file URL or path as a plain path without a trailing slash. @@ -223,6 +227,7 @@ impl Session { ax_restart_unhelpful: false, system_in_front: false, dnd, + capture: None, } } @@ -262,6 +267,8 @@ impl Session { /// Drop every connection. The next request builds them again. pub fn reset(&mut self) { + // Its stream runs on the tunnel being dropped. + self.end_capture("the connection to the phone was reset"); let tunnel = self.tunnel.take(); if let Some(input) = self.input.take() { self.input_closed_at = Some(Instant::now()); @@ -771,6 +778,34 @@ impl Session { self.rsd_client().await } + /// The phone's log stream, filtered to one process when `pid` is given, + /// and its reset. Dropped on any path, here or later, the stream resets + /// its connection rather than closing it, which would hold the relay for + /// the next capture. + pub async fn os_trace(&mut self, pid: Option) -> Res<(OsTraceRelayReceiver, Reset)> { + let name = OsTraceRelayClient::rsd_service_name(); + let unavailable = |e: String| Fail::not_sent("service_unavailable", format!("{name}: {e}")); + // As `rsd_client`: a tunnel that died under the session is rebuilt once. + let mut attempt = 0; + let mut stream = loop { + let (mut adapter, port) = self.service_port(&name).await?; + match bounded("connect", 12, adapter.connect(port)).await { + Ok(stream) => break stream, + Err(e) if attempt == 0 && is_transport_error(&e) => { + attempt += 1; + self.reset(); + } + Err(e) => return Err(unavailable(e)), + } + }; + let reset = stream.reset_on_drop(); + let started = match OsTraceRelayClient::from_stream(Box::new(stream)).await { + Ok(client) => bounded("start_trace", 12, client.start_trace(pid)).await, + Err(e) => Err(format!("{e:?}")), + }; + started.map(|receiver| (receiver, reset)).map_err(unavailable) + } + pub async fn pasteboard(&mut self) -> Res>> { self.rsd_client().await } diff --git a/src/lib.rs b/src/lib.rs index f9e2b04..347241e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,6 +25,7 @@ pub mod mcp; pub mod paths; pub mod script; pub mod steps; +pub mod syslog; pub mod tcp; pub mod reply; pub mod selector; diff --git a/src/main.rs b/src/main.rs index 9a49a4b..5828edb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -188,6 +188,31 @@ enum Cmd { }, /// Do Not Disturb on the phone: on, off (back to the Focus that was on), status. Dnd { action: String }, + /// Write the phone's log to a JSON Lines file while a test runs: start, stop, status. + Syslog { + action: String, + /// start: keep only this process, by executable name (Settings is Preferences). Repeatable. + #[arg(long)] + process: Vec, + /// start: keep only this pid (the phone filters it). + #[arg(long)] + pid: Option, + /// start: lowest level kept: debug, info, notice, error, fault. + #[arg(long)] + level: Option, + /// start: the file to write (default: .syslog.jsonl in the state directory). + #[arg(short, long)] + output: Option, + /// start: move the file to .1 when it reaches this size (default 64). + #[arg(long)] + max_mb: Option, + /// stop: return the entries whose message matches this regular expression. + #[arg(long)] + grep: Option, + /// stop: most entries to return, the latest ones (default 50, at most 1000). + #[arg(long)] + max: Option, + }, /// Stop the background daemon for this phone. Stop, /// Internal: the resident process. @@ -395,6 +420,15 @@ async fn run(cli: Cli) -> i32 { Cmd::Key { key } => ("key", json!({ "key": key })), Cmd::Button { button } => ("button", json!({ "button": button })), Cmd::Dnd { action } => ("dnd", json!({ "action": action })), + Cmd::Syslog { action, process, pid, level, output, max_mb, grep, max } => { + // The daemon writes the file, so the path must not depend on its cwd. + let output = output.map(|o| std::path::absolute(&o).map(|p| p.display().to_string()).unwrap_or(o)); + let process = (!process.is_empty()).then_some(process); + ("syslog", json!({ + "action": action, "process": process, "pid": pid, "level": level, "output": output, + "max_mb": max_mb, "grep": grep, "max": max, + })) + } Cmd::Launch { app, restart, env, arguments } => match launch_args(&app, restart, &env, &arguments) { Ok(v) => ("launch", v), Err(f) => { diff --git a/src/mcp.rs b/src/mcp.rs index e639d04..ab38438 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -18,6 +18,7 @@ const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loo The commands are functions that return what the tool of the same name returns: read(opts), find(selector), tap(target, opts), swipe(direction | {from, to}, opts), \ pinch(direction | {scale, rotate, at}, opts), scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart, arguments, environment}), apps(). Also waitFor(selector, {timeout_ms}), \ readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \ +syslog(\"start\" | \"stop\" | \"status\", {process, pid, level, grep, max}) captures the phone's log as iph_syslog does; a script cannot choose the file. \ tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \ A call that fails throws an Error with .code, .outcome, .hint and .result (the full result object); uncaught, it ends the script and the result says which call and line. \ After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \ @@ -168,6 +169,23 @@ fn tools() -> Vec { json!({ "action": { "type": "string", "enum": ["on", "off", "status"] } }), &["action"], ), + tool( + "iph_syslog", + "Capture the phone's log to a JSON Lines file while other calls run, to check what an app logged after a tap. \ + \"start\" (one capture at a time), \"stop\" (ends it; with grep or max it returns the latest matching entries), \"status\". \ + Filter with process (executable names such as Preferences; survives app restarts) or pid; unfiltered over Wi-Fi it is a lot of data.", + json!({ + "action": { "type": "string", "enum": ["start", "stop", "status"] }, + "process": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these executables." }, + "pid": { "type": "integer", "description": "start: keep only this pid (filtered on the phone)." }, + "level": { "type": "string", "enum": ["debug", "info", "notice", "error", "fault"], "description": "start: lowest level kept." }, + "output": { "type": "string", "description": "start: absolute path of the file (default: in iph's state directory)." }, + "max_mb": { "type": "integer", "description": "start: move the file to .1 at this size (default 64)." }, + "grep": { "type": "string", "description": "stop: regular expression matched against each message." }, + "max": { "type": "integer", "description": "stop: most entries returned, the latest (default 50, at most 1000)." }, + }), + &["action"], + ), tool( "iph_screenshot", "Save a PNG screenshot to a file on this computer. Use iph_read for content; this is for looks.", @@ -223,13 +241,16 @@ async fn call(udid: &str, name: &str, args: Value) -> Value { Err(e) => envelope(Err(Fail::invalid(e.to_string())), started), }, "iph_scripts" => envelope(script::cmd_scripts(), started), + "iph_syslog" if args.get("output").and_then(|o| o.as_str()).is_some_and(|o| !std::path::Path::new(o).is_absolute()) => { + envelope(Err(Fail::invalid("`output` must be an absolute path")), started) + } "iph_script" | "iph_run" => match script_request(name, &args) { Ok(request) => client::request(udid, "script", request).await, Err(f) => envelope(Err(f), started), }, "iph_read" | "iph_find" | "iph_tap" | "iph_swipe" | "iph_pinch" | "iph_scroll" | "iph_type" | "iph_key" | "iph_button" | "iph_launch" | "iph_apps" | "iph_screenshot" | "iph_batch" | "iph_doctor" - | "iph_dnd" => { + | "iph_dnd" | "iph_syslog" => { let cmd = name.trim_start_matches("iph_"); let args = if cmd == "apps" { Value::Null } else { args }; client::request(udid, cmd, args).await diff --git a/src/script.rs b/src/script.rs index 6d67ab8..04965df 100644 --- a/src/script.rs +++ b/src/script.rs @@ -145,6 +145,7 @@ const PRELUDE: &str = r#" g.waitFor = (selector, o) => call("wait_for", { ...opts(o), selector }); g.readField = (spec) => call("read_field", opts(spec)).value; g.readList = (spec) => call("read_list", opts(spec)); + g.syslog = (action, o) => call("syslog", { ...opts(o), action }); g.sleep = (ms) => { __sleep(Number(ms) || 0); }; g.log = (...xs) => { __emit("log", "", xs.map(text).join(" ")); }; g.output = (key, value) => { __emit("output", String(key), JSON.stringify(value === undefined ? null : value)); }; @@ -459,6 +460,10 @@ impl RunState { let Value::Object(mut map) = args else { return Err(Fail::invalid(format!("`{cmd}` takes an object of arguments"))); }; + if cmd == "syslog" && map.get("output").is_some_and(|v| !v.is_null()) { + // Saved scripts come from anywhere; the file stays where iph keeps its own. + return Err(Fail::invalid("a script cannot choose the file; the capture goes to iph's state directory")); + } let hint = map.remove("hint").and_then(|v| v.as_str().map(String::from)); Ok(Prepared { args: Value::Object(map), hint }) } @@ -667,8 +672,9 @@ impl PhoneHost<'_> { let (_, value) = Box::pin(self.session.read_field(&args)).await?; Ok(fields! { "value": value }) } + "syslog" => Box::pin(self.session.cmd_syslog(&args)).await, other => Err(Fail::invalid(format!( - "a script has no `{other}` (read, find, tap, swipe, pinch, scroll, type, key, button, launch, apps, waitFor, readField, readList)" + "a script has no `{other}` (read, find, tap, swipe, pinch, scroll, type, key, button, launch, apps, waitFor, readField, readList, syslog)" ))), } } @@ -882,6 +888,34 @@ mod tests { ); } + #[test] + fn syslog_is_not_an_input_and_cannot_choose_its_file() { + let mut fake = Fake::default(); + let code = r#" + syslog("start", {process: ["Preferences"], level: "info"}); + tap("일반"); tap("정보"); + const done = syslog("stop", {grep: "row", max: 5}); + let refused = null; + try { syslog("start", {output: "/tmp/elsewhere.jsonl"}); } catch (e) { refused = e.code; } + return { refused }; + "#; + let (res, _) = go(&mut fake, code, json!({}), limits()); + let out = res.unwrap(); + let asked: Vec<(&str, &Value)> = fake.asked.iter().map(|(c, a)| (c.as_str(), a)).collect(); + assert_eq!(asked[0], ("syslog", &json!({"process": ["Preferences"], "level": "info", "action": "start"}))); + assert_eq!(asked[3], ("syslog", &json!({"grep": "row", "max": 5, "action": "stop"}))); + assert_eq!(asked.len(), 4, "the refused start never reached the phone"); + assert_eq!(out["outputs"]["refused"], "invalid_argument"); + assert_eq!(out["inputs_sent"], 2); + } + + #[test] + fn a_script_may_pass_a_null_output() { + let mut run = RunState::default(); + assert!(run.prepare("syslog", json!({"action": "start", "output": null})).is_ok()); + assert!(run.prepare("syslog", json!({"action": "start", "output": "/tmp/x.jsonl"})).is_err()); + } + #[test] fn a_failed_call_throws_and_stops_the_script_unless_caught() { let not_found = json!({"ok": false, "outcome": "not_sent", diff --git a/src/syslog.rs b/src/syslog.rs new file mode 100644 index 0000000..92bba97 --- /dev/null +++ b/src/syslog.rs @@ -0,0 +1,823 @@ +//! `iph syslog`: the phone's log stream, written to a file while a test runs, +//! so what an app logged after a tap can be checked afterwards. +//! +//! One capture per daemon. The stream is read by a task of its own that never +//! touches the session, so commands keep working while it runs. The file is +//! JSON Lines: a `start` line, the kept entries, and an `end` line that says +//! why the capture ended. A file without an `end` line belongs to a daemon +//! that was killed. + +use std::{ + collections::VecDeque, + fs::File, + io::{BufRead, BufReader, Write}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +use idevice::{ + IdeviceError, + os_trace_relay::{LogLevel, OsTraceLog, OsTraceRelayReceiver}, +}; +use regex::Regex; +use serde_json::{Map, Value, json}; + +use crate::{ + clock, + device::session::Session, + fields, paths, + reply::{Fail, Res}, + tcp::handle::Reset, +}; + +const DEFAULT_MAX_MB: u64 = 64; +const DEFAULT_MATCHES: u64 = 50; +const MAX_MATCHES: u64 = 1000; +/// Longest message a match returns; the file keeps the whole message. +const MATCH_CHARS: usize = 500; + +/// Severity, lowest first. The device's own codes are not in this order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + Debug, + Info, + Notice, + Error, + Fault, +} + +impl Level { + pub fn name(self) -> &'static str { + match self { + Level::Debug => "debug", + Level::Info => "info", + Level::Notice => "notice", + Level::Error => "error", + Level::Fault => "fault", + } + } + + fn parse(s: &str) -> Option { + Some(match s.to_ascii_lowercase().as_str() { + "debug" => Level::Debug, + "info" => Level::Info, + // Apple's tools call this level "default". + "notice" | "default" => Level::Notice, + "error" => Level::Error, + "fault" => Level::Fault, + _ => return None, + }) + } +} + +impl From for Level { + fn from(level: LogLevel) -> Self { + match level { + LogLevel::Debug => Level::Debug, + LogLevel::Info => Level::Info, + LogLevel::Notice => Level::Notice, + LogLevel::Error => Level::Error, + LogLevel::Fault => Level::Fault, + } + } +} + +/// One log entry as the file keeps it. +#[derive(Debug, Clone, PartialEq)] +pub struct Entry { + /// UTC. + pub time: String, + pub pid: u32, + /// The executable's file name, the same across restarts of the app. + pub process: String, + /// The library or executable that logged it. + pub sender: String, + pub level: Level, + pub subsystem: Option, + pub category: Option, + pub message: String, +} + +/// The library hands the device's microseconds to a constructor that takes +/// nanoseconds (idevice 0.1.68), so the sub-second part arrives as micros. +fn utc_micros(secs: i64, micros: u32) -> String { + let whole = clock::format_utc(secs); + format!("{}.{:06}Z", whole.trim_end_matches('Z'), micros.min(999_999)) +} + +fn file_name(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +impl From for Entry { + fn from(log: OsTraceLog) -> Self { + let (subsystem, category) = match log.label { + Some(l) => (Some(l.subsystem), Some(l.category)), + None => (None, None), + }; + Self { + time: utc_micros(log.timestamp.and_utc().timestamp(), log.timestamp.and_utc().timestamp_subsec_nanos()), + pid: log.pid, + process: file_name(&log.filename).to_string(), + sender: file_name(&log.image_name).to_string(), + level: log.level.into(), + subsystem, + category, + message: log.message, + } + } +} + +impl Entry { + pub fn line(&self) -> String { + let mut v = json!({ + "time": self.time, + "pid": self.pid, + "process": self.process, + "sender": self.sender, + "level": self.level.name(), + }); + if let Some(s) = &self.subsystem { + v["subsystem"] = json!(s); + } + if let Some(c) = &self.category { + v["category"] = json!(c); + } + v["message"] = json!(self.message); + v.to_string() + } +} + +/// What is kept on this side. A pid is filtered by the phone instead. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Filter { + pub processes: Vec, + pub min_level: Option, +} + +impl Filter { + pub fn keeps(&self, e: &Entry) -> bool { + (self.processes.is_empty() || self.processes.contains(&e.process)) + && self.min_level.is_none_or(|min| e.level >= min) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Spec { + pub filter: Filter, + pub pid: Option, + pub path: PathBuf, + pub max_bytes: u64, +} + +#[derive(Debug)] +pub struct Query { + pub grep: Option, + pub max: usize, +} + +#[derive(Debug)] +pub enum Request { + Start(Spec), + /// `None`: report the counts only. + Stop(Option), + Status, +} + +/// Parse the arguments every surface sends. `default_path` is used when no +/// `output` is given; a given one must be absolute, since the daemon writes it. +pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res { + let given: Map = match args { + Value::Null => Map::new(), + Value::Object(m) => m.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(), + _ => return Err(Fail::invalid("syslog takes an object of arguments")), + }; + let action = given + .get("action") + .and_then(|v| v.as_str()) + .ok_or_else(|| Fail::invalid("syslog needs an action: start, stop or status"))?; + let allowed: &[&str] = match action { + "start" => &["action", "process", "pid", "level", "output", "max_mb"], + "stop" => &["action", "grep", "max"], + "status" => &["action"], + other => return Err(Fail::invalid(format!("unknown syslog action `{other}` (start, stop, status)"))), + }; + if let Some(key) = given.keys().find(|k| !allowed.contains(&k.as_str())) { + return Err(Fail::invalid(format!("`syslog {action}` takes no `{key}`"))); + } + let number = |key: &str| -> Res> { + match given.get(key) { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| Fail::invalid(format!("`{key}` takes a whole number"))), + } + }; + match action { + "start" => { + let processes = match given.get("process") { + None => Vec::new(), + Some(Value::String(s)) => vec![s.clone()], + Some(Value::Array(a)) => a + .iter() + .map(|v| v.as_str().map(String::from)) + .collect::>>() + .ok_or_else(|| Fail::invalid("`process` takes names"))?, + Some(_) => return Err(Fail::invalid("`process` takes a name or a list of names")), + }; + if processes.iter().any(|p| p.is_empty() || p.contains('/')) { + return Err(Fail::invalid("`process` takes executable names such as Preferences, not paths")); + } + let min_level = match given.get("level") { + None => None, + Some(v) => Some(v.as_str().and_then(Level::parse).ok_or_else(|| { + Fail::invalid("`level` takes debug, info, notice, error or fault") + })?), + }; + let pid = match number("pid")? { + None => None, + Some(n) => Some(u32::try_from(n).map_err(|_| Fail::invalid("`pid` is out of range"))?), + }; + let path = match given.get("output") { + None => default_path(), + Some(v) => { + let path = PathBuf::from(v.as_str().ok_or_else(|| Fail::invalid("`output` takes a path"))?); + if !path.is_absolute() { + return Err(Fail::invalid("`output` must be an absolute path")); + } + path + } + }; + let max_mb = number("max_mb")?.unwrap_or(DEFAULT_MAX_MB); + if max_mb == 0 { + return Err(Fail::invalid("`max_mb` must be at least 1")); + } + Ok(Request::Start(Spec { + filter: Filter { processes, min_level }, + pid, + path, + max_bytes: max_mb * 1024 * 1024, + })) + } + "stop" => { + let grep = match given.get("grep") { + None => None, + Some(v) => { + let pattern = v.as_str().ok_or_else(|| Fail::invalid("`grep` takes a regular expression"))?; + Some(Regex::new(pattern).map_err(|e| Fail::invalid(format!("`grep`: {e}")))?) + } + }; + let max = number("max")?; + if grep.is_none() && max.is_none() { + return Ok(Request::Stop(None)); + } + let max = max.unwrap_or(DEFAULT_MATCHES).min(MAX_MATCHES) as usize; + Ok(Request::Stop(Some(Query { grep, max }))) + } + _ => Ok(Request::Status), + } +} + +/// Where the previous part goes when the file reaches its size. +pub fn rotated(path: &Path) -> PathBuf { + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(".1"); + path.with_file_name(name) +} + +fn open_private(path: &Path) -> std::io::Result { + let file = paths::private_file().write(true).create(true).truncate(true).open(path)?; + #[cfg(unix)] + { + // `private_file` sets the mode only on a file it creates. + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + Ok(file) +} + +/// The file, kept under a size: once the next line would pass it, the file +/// becomes `.1` (replacing an older one) and a new file starts. +pub struct Sink { + path: PathBuf, + file: File, + size: u64, + cap: u64, + pub rotations: u32, +} + +impl Sink { + pub fn create(path: &Path, cap: u64) -> std::io::Result { + let file = open_private(path)?; + // A part left from an earlier capture would read as this one's. + let _ = std::fs::remove_file(rotated(path)); + Ok(Self { path: path.to_path_buf(), file, size: 0, cap, rotations: 0 }) + } + + /// Write one line in a single call, so nothing that stops the writer + /// leaves half a line behind. + pub fn write(&mut self, line: &str) -> std::io::Result<()> { + let bytes = format!("{line}\n"); + let len = bytes.len() as u64; + if self.size > 0 && self.size + len > self.cap { + std::fs::rename(&self.path, rotated(&self.path))?; + self.file = open_private(&self.path)?; + self.size = 0; + self.rotations += 1; + } + self.file.write_all(bytes.as_bytes())?; + self.size += len; + Ok(()) + } +} + +/// What the reading task and the session share. +pub struct Live { + sink: Sink, + filter: Filter, + pub seen: u64, + pub kept: u64, + /// Entries the library could not parse; the stream goes on after them. + pub unparsed: u64, + pub ended: Option, +} + +impl Live { + pub fn new(sink: Sink, filter: Filter) -> Self { + Self { sink, filter, seen: 0, kept: 0, unparsed: 0, ended: None } + } + + pub fn take(&mut self, entry: &Entry) -> std::io::Result<()> { + if self.ended.is_some() { + return Ok(()); + } + self.seen += 1; + if self.filter.keeps(entry) { + self.sink.write(&entry.line())?; + self.kept += 1; + } + Ok(()) + } + + /// Write the `end` line once; later calls change nothing. + pub fn end(&mut self, reason: &str) { + if self.ended.is_some() { + return; + } + let line = json!({ + "event": "end", + "time": clock::now_utc(), + "reason": reason, + "seen": self.seen, + "kept": self.kept, + "unparsed": self.unparsed, + "rotations": self.sink.rotations, + }); + let _ = self.sink.write(&line.to_string()); + self.ended = Some(reason.to_string()); + } +} + +/// The library reads a whole entry before parsing it, so an entry it cannot +/// parse costs only that entry. A missing leading byte means the stream lost +/// its place, and nothing after it can be trusted. +fn skippable(e: &IdeviceError) -> bool { + matches!(e, IdeviceError::UnexpectedResponse(m) if !m.contains("leading byte")) +} + +async fn pump(mut stream: OsTraceRelayReceiver, live: Arc>) { + loop { + // Never under a timeout: an entry is several reads, and giving up + // between them would leave the stream mid-entry. + let reason = match stream.next().await { + Ok(log) => match live.lock().unwrap().take(&Entry::from(log)) { + Ok(()) => continue, + Err(e) => format!("cannot write the file: {e}"), + }, + Err(e) if skippable(&e) => { + live.lock().unwrap().unparsed += 1; + continue; + } + Err(e) => format!("the log stream ended: {e}"), + }; + live.lock().unwrap().end(&reason); + return; + } +} + +pub struct Capture { + spec: Spec, + started_at: String, + started: std::time::Instant, + live: Arc>, + task: tokio::task::JoinHandle<()>, + reset: Reset, +} + +impl Capture { + /// End it now. The task is stopped first, so the `end` line is the last. + /// The connection is reset here, not when the stopped task drops the + /// stream: by then `Session::reset` may have closed the tunnel. + pub fn end(&self, reason: &str) { + self.reset.now(); + self.task.abort(); + self.live.lock().unwrap().end(reason); + } + + /// After `end`: wait until the connection has been reset, so the relay + /// has let go of it before the next capture connects or the daemon exits. + pub async fn settle(&mut self) { + let _ = tokio::time::timeout(std::time::Duration::from_secs(1), self.reset.sent()).await; + } + + /// A task that stopped without saying why (a panic in the parser). + fn check(&self) { + if self.task.is_finished() { + self.live.lock().unwrap().end("the log reader stopped unexpectedly"); + } + } + + pub fn is_running(&self) -> bool { + self.check(); + self.live.lock().unwrap().ended.is_none() + } + + pub fn report(&self) -> Map { + self.check(); + let live = self.live.lock().unwrap(); + let mut out = fields! { + "state": if live.ended.is_none() { "running" } else { "ended" }, + "path": self.spec.path.display().to_string(), + "started_at": self.started_at, + "seen": live.seen, + "kept": live.kept, + "unparsed": live.unparsed, + "rotations": live.sink.rotations, + }; + if !self.spec.filter.processes.is_empty() { + out.insert("process".into(), json!(self.spec.filter.processes)); + } + if let Some(pid) = self.spec.pid { + out.insert("pid".into(), json!(pid)); + } + if let Some(level) = self.spec.filter.min_level { + out.insert("level".into(), json!(level.name())); + } + if live.sink.rotations > 0 { + out.insert("previous_part".into(), json!(rotated(&self.spec.path).display().to_string())); + } + if let Some(reason) = &live.ended { + out.insert("ended_reason".into(), json!(reason)); + } + // Not with a pid: a quiet process sends nothing either. + if live.ended.is_none() + && self.spec.pid.is_none() + && live.seen == 0 + && self.started.elapsed() > std::time::Duration::from_secs(5) + { + // Seen live: a relay connection that was dropped, not reset, + // held the next capture for about 30 s. + out.insert("hint".into(), json!(crate::i18n::t( + "아직 받은 로그가 없습니다. 연결이 끊긴 직후에는 폰이 약 30초 뒤에야 로그를 보냅니다.", + "No entries yet. Right after a dropped connection the phone starts sending about 30 s later.", + ))); + } + out + } +} + +/// Entries in `files` (oldest first) whose message matches, the most recent +/// `max` of them, with the number that matched in all. +pub fn search(files: &[PathBuf], grep: Option<&Regex>, max: usize) -> (Vec, u64) { + let mut found = VecDeque::new(); + let mut matched = 0; + for path in files { + let Ok(file) = File::open(path) else { continue }; + for line in BufReader::new(file).lines().map_while(Result::ok) { + let Ok(Value::Object(mut entry)) = serde_json::from_str::(&line) else { continue }; + if entry.contains_key("event") { + continue; + } + let message = entry.get("message").and_then(|m| m.as_str()).unwrap_or("").to_string(); + if grep.is_some_and(|re| !re.is_match(&message)) { + continue; + } + matched += 1; + if max == 0 { + continue; + } + if message.chars().count() > MATCH_CHARS { + entry.insert("message".into(), json!(message.chars().take(MATCH_CHARS).collect::())); + entry.insert("message_cut".into(), json!(true)); + } + if found.len() == max { + found.pop_front(); + } + found.push_back(Value::Object(entry)); + } + } + (found.into(), matched) +} + +impl Session { + pub async fn cmd_syslog(&mut self, args: &Value) -> Res { + let udid = self.udid.clone(); + let request = parse(args, || paths::state_dir().join(format!("{udid}.syslog.jsonl")))?; + match request { + Request::Status => Ok(match &self.capture { + Some(c) => c.report(), + None => fields! { "state": "none" }, + }), + Request::Start(spec) => { + if let Some(c) = self.capture.as_ref().filter(|c| c.is_running()) { + return Err(Fail::not_sent("capture_running", "a capture is already running") + .with("path", c.spec.path.display().to_string()) + .hint(crate::i18n::t( + "`iph syslog stop`으로 끝낸 뒤 다시 시작하세요.", + "End it with `iph syslog stop` first.", + ))); + } + // The file is opened only once the relay runs: a start that + // fails leaves an earlier capture's file as it was. + let (stream, reset) = self.os_trace(spec.pid).await?; + let sink = Sink::create(&spec.path, spec.max_bytes) + .map_err(|e| Fail::invalid(format!("{}: {e}", spec.path.display())))?; + let mut live = Live::new(sink, spec.filter.clone()); + let started_at = clock::now_utc(); + let start = json!({ + "event": "start", + "time": started_at, + "udid": self.udid, + "process": spec.filter.processes, + "pid": spec.pid, + "level": spec.filter.min_level.map(Level::name), + "max_mb": spec.max_bytes / (1024 * 1024), + }); + if let Err(e) = live.sink.write(&start.to_string()) { + return Err(Fail::invalid(format!("{}: {e}", spec.path.display()))); + } + let live = Arc::new(Mutex::new(live)); + let task = tokio::task::spawn_local(pump(stream, live.clone())); + let started = std::time::Instant::now(); + let capture = Capture { spec, started_at, started, live, task, reset }; + let report = capture.report(); + self.capture = Some(capture); + Ok(report) + } + Request::Stop(query) => { + let Some(mut capture) = self.capture.take() else { + return Err(Fail::not_sent("no_capture", "no capture to stop")); + }; + capture.end("stopped"); + capture.settle().await; + let mut out = capture.report(); + if let Some(q) = query { + let files = [rotated(&capture.spec.path), capture.spec.path.clone()]; + let (matches, matched) = search(&files, q.grep.as_ref(), q.max); + out.insert("matched".into(), json!(matched)); + out.insert("matches".into(), json!(matches)); + } + Ok(out) + } + } + } + + /// End the capture, keeping it for `status` and `stop` to report. + pub fn end_capture(&mut self, reason: &str) { + if let Some(c) = &self.capture { + c.end(reason); + } + } + + /// Before the daemon exits: end the capture and let its reset go out. + pub async fn end_capture_before_exit(&mut self, reason: &str) { + if let Some(c) = &mut self.capture { + c.end(reason); + c.settle().await; + } + } + + pub fn capture_state(&self) -> Option<&'static str> { + self.capture.as_ref().map(|c| if c.is_running() { "running" } else { "ended" }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn log(filename: &str, level: &str, label: Option<(&str, &str)>) -> OsTraceLog { + serde_json::from_value(json!({ + "pid": 412, + // What the library produces for 01:02:03.004005: micros in the nanos field. + "timestamp": "2026-11-19T01:02:03.000004005", + "level": level, + "image_name": "/System/Library/Frameworks/UIKitCore.framework/UIKitCore", + "filename": filename, + "message": "tapped row", + "label": label.map(|(s, c)| json!({ "subsystem": s, "category": c })), + "procid": 412, + "thread_id": 7, + "image_offset": 0, + "image_uuid": "00000000-0000-0000-0000-000000000000", + "process_image_uuid": "00000000-0000-0000-0000-000000000000", + "mach_timestamp": 0, + })) + .unwrap() + } + + fn entry(process: &str, level: Level, message: &str) -> Entry { + Entry { + time: "2026-11-19T01:02:03.000000Z".into(), + pid: 1, + process: process.into(), + sender: process.into(), + level, + subsystem: None, + category: None, + message: message.into(), + } + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("iph-syslog-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn lines(path: &Path) -> Vec { + std::fs::read_to_string(path) + .unwrap() + .lines() + .map(|l| serde_json::from_str(l).expect("every line is JSON")) + .collect() + } + + #[test] + fn an_entry_becomes_one_json_line_named_by_its_executable() { + let e = Entry::from(log("/Applications/Preferences.app/Preferences", "Error", Some(("com.apple.settings", "ui")))); + let v: Value = serde_json::from_str(&e.line()).unwrap(); + assert_eq!( + v, + json!({ + "time": "2026-11-19T01:02:03.004005Z", "pid": 412, "process": "Preferences", "sender": "UIKitCore", + "level": "error", "subsystem": "com.apple.settings", "category": "ui", "message": "tapped row", + }) + ); + let plain = Entry::from(log("/usr/libexec/backboardd", "Notice", None)); + let v: Value = serde_json::from_str(&plain.line()).unwrap(); + assert_eq!(v["process"], "backboardd"); + assert_eq!(v["level"], "notice"); + assert!(v.get("subsystem").is_none()); + } + + #[test] + fn the_filter_keeps_named_processes_at_or_above_a_level() { + let any = Filter::default(); + assert!(any.keeps(&entry("SpringBoard", Level::Debug, ""))); + let f = Filter { processes: vec!["Preferences".into(), "Papago".into()], min_level: Some(Level::Notice) }; + assert!(f.keeps(&entry("Preferences", Level::Notice, ""))); + assert!(f.keeps(&entry("Papago", Level::Fault, ""))); + assert!(!f.keeps(&entry("Preferences", Level::Info, ""))); + assert!(!f.keeps(&entry("SpringBoard", Level::Error, ""))); + // Exact names only: a prefix is another process. + assert!(!f.keeps(&entry("PreferencesExtension", Level::Error, ""))); + } + + #[test] + fn only_an_entry_the_library_could_not_parse_is_skipped() { + let unparsed = IdeviceError::UnexpectedResponse("unknown log level byte value".into()); + let lost_place = IdeviceError::UnexpectedResponse("expected leading byte 0x02 at start of log packet".into()); + let gone = IdeviceError::Socket(std::io::Error::from(std::io::ErrorKind::ConnectionReset)); + assert!(skippable(&unparsed)); + assert!(!skippable(&lost_place)); + assert!(!skippable(&gone)); + } + + #[test] + fn device_levels_rank_by_severity_not_by_code() { + let levels: Vec = [LogLevel::Fault, LogLevel::Debug, LogLevel::Error, LogLevel::Notice, LogLevel::Info] + .into_iter() + .map(Level::from) + .collect(); + let mut sorted = levels.clone(); + sorted.sort(); + assert_eq!(sorted, [Level::Debug, Level::Info, Level::Notice, Level::Error, Level::Fault]); + } + + #[test] + fn the_file_rolls_over_at_its_size_with_whole_lines_in_both_parts() { + let dir = temp_dir("rotate"); + let path = dir.join("cap.jsonl"); + std::fs::write(rotated(&path), "left from before\n").unwrap(); + let mut sink = Sink::create(&path, 1000).unwrap(); + assert!(!rotated(&path).exists(), "an earlier part is removed at start"); + let line = json!({ "message": "x".repeat(80) }).to_string(); + for _ in 0..30 { + sink.write(&line).unwrap(); + } + assert!(sink.rotations >= 2); + for p in [&path, &rotated(&path)] { + assert!(std::fs::metadata(p).unwrap().len() <= 1000); + assert!(lines(p).iter().all(|v| v["message"].as_str().unwrap().len() == 80)); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_capture_ends_with_one_end_line_and_keeps_nothing_after_it() { + let dir = temp_dir("end"); + let path = dir.join("cap.jsonl"); + let filter = Filter { processes: vec!["Papago".into()], min_level: None }; + let mut live = Live::new(Sink::create(&path, 1 << 20).unwrap(), filter); + live.take(&entry("Papago", Level::Info, "one")).unwrap(); + live.take(&entry("SpringBoard", Level::Info, "other")).unwrap(); + live.end("the log stream ended: socket closed"); + live.end("stopped"); + live.take(&entry("Papago", Level::Info, "late")).unwrap(); + let got = lines(&path); + assert_eq!(got.len(), 2); + assert_eq!(got[0]["message"], "one"); + assert_eq!(got[1]["event"], "end"); + assert_eq!(got[1]["reason"], "the log stream ended: socket closed"); + assert_eq!((got[1]["seen"].as_u64(), got[1]["kept"].as_u64()), (Some(2), Some(1))); + assert_eq!(live.ended.as_deref(), Some("the log stream ended: socket closed")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn search_returns_the_latest_matches_cut_to_length() { + let dir = temp_dir("search"); + let older = dir.join("cap.jsonl.1"); + let newer = dir.join("cap.jsonl"); + // The current part first: starting it removes an earlier `.1`. + let mut b = Sink::create(&newer, 1 << 20).unwrap(); + let mut a = Sink::create(&older, 1 << 20).unwrap(); + a.write(r#"{"event":"start"}"#).unwrap(); + for i in 0..3 { + a.write(&entry("Papago", Level::Info, &format!("hit {i}")).line()).unwrap(); + } + b.write(&entry("Papago", Level::Info, "miss").line()).unwrap(); + b.write(&entry("Papago", Level::Info, &format!("hit 3 {}", "y".repeat(900))).line()).unwrap(); + b.write(r#"{"event":"end","reason":"hit"}"#).unwrap(); + let files = [older, newer]; + let re = Regex::new("^hit").unwrap(); + let (found, matched) = search(&files, Some(&re), 2); + assert_eq!(matched, 4); + assert_eq!(found.len(), 2); + assert_eq!(found[0]["message"], "hit 2"); + assert_eq!(found[1]["message"].as_str().unwrap().chars().count(), MATCH_CHARS); + assert_eq!(found[1]["message_cut"], true); + let (all, matched) = search(&files, None, 0); + assert_eq!((all.len(), matched), (0, 5)); + let _ = std::fs::remove_dir_all(&dir); + } + + fn parsed(args: Value) -> Res { + parse(&args, || PathBuf::from("/state/u.syslog.jsonl")) + } + + #[test] + fn each_action_takes_only_its_own_arguments() { + let Ok(Request::Start(spec)) = parsed(json!({ + "action": "start", "process": "Preferences", "level": "default", "pid": null, "max_mb": 2, + })) else { + panic!("start") + }; + assert_eq!(spec.filter.processes, ["Preferences"]); + assert_eq!(spec.filter.min_level, Some(Level::Notice)); + assert_eq!(spec.path, PathBuf::from("/state/u.syslog.jsonl")); + assert_eq!(spec.max_bytes, 2 * 1024 * 1024); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": "/tmp/x.jsonl" })) else { + panic!("start with a list") + }; + assert_eq!((spec.filter.processes.len(), spec.pid), (2, Some(7))); + assert_eq!(spec.path, PathBuf::from("/tmp/x.jsonl")); + + assert!(matches!(parsed(json!({ "action": "stop" })), Ok(Request::Stop(None)))); + let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "grep": "a+", "max": 5000 })) else { + panic!("stop with grep") + }; + assert_eq!(q.max, MAX_MATCHES as usize); + assert!(matches!(parsed(json!({ "action": "status" })), Ok(Request::Status))); + + for bad in [ + json!({}), + json!({ "action": "pause" }), + json!({ "action": "stop", "process": "A" }), + json!({ "action": "status", "grep": "a" }), + json!({ "action": "start", "output": "relative.jsonl" }), + json!({ "action": "start", "level": "loud" }), + json!({ "action": "start", "process": "/Applications/Preferences.app/Preferences" }), + json!({ "action": "start", "max_mb": 0 }), + json!({ "action": "stop", "grep": "(" }), + ] { + let err = parsed(bad.clone()).expect_err(&bad.to_string()); + assert_eq!(err.code, "invalid_argument", "{bad}"); + } + } +} From 42faec811f8471a8c32485ef185111bfa7d3dd6a Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 12:33:19 +0900 Subject: [PATCH 3/7] docs: describe `iph syslog` README and README.ko get a "Phone log" section with the file format, filters, the measured volume over Wi-Fi and what ends a capture. The agent skill says when to wrap steps in a capture and how to find an app's executable name. Co-Authored-By: Claude Opus 5.5 --- README.ko.md | 27 +++++++++++++++++++++++++-- README.md | 27 +++++++++++++++++++++++++-- site/index.html | 2 +- site/llms-full.txt | 4 +++- skills/iph/SKILL.md | 7 ++++++- 5 files changed, 60 insertions(+), 7 deletions(-) diff --git a/README.ko.md b/README.ko.md index 163dd4b..c99d1ba 100644 --- a/README.ko.md +++ b/README.ko.md @@ -159,6 +159,7 @@ Apple 기기 연결 서비스가 필요합니다. CLI·MCP·스크립트는 선 | `iph run <이름> [--arg k=v]` / `iph scripts` | 저장된 스크립트 실행 · 목록 | | `iph mcp [--tools a,b]` | MCP 서버 (stdio) | | `iph dnd ` | 방해금지 모드를 켜기, 원래 집중 모드로 되돌리기, 지금 상태 보기 | +| `iph syslog [--process 이름] [--pid N] [--level L] [-o 파일] [--max-mb N] [--grep RE] [--max N]` | 다른 명령을 쓰는 동안 폰의 로그를 파일로 받습니다. `stop`은 조건에 맞는 최근 항목을 돌려줄 수 있습니다. 아래 [폰 로그](#폰-로그) | | `iph stop` | 이 폰의 상주 프로세스 종료 | ### 셀렉터 @@ -239,6 +240,27 @@ memory_mb = 64 # 스크립트가 쓸 수 있는 메모리 - **필요한 것:** 제어 센터 첫 페이지에 '집중 모드' 항목이 있고, 앱을 쓰는 중에도 제어 센터가 열려야 합니다. 폰 언어가 한국어 · 영어가 아니면 `[dnd]`의 `control`, `focus`에 폰에 보이는 이름을 적으세요. - **막지 못하는 것:** 방해금지 모드에서도 뜨는 것(알람 · 타이머, 긴급 재난 문자, 방해금지 모드 설정에서 허용해 둔 사람 · 앱)과 시스템 팝업. 방해금지 모드가 켜진 동안 실제로 배너가 안 뜨는지는 따로 확인하지 않았습니다 (iOS의 동작에 기댑니다). +### 폰 로그 + +`iph syslog start`는 탭 · 읽기 · 스크립트를 그대로 쓰는 동안 폰이 남기는 로그를 JSON Lines 파일로 받습니다. `iph syslog stop`으로 끝내면, 탭 뒤에 앱이 무엇을 남겼는지 테스트나 에이전트가 확인할 수 있습니다. 맥에서 `sudo log collect`를 돌리지 않아도 됩니다. + +```sh +iph syslog start --process Preferences # 설정 앱의 실행 파일 이름 +iph launch com.apple.Preferences --restart +iph tap "배터리" +iph syslog stop --grep "battery" --max 20 # 메시지가 맞는 최근 항목 20개 +``` + +- **파일:** `~/Library/Application Support/iph/.syslog.jsonl` (나만 읽을 수 있습니다), 또는 `-o <파일>`. 한 줄이 한 항목입니다. `time`(UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. 기록은 `{"event": "start", …}` 줄로 시작해 `{"event": "end", "reason": …}` 줄로 끝납니다. `end` 줄이 없으면 상주 프로세스가 강제로 끝난 것입니다. 다시 시작하면 폰이 로그를 보내기 시작한 뒤에 파일을 비웁니다. 실패한 `start`는 파일을 건드리지 않습니다. +- **거르기:** `--process`는 실행 파일 이름이 정확히 같은 항목만 남깁니다 (여러 번 줄 수 있습니다). 앱을 다시 띄워도 계속 걸립니다. 설정 앱은 `Preferences`입니다. 다른 앱은 거르지 않고 한 번 받아서 `process` 칸을 보세요. `--level`은 debug, info, notice, error, fault 중 고른 것보다 낮은 항목을 뺍니다. `--pid`는 폰이 그 프로세스의 항목만 보내게 합니다. +- **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. `--max-mb` MiB(기본 64)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 그래서 거르지 않은 기록은 대략 마지막 1~2분만 남습니다. 길게 받을 때는 `--process`로 거르세요. +- **다른 명령에 주는 부담:** 거르지 않은 기록을 켜 둔 동안 탭과 읽기 모두 중앙값이 10% 안쪽으로 늘었습니다 (탭 10회 · 읽기 5회씩 비교, 한 번 측정). +- **`stop`:** `seen`(폰이 보낸 항목 수), `kept`(파일에 쓴 수), `rotations`, 끝난 이유를 돌려줍니다. `--grep`(메시지에 거는 정규식)이나 `--max`를 주면 조건에 맞는 최근 항목을 `--max`개까지(기본 50, 최대 1000) 함께 돌려줍니다. 메시지는 500자에서 자르고, 맞은 항목 전체 수는 `matched`에 있습니다. +- **기록이 끝나는 때:** `stop`, 연결이 끊겼을 때, `iph`가 연결을 새로 맺을 때 (명령이 시간을 넘기거나 폰이 답하지 않을 때), `iph stop`, 새 빌드의 `iph`가 상주 프로세스를 바꿀 때, 상주 프로세스가 오래 쓰이지 않아 끝날 때 (기록 중이어도 상주 프로세스는 그대로 끝납니다). 어느 것인지는 `end` 줄과 `status`에 나옵니다. 저절로 다시 시작하지 않으므로 로그에 빈 구간이 생기면 드러납니다. 기록은 한 번에 하나이고, 두 번째 `start`는 `capture_running`으로 실패합니다. +- **연결이 끊긴 직후**에는 폰이 다음 기록에 약 20~30초 동안 아무것도 보내지 않습니다. 그동안 `status`의 `hint`가 이를 알려 줍니다. +- **비공개 값:** 앱이 로그에서 비공개로 표시한 값은 콘솔 앱에서처럼 ``로 옵니다. 한 앱을 띄울 때 받은 항목 가운데 약 5분의 1에 들어 있었습니다. +- 스크립트에서는 `syslog(action, opts)`, MCP에서는 `iph_syslog`입니다. 스크립트는 파일 위치를 정하지 못합니다. `batch`에는 없습니다. 기록은 그것을 시작한 호출보다 오래가기 때문입니다. + ## 스크립트 자주 하는 순서는 자바스크립트로 적어 한 번에 실행합니다. `read`, `tap`, `scroll` 같은 명령이 그대로 함수이고, 반복 · 조건 · 변수는 언어의 것을 씁니다. 엔진(QuickJS)이 `iph` 안에 들어 있어 따로 설치할 것은 없습니다. @@ -281,6 +303,7 @@ iph scripts # 저장된 스크립트 목록 | `readField({selector, take, regex})` | 값 하나를 글자로. `take`: `value`(기본), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | 목록을 스크롤하며 겹치지 않게 모아 `{rows, scrolls, ended}`로 돌려줍니다 | | `sleep(ms)` · `log(…)` · `output(k, v)` | 대기 · 기록 · 결과에 값 넣기 | +| `syslog(action, {process, pid, level, grep, max})` | `-o` 없는 `iph syslog`입니다. 파일은 `iph`의 상태 폴더에 남습니다. `inputs_sent`에 세지 않습니다 | - 함수가 돌려주는 것은 같은 이름의 CLI 명령이 내는 JSON 객체 그대로입니다 (`tap("일반").screen_changed`, `read().elements`). 셀렉터는 문자열과 객체 둘 다 됩니다. - **실패는 예외입니다.** 실패한 호출은 `Error`를 던지고, `e.code`, `e.outcome`, `e.hint`, `e.result`(결과 객체 전체)가 붙어 있습니다. 잡지 않으면 스크립트가 거기서 멈추고 결과에 `failed_call: {cmd, line, outcome}`, `reason: {code, message}`, `screen_summary`가 담깁니다. 추측해서 진행하지 않습니다. 없어도 되는 것을 눌러 볼 때만 `try { … } catch (e) { … }`로 잡으세요. @@ -327,7 +350,7 @@ ln -s "$PWD/skills/iph" ~/.claude/skills/iph # Claude Code ln -s "$PWD/skills/iph" ~/.codex/skills/iph # Codex ``` -도구: `iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`. 인자와 결과는 CLI와 같고, `iph_launch`는 `arguments`(글자 배열)와 `environment`(글자 값 객체)를 받습니다. `iph_script`는 `code`(자바스크립트)와 `args`를, `iph_run`은 `name`과 `args`를 받습니다. 에이전트용 안내는 [skills/iph/SKILL.md](skills/iph/SKILL.md)에 있습니다. +도구: `iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`, `iph_syslog`. 인자와 결과는 CLI와 같고, `iph_launch`는 `arguments`(글자 배열)와 `environment`(글자 값 객체)를 받습니다. `iph_script`는 `code`(자바스크립트)와 `args`를, `iph_run`은 `name`과 `args`를 받습니다. 에이전트용 안내는 [skills/iph/SKILL.md](skills/iph/SKILL.md)에 있습니다. ## 속도 @@ -428,4 +451,4 @@ IPH_PCAP=<폴더> iph … # 터널의 패킷을 Wireshark용 파일로 남김. ## 라이선스 -MIT. [LICENSE](LICENSE). 미디어 세션 시작 부분은 idevice의 예제 도구를 고쳐 썼습니다 ([LICENSE.idevice](LICENSE.idevice)). `src/tcp`는 터널의 TCP 스택으로, jktcp 0.1.8(MIT)을 가져와 연결을 포기하기까지의 시간 상수 두 개를 늘리고 패킷 기록의 마이크로초 값을 고친 것입니다 ([LICENSE.jktcp](LICENSE.jktcp)). +MIT. [LICENSE](LICENSE). 미디어 세션 시작 부분은 idevice의 예제 도구를 고쳐 썼습니다 ([LICENSE.idevice](LICENSE.idevice)). `src/tcp`는 터널의 TCP 스택으로, jktcp 0.1.8(MIT)을 가져와 연결을 포기하기까지의 시간 상수 두 개를 늘리고, 패킷 기록의 마이크로초 값을 고치고, `iph syslog`를 위해 연결 하나를 초기화(RST)하는 기능을 더한 것입니다 ([LICENSE.jktcp](LICENSE.jktcp)). diff --git a/README.md b/README.md index 9805f54..4f1d7c6 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ Every command prints JSON; add `--human` for people. The device is chosen by `-- | `iph run [--arg k=v]` / `iph scripts` | Run a saved script, list saved scripts | | `iph mcp [--tools a,b]` | MCP server on stdio | | `iph dnd ` | Turn Do Not Disturb on, put the earlier Focus back, or show the current state | +| `iph syslog [--process name] [--pid N] [--level L] [-o file] [--max-mb N] [--grep RE] [--max N]` | Write the phone's log to a file while other commands run; `stop` can return the latest matching entries. See [Phone log](#phone-log) | | `iph stop` | Stop the resident process for this phone | ### Selectors @@ -236,6 +237,27 @@ iph does not judge what it presses. Pay, send and order buttons are pressed like - **Needs:** the Focus control on Control Center's first page, and Control Center opening while an app is in front. For a phone in a language other than Korean or English, put the names the phone shows in `control` and `focus` under `[dnd]`. - **Not covered:** whatever comes through Do Not Disturb (alarms and timers, emergency alerts, people and apps allowed in the Do Not Disturb settings) and system pop-ups. Whether banners really stay away while Do Not Disturb is on was not tested separately (it relies on how iOS behaves). +### Phone log + +`iph syslog start` writes what the phone logs to a JSON Lines file while taps, reads and scripts go on as usual. `iph syslog stop` ends it, so a test or an agent can check what an app logged after a tap. No `sudo log collect` on the Mac is needed. + +```sh +iph syslog start --process Preferences # Settings' executable name +iph launch com.apple.Preferences --restart +iph tap "Battery" +iph syslog stop --grep "battery" --max 20 # the 20 latest entries whose message matches +``` + +- **The file:** `~/Library/Application Support/iph/.syslog.jsonl` (readable by you only), or `-o `. Each entry is one line: `time` (UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. A capture begins with a `{"event": "start", …}` line and finishes with `{"event": "end", "reason": …}`. A file without an `end` line was cut off by a killed resident process. Starting again empties the file once the phone has started sending; a `start` that fails leaves it as it was. +- **Filters:** `--process` keeps entries by executable name, exactly (repeatable). It keeps matching across app restarts. Settings is `Preferences`; for another app, start without a filter and look at the `process` field. `--level` drops anything below debug, info, notice, error or fault. `--pid` makes the phone send only that process's entries. +- **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At `--max-mb` MiB (64 by default) the file moves to `.1`, replacing the previous one (the `start` line goes with it), so an unfiltered capture keeps roughly the last minute or two. Filter with `--process` for anything longer. +- **Cost to other commands:** with an unfiltered capture running, the median tap and the median read each took under 10% longer (10 taps and 5 reads each way, one run). +- **`stop`:** returns `seen` (entries the phone sent), `kept` (written), `rotations` and why it ended. With `--grep` (a regular expression on the message) or `--max`, it also returns up to `--max` of the latest matching entries (50 by default, at most 1000), each message cut to 500 characters, and `matched`, the number that matched in all. +- **What ends a capture:** `stop`, a dropped connection, iph rebuilding its connections (after a command times out or the phone stops answering), `iph stop`, a newer build of iph replacing the resident process, or the resident process exiting after its idle time (a capture does not keep it alive). The `end` line and `status` say which. A capture is not restarted by itself, so a gap in the log is never hidden. One capture runs at a time; a second `start` fails with `capture_running`. +- **After a dropped connection** the phone sends nothing to the next capture for about 20 to 30 s. `status` says so in a `hint` while nothing has arrived. +- **Private values:** values an app marks private in its log calls arrive as ``, as in Console. In one app's launch, about a fifth of its entries carried one. +- Also in scripts as `syslog(action, opts)` and over MCP as `iph_syslog`. A script cannot choose the file. Not in `batch`: a capture outlives the call that started it. + ## Scripts A sequence you run often is written in JavaScript and runs in one call. The commands (`read`, `tap`, `scroll` …) are functions; loops, conditions and variables are the language's own. The engine (QuickJS) is inside `iph`, so there is nothing else to install. @@ -278,6 +300,7 @@ iph scripts # list saved scripts | `readField({selector, take, regex})` | One value, as text. `take`: `value` (default), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | Collect a list while scrolling, each row once; returns `{rows, scrolls, ended}` | | `sleep(ms)` · `log(…)` · `output(k, v)` | Wait, note, add a value to the result | +| `syslog(action, {process, pid, level, grep, max})` | `iph syslog` without `-o`: the file stays in iph's state directory. Not counted in `inputs_sent` | - A function returns the JSON object the CLI command of the same name prints (`tap("일반").screen_changed`, `read().elements`). Selectors can be strings or objects. - **A failure is an exception.** A call that fails throws an `Error` carrying `e.code`, `e.outcome`, `e.hint` and `e.result` (the whole result object). Uncaught, it ends the script, and the result has `failed_call: {cmd, line, outcome}`, `reason: {code, message}` and `screen_summary`. Nothing is guessed. Use `try { … } catch (e) { … }` only around something that may legitimately be missing. @@ -324,7 +347,7 @@ ln -s "$PWD/skills/iph" ~/.claude/skills/iph # Claude Code ln -s "$PWD/skills/iph" ~/.codex/skills/iph # Codex ``` -Tools: `iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`. Arguments and results are the same as the CLI's; `iph_launch` takes `arguments` (array of strings) and `environment` (object of strings). `iph_script` takes `code` (JavaScript) and `args`; `iph_run` takes `name` and `args`. Guidance for agents: [skills/iph/SKILL.md](skills/iph/SKILL.md). +Tools: `iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`, `iph_syslog`. Arguments and results are the same as the CLI's; `iph_launch` takes `arguments` (array of strings) and `environment` (object of strings). `iph_script` takes `code` (JavaScript) and `args`; `iph_run` takes `name` and `args`. Guidance for agents: [skills/iph/SKILL.md](skills/iph/SKILL.md). ## Speed @@ -425,4 +448,4 @@ IPH_PCAP= iph … # writes the tunnel's packets out for Wireshark; they hol ## License -MIT, see [LICENSE](LICENSE). The media-session bring-up is adapted from an idevice example tool ([LICENSE.idevice](LICENSE.idevice)). `src/tcp` is the tunnel's TCP stack, taken from jktcp 0.1.8 (MIT), with two constants changed so that it waits longer before giving a connection up, and the microseconds of its packet capture fixed ([LICENSE.jktcp](LICENSE.jktcp)). +MIT, see [LICENSE](LICENSE). The media-session bring-up is adapted from an idevice example tool ([LICENSE.idevice](LICENSE.idevice)). `src/tcp` is the tunnel's TCP stack, taken from jktcp 0.1.8 (MIT), with two constants changed so that it waits longer before giving a connection up, the microseconds of its packet capture fixed, and a way to reset one connection (RST) added for `iph syslog` ([LICENSE.jktcp](LICENSE.jktcp)). diff --git a/site/index.html b/site/index.html index 5bc54fa..266007f 100644 --- a/site/index.html +++ b/site/index.html @@ -1180,7 +1180,7 @@

Embedded QuickJS Scripting (iph script)

First-Class MCP Server & Agent Skill

-

Run iph mcp over stdio to expose 19 tools (iph_read, iph_tap, iph_pinch, iph_script, iph_dnd, …) to Claude Code or Codex — or link skills/iph/SKILL.md for shell-native driving.

+

Run iph mcp over stdio to expose 20 tools (iph_read, iph_tap, iph_pinch, iph_script, iph_dnd, …) to Claude Code or Codex — or link skills/iph/SKILL.md for shell-native driving.

claude mcp add iph -- iph mcp
 codex  mcp add iph -- iph mcp
 iph mcp --tools read,find,script
diff --git a/site/llms-full.txt b/site/llms-full.txt index dbe0290..2749071 100644 --- a/site/llms-full.txt +++ b/site/llms-full.txt @@ -102,6 +102,7 @@ Every command outputs JSON by default; pass `--human` for human-readable output. - `iph script [--arg k=v]` — run QuickJS JavaScript automation in one call - `iph run [--arg k=v]` / `iph scripts` — run or list saved scripts (`~/.config/iph/scripts/.js`) - `iph mcp [--tools a,b]` — run stdio MCP server +- `iph syslog [--app bundle|name] [--process NAME] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o file]` — capture the phone's unified log into a memory buffer and read new entries with a cursor while other commands run - `iph dnd ` — toggle Do Not Disturb to prevent notification banners from intercepting top-of-screen taps - `iph diagnose [--wifi] [-- ]` — collect a diagnostic bundle for issue reporting - `iph stop` — stop the resident daemon for the selected phone @@ -145,6 +146,7 @@ Available globals inside `iph script` (sandboxed: no filesystem, network, or pro - `scroll(direction, {until, max})` - `type(text, {clear, submit})`, `key(name)`, `button(name)` - `launch(app, {restart, arguments, environment})` +- `syslog(action, opts)` — `start`, `read`, `status` or `stop`; scripts cannot write a file, and a capture outlives the script - `waitFor(selector, {timeout_ms})` - `readField({selector, take, regex})` - `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` @@ -154,4 +156,4 @@ Available globals inside `iph script` (sandboxed: no filesystem, network, or pro ## MCP Tools (`iph mcp`) -`iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`. +`iph_connect`, `iph_read`, `iph_find`, `iph_tap`, `iph_swipe`, `iph_pinch`, `iph_scroll`, `iph_type`, `iph_key`, `iph_button`, `iph_launch`, `iph_apps`, `iph_screenshot`, `iph_batch`, `iph_script`, `iph_run`, `iph_scripts`, `iph_doctor`, `iph_dnd`, `iph_syslog`. diff --git a/skills/iph/SKILL.md b/skills/iph/SKILL.md index bfadda9..badcedd 100644 --- a/skills/iph/SKILL.md +++ b/skills/iph/SKILL.md @@ -79,6 +79,7 @@ A script is the body of a function, so `return` ends it. The commands are functi - `readList({row, columns, key, group, stop_below, max_scrolls})` scrolls a list and returns `{rows, scrolls, ended}` with each row once. `columns: {name: {take, regex}}`, or `{name: {value: "…"}}` for a constant. `group: {selector, regex, as}` gives each row the heading it stands under (a date line), and `stop_below: N` stops once a heading's number falls below N. `key: "column"` names the column that identifies a row; use it when rows change while the list is read (a clock, time left). - `args` holds the `--arg k=v` values as text (`Number(args.n)` for a number). Return an object, or call `output(key, value)`, and it comes back as `outputs`. `log(…)` lines come back as `logs`. `sleep(ms)` waits. - Any call takes `hint: "…"`: what to tell the person if the script stops there. A screen that waits for Face ID: `waitFor(sel, { timeout_ms: 40000, hint: "폰을 봐 주세요" })`. +- `syslog(action, {process, pid, level, grep, max})` captures the phone's log, as `iph syslog` does below. - There are no files, no network and no timers. `Date`, `JSON`, `RegExp` and the rest of the language work. ### When a call fails @@ -117,9 +118,13 @@ After `launch`, that app must stay in front; if another one comes up, the script `iph type "글"` pastes into the field that has the keyboard, so tap the field first. `--clear` replaces the content, `--submit` presses Return. The result has `value` (what the field shows now) and `clipboard_restored`. iph does not judge `value`: apps format, mask and correct what is pasted (`30000` shows as `₩ 30,000`), so you decide whether it is right. A `value` that is still what the field held before means the paste did not happen; before `--submit` sends something that matters, type without it, look at `value`, then `iph key return`. When the user had copied something in an app, it cannot be put back (`clipboard_restored: false`, `clipboard_note`); tell the user. The on-screen keyboard disappears for a moment while typing; that is expected. +## What the app logged + +To check what an app logged after a tap, wrap the steps in a capture: `iph syslog start --process `, the steps, then `iph syslog stop --grep --max 20` (MCP: `iph_syslog` with `action`). The executable name is not the app's display name (Settings is `Preferences`); when you do not know it, start without `--process`, stop after a second, and look at the `process` field of the entries for the app's pid. Unfiltered over Wi-Fi the phone sends thousands of entries a second, so filter for anything longer. If `stop` says `seen: 0`, nothing arrived: after a dropped connection the phone sends nothing for about 30 s, and `status` gives a `hint` while it waits. Values the app marked private arrive as ``; that is the app's choice, not a failure. The entries are the user's data: quote only what the task needs. + ## Commands at a glance -`read`, `find`, `tap`, `swipe`, `pinch`, `scroll`, `type`, `key`, `button`, `launch`, `apps` (bundle ids), `screenshot`, `script`, `run`, `scripts`, `batch`, `dnd`, `doctor`, `connect --ip `, `devices`, `stop`. `iph --help` has the flags; add `--human` to read a result yourself. +`read`, `find`, `tap`, `swipe`, `pinch`, `scroll`, `type`, `key`, `button`, `launch`, `apps` (bundle ids), `screenshot`, `script`, `run`, `scripts`, `batch`, `dnd`, `syslog`, `doctor`, `connect --ip `, `devices`, `stop`. `iph --help` has the flags; add `--human` to read a result yourself. ## When something is off From a138be53d4f7c79fdb41aacabe26c2f65b79cf35 Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 15:42:19 +0900 Subject: [PATCH 4/7] fix: buffer the syslog file, and rotate it without renaming an open file Review of the capture file writer: - The file is wrapped in a BufWriter. A small task of its own flushes it every 250 ms, so a quiet capture's last lines still reach the file; it is not the reading task, which must never be interrupted between two reads of an entry. The `end` line is flushed when a capture ends. - A rotation flushes and drops the file handle, removes an existing `.1`, then renames, so it does not depend on how a platform treats an open file or an existing target. CI now runs the tests on Windows. The rotation test rolls over twice, which is the rename over an existing `.1`. If a step of the rotation fails, the file that holds the last entry stays open and the `end` line still goes after it, so the file does not read like one a killed daemon left. - `max_mb` takes 1 to 4096 and the byte size is computed with checked_mul; anything else is `invalid_argument`. Co-Authored-By: Claude Opus 5.5 --- README.ko.md | 2 +- README.md | 2 +- src/main.rs | 2 +- src/mcp.rs | 2 +- src/syslog.rs | 210 ++++++++++++++++++++++++++++++++++++++++++-------- 5 files changed, 182 insertions(+), 36 deletions(-) diff --git a/README.ko.md b/README.ko.md index c99d1ba..173c09b 100644 --- a/README.ko.md +++ b/README.ko.md @@ -253,7 +253,7 @@ iph syslog stop --grep "battery" --max 20 # 메시지가 맞는 최근 항 - **파일:** `~/Library/Application Support/iph/.syslog.jsonl` (나만 읽을 수 있습니다), 또는 `-o <파일>`. 한 줄이 한 항목입니다. `time`(UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. 기록은 `{"event": "start", …}` 줄로 시작해 `{"event": "end", "reason": …}` 줄로 끝납니다. `end` 줄이 없으면 상주 프로세스가 강제로 끝난 것입니다. 다시 시작하면 폰이 로그를 보내기 시작한 뒤에 파일을 비웁니다. 실패한 `start`는 파일을 건드리지 않습니다. - **거르기:** `--process`는 실행 파일 이름이 정확히 같은 항목만 남깁니다 (여러 번 줄 수 있습니다). 앱을 다시 띄워도 계속 걸립니다. 설정 앱은 `Preferences`입니다. 다른 앱은 거르지 않고 한 번 받아서 `process` 칸을 보세요. `--level`은 debug, info, notice, error, fault 중 고른 것보다 낮은 항목을 뺍니다. `--pid`는 폰이 그 프로세스의 항목만 보내게 합니다. -- **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. `--max-mb` MiB(기본 64)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 그래서 거르지 않은 기록은 대략 마지막 1~2분만 남습니다. 길게 받을 때는 `--process`로 거르세요. +- **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. `--max-mb` MiB(1~4096, 기본 64)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 그래서 거르지 않은 기록은 대략 마지막 1~2분만 남습니다. 길게 받을 때는 `--process`로 거르세요. - **다른 명령에 주는 부담:** 거르지 않은 기록을 켜 둔 동안 탭과 읽기 모두 중앙값이 10% 안쪽으로 늘었습니다 (탭 10회 · 읽기 5회씩 비교, 한 번 측정). - **`stop`:** `seen`(폰이 보낸 항목 수), `kept`(파일에 쓴 수), `rotations`, 끝난 이유를 돌려줍니다. `--grep`(메시지에 거는 정규식)이나 `--max`를 주면 조건에 맞는 최근 항목을 `--max`개까지(기본 50, 최대 1000) 함께 돌려줍니다. 메시지는 500자에서 자르고, 맞은 항목 전체 수는 `matched`에 있습니다. - **기록이 끝나는 때:** `stop`, 연결이 끊겼을 때, `iph`가 연결을 새로 맺을 때 (명령이 시간을 넘기거나 폰이 답하지 않을 때), `iph stop`, 새 빌드의 `iph`가 상주 프로세스를 바꿀 때, 상주 프로세스가 오래 쓰이지 않아 끝날 때 (기록 중이어도 상주 프로세스는 그대로 끝납니다). 어느 것인지는 `end` 줄과 `status`에 나옵니다. 저절로 다시 시작하지 않으므로 로그에 빈 구간이 생기면 드러납니다. 기록은 한 번에 하나이고, 두 번째 `start`는 `capture_running`으로 실패합니다. diff --git a/README.md b/README.md index 4f1d7c6..5719b22 100644 --- a/README.md +++ b/README.md @@ -250,7 +250,7 @@ iph syslog stop --grep "battery" --max 20 # the 20 latest entries whose mess - **The file:** `~/Library/Application Support/iph/.syslog.jsonl` (readable by you only), or `-o `. Each entry is one line: `time` (UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. A capture begins with a `{"event": "start", …}` line and finishes with `{"event": "end", "reason": …}`. A file without an `end` line was cut off by a killed resident process. Starting again empties the file once the phone has started sending; a `start` that fails leaves it as it was. - **Filters:** `--process` keeps entries by executable name, exactly (repeatable). It keeps matching across app restarts. Settings is `Preferences`; for another app, start without a filter and look at the `process` field. `--level` drops anything below debug, info, notice, error or fault. `--pid` makes the phone send only that process's entries. -- **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At `--max-mb` MiB (64 by default) the file moves to `.1`, replacing the previous one (the `start` line goes with it), so an unfiltered capture keeps roughly the last minute or two. Filter with `--process` for anything longer. +- **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At `--max-mb` MiB (1 to 4096, 64 by default) the file moves to `.1`, replacing the previous one (the `start` line goes with it), so an unfiltered capture keeps roughly the last minute or two. Filter with `--process` for anything longer. - **Cost to other commands:** with an unfiltered capture running, the median tap and the median read each took under 10% longer (10 taps and 5 reads each way, one run). - **`stop`:** returns `seen` (entries the phone sent), `kept` (written), `rotations` and why it ended. With `--grep` (a regular expression on the message) or `--max`, it also returns up to `--max` of the latest matching entries (50 by default, at most 1000), each message cut to 500 characters, and `matched`, the number that matched in all. - **What ends a capture:** `stop`, a dropped connection, iph rebuilding its connections (after a command times out or the phone stops answering), `iph stop`, a newer build of iph replacing the resident process, or the resident process exiting after its idle time (a capture does not keep it alive). The `end` line and `status` say which. A capture is not restarted by itself, so a gap in the log is never hidden. One capture runs at a time; a second `start` fails with `capture_running`. diff --git a/src/main.rs b/src/main.rs index 5828edb..e803bef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -203,7 +203,7 @@ enum Cmd { /// start: the file to write (default: .syslog.jsonl in the state directory). #[arg(short, long)] output: Option, - /// start: move the file to .1 when it reaches this size (default 64). + /// start: move the file to .1 when it reaches this size in MiB (1 to 4096, default 64). #[arg(long)] max_mb: Option, /// stop: return the entries whose message matches this regular expression. diff --git a/src/mcp.rs b/src/mcp.rs index ab38438..1159881 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -180,7 +180,7 @@ fn tools() -> Vec { "pid": { "type": "integer", "description": "start: keep only this pid (filtered on the phone)." }, "level": { "type": "string", "enum": ["debug", "info", "notice", "error", "fault"], "description": "start: lowest level kept." }, "output": { "type": "string", "description": "start: absolute path of the file (default: in iph's state directory)." }, - "max_mb": { "type": "integer", "description": "start: move the file to .1 at this size (default 64)." }, + "max_mb": { "type": "integer", "description": "start: move the file to .1 at this size in MiB (1 to 4096, default 64)." }, "grep": { "type": "string", "description": "stop: regular expression matched against each message." }, "max": { "type": "integer", "description": "stop: most entries returned, the latest (default 50, at most 1000)." }, }), diff --git a/src/syslog.rs b/src/syslog.rs index 92bba97..10ef6fb 100644 --- a/src/syslog.rs +++ b/src/syslog.rs @@ -10,9 +10,10 @@ use std::{ collections::VecDeque, fs::File, - io::{BufRead, BufReader, Write}, + io::{BufRead, BufReader, BufWriter, Write}, path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, Weak}, + time::Duration, }; use idevice::{ @@ -31,6 +32,11 @@ use crate::{ }; const DEFAULT_MAX_MB: u64 = 64; +/// The most `max_mb` takes. A part is read back whole by whoever opens it. +const MAX_FILE_MB: u64 = 4096; +/// How long a written line may wait in the buffer before it is flushed. +const FLUSH_EVERY: Duration = Duration::from_millis(250); +const FILE_BUFFER: usize = 32 * 1024; const DEFAULT_MATCHES: u64 = 50; const MAX_MATCHES: u64 = 1000; /// Longest message a match returns; the file keeps the whole message. @@ -247,14 +253,16 @@ pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res { @@ -283,7 +291,7 @@ pub fn rotated(path: &Path) -> PathBuf { path.with_file_name(name) } -fn open_private(path: &Path) -> std::io::Result { +fn open_private(path: &Path) -> std::io::Result> { let file = paths::private_file().write(true).create(true).truncate(true).open(path)?; #[cfg(unix)] { @@ -291,14 +299,20 @@ fn open_private(path: &Path) -> std::io::Result { use std::os::unix::fs::PermissionsExt; file.set_permissions(std::fs::Permissions::from_mode(0o600))?; } - Ok(file) + Ok(BufWriter::with_capacity(FILE_BUFFER, file)) } /// The file, kept under a size: once the next line would pass it, the file /// becomes `.1` (replacing an older one) and a new file starts. +/// +/// Writes are buffered. A line reaches the file when the buffer fills, on +/// `flush` (the capture flushes every `FLUSH_EVERY` and when it ends) and +/// before a rotation. The buffer only ever holds whole lines, so a killed +/// process loses at most the last few, never half of one. pub struct Sink { path: PathBuf, - file: File, + /// `None` only after a rotation that could reopen neither part. + writer: Option>, size: u64, cap: u64, pub rotations: u32, @@ -306,27 +320,70 @@ pub struct Sink { impl Sink { pub fn create(path: &Path, cap: u64) -> std::io::Result { - let file = open_private(path)?; + let writer = open_private(path)?; // A part left from an earlier capture would read as this one's. let _ = std::fs::remove_file(rotated(path)); - Ok(Self { path: path.to_path_buf(), file, size: 0, cap, rotations: 0 }) + Ok(Self { path: path.to_path_buf(), writer: Some(writer), size: 0, cap, rotations: 0 }) } - /// Write one line in a single call, so nothing that stops the writer - /// leaves half a line behind. pub fn write(&mut self, line: &str) -> std::io::Result<()> { + if self.size > 0 && self.size + line.len() as u64 + 1 > self.cap { + self.rotate()?; + } + self.append(line) + } + + /// Without rotating first, for the `end` line: it goes right after the + /// last entry, even past the size or after a rotation that failed. + fn append(&mut self, line: &str) -> std::io::Result<()> { let bytes = format!("{line}\n"); - let len = bytes.len() as u64; - if self.size > 0 && self.size + len > self.cap { - std::fs::rename(&self.path, rotated(&self.path))?; - self.file = open_private(&self.path)?; - self.size = 0; - self.rotations += 1; - } - self.file.write_all(bytes.as_bytes())?; - self.size += len; + self.writer.as_mut().ok_or_else(Self::closed)?.write_all(bytes.as_bytes())?; + self.size += bytes.len() as u64; Ok(()) } + + pub fn flush(&mut self) -> std::io::Result<()> { + self.writer.as_mut().map_or(Ok(()), |w| w.flush()) + } + + /// On failure the file that holds the last entry stays open, so the + /// `end` line still lands after it. + fn rotate(&mut self) -> std::io::Result<()> { + // The handle goes first: Windows renames neither an open file nor + // over an existing one. + if let Some(writer) = self.writer.as_mut() { + writer.flush()?; + } + self.writer = None; + let previous = rotated(&self.path); + let renamed = match std::fs::remove_file(&previous) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e), + _ => std::fs::rename(&self.path, &previous), + }; + if let Err(e) = renamed { + self.writer = reopen(&self.path); + return Err(e); + } + match open_private(&self.path) { + Ok(writer) => self.writer = Some(writer), + Err(e) => { + self.writer = reopen(&previous); + return Err(e); + } + } + self.size = 0; + self.rotations += 1; + Ok(()) + } + + fn closed() -> std::io::Error { + std::io::Error::other("the file could not be reopened after a rotation") + } +} + +fn reopen(path: &Path) -> Option> { + let file = std::fs::OpenOptions::new().append(true).open(path).ok()?; + Some(BufWriter::with_capacity(FILE_BUFFER, file)) } /// What the reading task and the session share. @@ -371,11 +428,27 @@ impl Live { "unparsed": self.unparsed, "rotations": self.sink.rotations, }); - let _ = self.sink.write(&line.to_string()); + // The end line is what tells a reader the capture finished. + let _ = self.sink.append(&line.to_string()).and_then(|()| self.sink.flush()); self.ended = Some(reason.to_string()); } } +/// Puts buffered lines in the file while the stream is quiet. Not part of +/// the reading task: that one must never be interrupted between two reads. +async fn flusher(live: Weak>) { + let mut tick = tokio::time::interval(FLUSH_EVERY); + loop { + tick.tick().await; + let Some(live) = live.upgrade() else { return }; + let mut live = live.lock().unwrap(); + if live.ended.is_some() { + return; + } + let _ = live.sink.flush(); + } +} + /// The library reads a whole entry before parsing it, so an entry it cannot /// parse costs only that entry. A missing leading byte means the stream lost /// its place, and nothing after it can be trusted. @@ -409,6 +482,7 @@ pub struct Capture { started: std::time::Instant, live: Arc>, task: tokio::task::JoinHandle<()>, + flusher: tokio::task::JoinHandle<()>, reset: Reset, } @@ -419,6 +493,7 @@ impl Capture { pub fn end(&self, reason: &str) { self.reset.now(); self.task.abort(); + self.flusher.abort(); self.live.lock().unwrap().end(reason); } @@ -556,8 +631,9 @@ impl Session { } let live = Arc::new(Mutex::new(live)); let task = tokio::task::spawn_local(pump(stream, live.clone())); + let flusher = tokio::task::spawn_local(flusher(Arc::downgrade(&live))); let started = std::time::Instant::now(); - let capture = Capture { spec, started_at, started, live, task, reset }; + let capture = Capture { spec, started_at, started, live, task, flusher, reset }; let report = capture.report(); self.capture = Some(capture); Ok(report) @@ -709,25 +785,82 @@ mod tests { let dir = temp_dir("rotate"); let path = dir.join("cap.jsonl"); std::fs::write(rotated(&path), "left from before\n").unwrap(); - let mut sink = Sink::create(&path, 1000).unwrap(); + let line = |i: u32| json!({ "i": format!("{i:02}"), "message": "x".repeat(80) }).to_string(); + let part = 10 * (line(0).len() as u64 + 1); + let mut sink = Sink::create(&path, part).unwrap(); assert!(!rotated(&path).exists(), "an earlier part is removed at start"); - let line = json!({ "message": "x".repeat(80) }).to_string(); - for _ in 0..30 { - sink.write(&line).unwrap(); + // Ten lines fit in a part, so 25 lines rotate twice and the second + // rotation renames over the `.1` the first one made. + for i in 0..25 { + sink.write(&line(i)).unwrap(); } - assert!(sink.rotations >= 2); + sink.flush().unwrap(); + assert_eq!(sink.rotations, 2); + let indexes = |p: &Path| lines(p).iter().map(|v| v["i"].as_str().unwrap().parse().unwrap()).collect::>(); + assert_eq!(indexes(&rotated(&path)), (10..20).collect::>(), "only the last full part is kept"); + assert_eq!(indexes(&path), (20..25).collect::>()); for p in [&path, &rotated(&path)] { - assert!(std::fs::metadata(p).unwrap().len() <= 1000); + assert!(std::fs::metadata(p).unwrap().len() <= part); assert!(lines(p).iter().all(|v| v["message"].as_str().unwrap().len() == 80)); } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::metadata(rotated(&path)).unwrap().permissions().mode() & 0o777, 0o600); } let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_rotation_that_fails_still_ends_the_file_with_the_end_line() { + let dir = temp_dir("rotate-fail"); + let path = dir.join("cap.jsonl"); + let mut sink = Sink::create(&path, 200).unwrap(); + // A directory where the previous part goes: the rotation cannot clear it. + std::fs::create_dir_all(rotated(&path).join("x")).unwrap(); + sink.write(&json!({ "message": "a".repeat(100) }).to_string()).unwrap(); + assert!(sink.write(&json!({ "message": "b".repeat(100) }).to_string()).is_err()); + let mut live = Live::new(sink, Filter::default()); + live.end("cannot write the file"); + let got = lines(&path); + assert_eq!(got.len(), 2, "the entry before the failed rotation, then the end line"); + assert_eq!(got[1]["event"], "end"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_rotation_flushes_what_is_buffered_before_it_moves_the_file() { + let dir = temp_dir("rotate-flush"); + let path = dir.join("cap.jsonl"); + let mut sink = Sink::create(&path, 200).unwrap(); + sink.write(&json!({ "message": "a".repeat(100) }).to_string()).unwrap(); + // Nothing was flushed yet; the rotation must not lose this line. + sink.write(&json!({ "message": "b".repeat(100) }).to_string()).unwrap(); + assert_eq!(sink.rotations, 1); + sink.flush().unwrap(); + assert_eq!(lines(&rotated(&path))[0]["message"], "a".repeat(100)); + assert_eq!(lines(&path)[0]["message"], "b".repeat(100)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_flusher_puts_a_quiet_capture_in_the_file() { + let dir = temp_dir("flusher"); + let path = dir.join("cap.jsonl"); + let live = Arc::new(Mutex::new(Live::new(Sink::create(&path, 1 << 20).unwrap(), Filter::default()))); + live.lock().unwrap().take(&entry("Papago", Level::Info, "quiet")).unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap(); + runtime.block_on(async { + let task = tokio::spawn(flusher(Arc::downgrade(&live))); + tokio::time::sleep(FLUSH_EVERY * 4).await; + assert_eq!(lines(&path)[0]["message"], "quiet", "written without an explicit flush"); + live.lock().unwrap().end("stopped"); + tokio::time::timeout(FLUSH_EVERY * 4, task).await.expect("the flusher stops once the capture ended").unwrap(); + }); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_capture_ends_with_one_end_line_and_keeps_nothing_after_it() { let dir = temp_dir("end"); @@ -764,6 +897,8 @@ mod tests { b.write(&entry("Papago", Level::Info, "miss").line()).unwrap(); b.write(&entry("Papago", Level::Info, &format!("hit 3 {}", "y".repeat(900))).line()).unwrap(); b.write(r#"{"event":"end","reason":"hit"}"#).unwrap(); + a.flush().unwrap(); + b.flush().unwrap(); let files = [older, newer]; let re = Regex::new("^hit").unwrap(); let (found, matched) = search(&files, Some(&re), 2); @@ -781,6 +916,10 @@ mod tests { parse(&args, || PathBuf::from("/state/u.syslog.jsonl")) } + fn absolute(name: &str) -> PathBuf { + std::env::temp_dir().join(name) + } + #[test] fn each_action_takes_only_its_own_arguments() { let Ok(Request::Start(spec)) = parsed(json!({ @@ -792,11 +931,16 @@ mod tests { assert_eq!(spec.filter.min_level, Some(Level::Notice)); assert_eq!(spec.path, PathBuf::from("/state/u.syslog.jsonl")); assert_eq!(spec.max_bytes, 2 * 1024 * 1024); - let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": "/tmp/x.jsonl" })) else { + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "max_mb": MAX_FILE_MB })) else { + panic!("the largest max_mb") + }; + assert_eq!(spec.max_bytes, MAX_FILE_MB * 1024 * 1024); + let out = absolute("x.jsonl"); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": out })) else { panic!("start with a list") }; assert_eq!((spec.filter.processes.len(), spec.pid), (2, Some(7))); - assert_eq!(spec.path, PathBuf::from("/tmp/x.jsonl")); + assert_eq!(spec.path, out); assert!(matches!(parsed(json!({ "action": "stop" })), Ok(Request::Stop(None)))); let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "grep": "a+", "max": 5000 })) else { @@ -814,6 +958,8 @@ mod tests { json!({ "action": "start", "level": "loud" }), json!({ "action": "start", "process": "/Applications/Preferences.app/Preferences" }), json!({ "action": "start", "max_mb": 0 }), + json!({ "action": "start", "max_mb": MAX_FILE_MB + 1 }), + json!({ "action": "start", "max_mb": u64::MAX }), json!({ "action": "stop", "grep": "(" }), ] { let err = parsed(bad.clone()).expect_err(&bad.to_string()); From 97ca7d580db695e5c56fd9e689deaf6ff29dd20c Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 15:49:40 +0900 Subject: [PATCH 5/7] feat: keep the syslog in a memory ring buffer and add `iph syslog read` Review of the capture design: a file is the wrong default, and the only way to look at a running capture was to stop it. The kept entries now go into a ring buffer in the resident process, bounded by entry count and by bytes (100,000 and 64 MiB; `--buffer-entries` and `--buffer-mb` change them). Unfiltered over Wi-Fi the phone sent about 4,800 entries/s at 290 B of JSON each, so the default holds about 20 s of that worst case, and minutes of a filtered capture. Such an entry weighs about 430 B in memory, so 100,000 of them take about 41 MiB; the byte limit binds when messages run long. Each kept entry gets a `seq`, 1 for the first, so the ring is a gap-free run of seqs and a seq finds its entry by position. `read [--after SEQ] [--grep RE] [--max N]` (CLI, MCP `iph_syslog`, script `syslog("read", opts)`) returns the matching entries newer than `after`, oldest first, without stopping the capture. The result has a `cursor`: the last entry returned when `max` cut the page short, the newest seq when the whole buffer was looked through, so a grep that matches nothing still advances and a loop neither repeats nor skips an entry still in the buffer. `more` says a further match is already waiting, `dropped` how many entries newer than `after` were evicted before the read. A cursor is only meaningful in the capture that issued it: seqs start again at 1 with each capture, so after a new `start` a read goes without `after`. One that runs ahead of the buffer's newest seq is pulled back to it. A capture that ended can still be read until it is stopped; until then a new `start` fails with `capture_ended` rather than discard it. `stop --grep/--max` returns the latest matches from the buffer, as `entries` like `read` does; the file is no longer parsed back. `-o ` now only adds a JSON Lines file with whole messages and `--max-mb` rotation; without it nothing is written to disk, and `--max-mb` without `-o` is `invalid_argument`. `status` reports the buffer under `buffer`. `--human` prints counts, a page and a stop's matches. Co-Authored-By: Claude Opus 5.5 --- README.ko.md | 29 +- README.md | 29 +- skills/iph/SKILL.md | 4 +- src/human.rs | 135 +++++++ src/main.rs | 45 ++- src/mcp.rs | 35 +- src/script.rs | 18 +- src/syslog.rs | 955 +++++++++++++++++++++++++++++++++++--------- 8 files changed, 1012 insertions(+), 238 deletions(-) diff --git a/README.ko.md b/README.ko.md index 173c09b..04a2e99 100644 --- a/README.ko.md +++ b/README.ko.md @@ -159,7 +159,7 @@ Apple 기기 연결 서비스가 필요합니다. CLI·MCP·스크립트는 선 | `iph run <이름> [--arg k=v]` / `iph scripts` | 저장된 스크립트 실행 · 목록 | | `iph mcp [--tools a,b]` | MCP 서버 (stdio) | | `iph dnd ` | 방해금지 모드를 켜기, 원래 집중 모드로 되돌리기, 지금 상태 보기 | -| `iph syslog [--process 이름] [--pid N] [--level L] [-o 파일] [--max-mb N] [--grep RE] [--max N]` | 다른 명령을 쓰는 동안 폰의 로그를 파일로 받습니다. `stop`은 조건에 맞는 최근 항목을 돌려줄 수 있습니다. 아래 [폰 로그](#폰-로그) | +| `iph syslog [--process 이름] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o 파일]` | 다른 명령을 쓰는 동안 폰의 로그를 메모리에 모읍니다. `read`는 끝내지 않고 새로 들어온 항목만 돌려주고, `stop`은 조건에 맞는 최근 항목을 돌려줄 수 있습니다. 아래 [폰 로그](#폰-로그) | | `iph stop` | 이 폰의 상주 프로세스 종료 | ### 셀렉터 @@ -242,24 +242,33 @@ memory_mb = 64 # 스크립트가 쓸 수 있는 메모리 ### 폰 로그 -`iph syslog start`는 탭 · 읽기 · 스크립트를 그대로 쓰는 동안 폰이 남기는 로그를 JSON Lines 파일로 받습니다. `iph syslog stop`으로 끝내면, 탭 뒤에 앱이 무엇을 남겼는지 테스트나 에이전트가 확인할 수 있습니다. 맥에서 `sudo log collect`를 돌리지 않아도 됩니다. +`iph syslog start`는 탭 · 읽기 · 스크립트를 그대로 쓰는 동안 폰이 남기는 로그를 상주 프로세스 안의 버퍼에 모읍니다. `iph syslog read`는 기록을 끝내지 않고 그 뒤에 들어온 항목만 돌려주므로, 탭을 할 때마다 앱이 무엇을 남겼는지 테스트나 에이전트가 확인할 수 있습니다. 맥에서 `sudo log collect`를 돌리지 않아도 됩니다. ```sh iph syslog start --process Preferences # 설정 앱의 실행 파일 이름 iph launch com.apple.Preferences --restart iph tap "배터리" -iph syslog stop --grep "battery" --max 20 # 메시지가 맞는 최근 항목 20개 +iph syslog read --grep "battery" # 시작한 뒤 남은 로그. 결과에 "cursor": 12가 있습니다 +iph tap "일반" +iph syslog read --after 12 --grep "general" # 지난 읽기보다 새 항목만 +iph syslog stop # 또는 stop --grep "general" --max 20 ``` -- **파일:** `~/Library/Application Support/iph/.syslog.jsonl` (나만 읽을 수 있습니다), 또는 `-o <파일>`. 한 줄이 한 항목입니다. `time`(UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. 기록은 `{"event": "start", …}` 줄로 시작해 `{"event": "end", "reason": …}` 줄로 끝납니다. `end` 줄이 없으면 상주 프로세스가 강제로 끝난 것입니다. 다시 시작하면 폰이 로그를 보내기 시작한 뒤에 파일을 비웁니다. 실패한 `start`는 파일을 건드리지 않습니다. +- **버퍼:** 남긴 항목은 메모리의 링 버퍼에 쌓입니다. 최대 100,000개, 64MiB(`--buffer-entries`, `--buffer-mb`)이고, 넘으면 오래된 것부터 버립니다. 항목마다 `seq`가 붙습니다. 한 기록의 첫 항목이 1이고 하나 들어올 때마다 1씩 늘어납니다. `-o`를 주지 않으면 디스크에는 아무것도 쓰지 않습니다. 버퍼는 상주 프로세스 안에 있어서, `iph stop`으로 끝나거나 새 빌드가 상주 프로세스를 바꾸거나 오래 쓰이지 않아 끝나면 기록과 함께 사라집니다. `status`의 `buffer`에 채워진 정도가 나옵니다(`entries`, `bytes`, `oldest_seq`, `newest_seq`, `evicted`). +- **`read`:** `--after SEQ`보다 새 항목 가운데 메시지가 `--grep`(정규식)에 맞는 것을 오래된 순서로 `--max`개까지(기본 50, 최대 1000) 돌려줍니다. 메시지는 500자에서 자릅니다(`message_cut`. 메시지 전체는 `-o` 파일에 남습니다). `--after`를 주지 않으면 버퍼에 남은 가장 오래된 항목부터입니다. 결과에는 `entries`, `count`, `cursor`, `more`, `dropped`, `state`가 있고, 기록이 끝났다면 `ended_reason`도 있습니다. + - `cursor`: 다음 `--after`에 그대로 넣습니다. `--max`에서 잘렸으면 돌려준 마지막 항목이고, 버퍼를 끝까지 훑었으면 맞는 항목이 없어도 가장 새 `seq`입니다. 그래서 같은 항목을 두 번 읽지도, 버퍼에 남은 항목을 건너뛰지도 않습니다. `cursor`는 그것을 준 기록에서만 쓸 수 있습니다. `seq`는 기록마다 1부터 다시 시작하므로, 새로 `start`한 뒤에는 `--after` 없이 읽으세요. + - `more`: `--max`에서 잘렸고 맞는 항목이 이미 더 있으면 `true`입니다. + - `dropped`: `--after`보다 새 항목 가운데 이번 읽기 전에 버퍼에서 밀려난 수입니다. 0이 아니면 빠진 항목이 있다는 뜻이니, 더 자주 읽거나 거르세요. + - 연결이 끊겨 끝난 기록도 `stop`하기 전에는 읽을 수 있습니다. +- **파일(선택):** `-o <파일>`을 주면 남긴 항목을 메시지 전체와 함께 JSON Lines 파일에도 씁니다(나만 읽을 수 있습니다). `{"event": "start", …}` 줄, 항목마다 한 줄(`seq`, `time`(UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`), 마지막 `{"event": "end", "reason": …}` 줄입니다. `end` 줄이 없으면 상주 프로세스가 강제로 끝난 것입니다. `--max-mb` MiB(1~4096, 기본 64이며 `-o`가 있어야 합니다)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 다시 시작하면 폰이 로그를 보내기 시작한 뒤에 파일을 비웁니다. 실패한 `start`는 파일을 건드리지 않습니다. - **거르기:** `--process`는 실행 파일 이름이 정확히 같은 항목만 남깁니다 (여러 번 줄 수 있습니다). 앱을 다시 띄워도 계속 걸립니다. 설정 앱은 `Preferences`입니다. 다른 앱은 거르지 않고 한 번 받아서 `process` 칸을 보세요. `--level`은 debug, info, notice, error, fault 중 고른 것보다 낮은 항목을 뺍니다. `--pid`는 폰이 그 프로세스의 항목만 보내게 합니다. -- **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. `--max-mb` MiB(1~4096, 기본 64)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 그래서 거르지 않은 기록은 대략 마지막 1~2분만 남습니다. 길게 받을 때는 `--process`로 거르세요. +- **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. 이 속도면 기본 버퍼는 약 20초(100,000개)를 담습니다. 더 길게 받을 때는 자주 읽거나 `--process`로 거르세요. JSON으로 약 290바이트인 항목은 메모리에서 약 430바이트라서, 기본 버퍼가 가득 차면 약 41MiB를 씁니다. 메시지가 길면 64MiB 제한이 걸립니다. - **다른 명령에 주는 부담:** 거르지 않은 기록을 켜 둔 동안 탭과 읽기 모두 중앙값이 10% 안쪽으로 늘었습니다 (탭 10회 · 읽기 5회씩 비교, 한 번 측정). -- **`stop`:** `seen`(폰이 보낸 항목 수), `kept`(파일에 쓴 수), `rotations`, 끝난 이유를 돌려줍니다. `--grep`(메시지에 거는 정규식)이나 `--max`를 주면 조건에 맞는 최근 항목을 `--max`개까지(기본 50, 최대 1000) 함께 돌려줍니다. 메시지는 500자에서 자르고, 맞은 항목 전체 수는 `matched`에 있습니다. -- **기록이 끝나는 때:** `stop`, 연결이 끊겼을 때, `iph`가 연결을 새로 맺을 때 (명령이 시간을 넘기거나 폰이 답하지 않을 때), `iph stop`, 새 빌드의 `iph`가 상주 프로세스를 바꿀 때, 상주 프로세스가 오래 쓰이지 않아 끝날 때 (기록 중이어도 상주 프로세스는 그대로 끝납니다). 어느 것인지는 `end` 줄과 `status`에 나옵니다. 저절로 다시 시작하지 않으므로 로그에 빈 구간이 생기면 드러납니다. 기록은 한 번에 하나이고, 두 번째 `start`는 `capture_running`으로 실패합니다. -- **연결이 끊긴 직후**에는 폰이 다음 기록에 약 20~30초 동안 아무것도 보내지 않습니다. 그동안 `status`의 `hint`가 이를 알려 줍니다. +- **`stop`:** `seen`(폰이 보낸 항목 수), `kept`(버퍼에 넣은 수), `buffer`, 끝난 이유를 돌려주고, `-o`를 썼다면 `rotations`와 `path`도 줍니다. `--grep`이나 `--max`를 주면 버퍼에서 맞은 항목 전체 수 `matched`와, 그중 최근 `--max`개를 오래된 순서로 담은 `entries`(기본 50, 최대 1000, 메시지는 `read`처럼 자름)도 돌려줍니다. `stop`하면 버퍼가 사라지니 필요한 것은 먼저 읽으세요. +- **기록이 끝나는 때:** `stop`, 연결이 끊겼을 때, `iph`가 연결을 새로 맺을 때 (명령이 시간을 넘기거나 폰이 답하지 않을 때), `iph stop`, 새 빌드의 `iph`가 상주 프로세스를 바꿀 때, 상주 프로세스가 오래 쓰이지 않아 끝날 때 (기록 중이어도 상주 프로세스는 그대로 끝납니다). 어느 것인지는 `end` 줄(`-o`를 썼을 때)과 `status`에 나옵니다. 저절로 다시 시작하지 않으므로 로그에 빈 구간이 생기면 드러납니다. 기록은 한 번에 하나입니다. 두 번째 `start`는 `capture_running`으로, 끝났지만 아직 `stop`하지 않은 기록이 있으면 `capture_ended`로 실패하니 먼저 `stop`하세요. +- **연결이 끊긴 직후**에는 폰이 다음 기록에 약 20~30초 동안 아무것도 보내지 않습니다. 그동안 `status`와 `read`의 `hint`가 이를 알려 줍니다. - **비공개 값:** 앱이 로그에서 비공개로 표시한 값은 콘솔 앱에서처럼 ``로 옵니다. 한 앱을 띄울 때 받은 항목 가운데 약 5분의 1에 들어 있었습니다. -- 스크립트에서는 `syslog(action, opts)`, MCP에서는 `iph_syslog`입니다. 스크립트는 파일 위치를 정하지 못합니다. `batch`에는 없습니다. 기록은 그것을 시작한 호출보다 오래가기 때문입니다. +- 스크립트에서는 `syslog(action, opts)`, MCP에서는 `iph_syslog`입니다. 스크립트는 파일을 쓰지 못합니다. `batch`에는 없습니다. 기록은 그것을 시작한 호출보다 오래가기 때문입니다. ## 스크립트 @@ -303,7 +312,7 @@ iph scripts # 저장된 스크립트 목록 | `readField({selector, take, regex})` | 값 하나를 글자로. `take`: `value`(기본), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | 목록을 스크롤하며 겹치지 않게 모아 `{rows, scrolls, ended}`로 돌려줍니다 | | `sleep(ms)` · `log(…)` · `output(k, v)` | 대기 · 기록 · 결과에 값 넣기 | -| `syslog(action, {process, pid, level, grep, max})` | `-o` 없는 `iph syslog`입니다. 파일은 `iph`의 상태 폴더에 남습니다. `inputs_sent`에 세지 않습니다 | +| `syslog(action, {process, pid, level, after, grep, max})` | `iph syslog`입니다. 로그는 메모리에 남고 `syslog("read", {after})`로 읽습니다. 스크립트는 파일을 쓰지 못합니다. `inputs_sent`에 세지 않습니다 | - 함수가 돌려주는 것은 같은 이름의 CLI 명령이 내는 JSON 객체 그대로입니다 (`tap("일반").screen_changed`, `read().elements`). 셀렉터는 문자열과 객체 둘 다 됩니다. - **실패는 예외입니다.** 실패한 호출은 `Error`를 던지고, `e.code`, `e.outcome`, `e.hint`, `e.result`(결과 객체 전체)가 붙어 있습니다. 잡지 않으면 스크립트가 거기서 멈추고 결과에 `failed_call: {cmd, line, outcome}`, `reason: {code, message}`, `screen_summary`가 담깁니다. 추측해서 진행하지 않습니다. 없어도 되는 것을 눌러 볼 때만 `try { … } catch (e) { … }`로 잡으세요. diff --git a/README.md b/README.md index 5719b22..ad19a00 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ Every command prints JSON; add `--human` for people. The device is chosen by `-- | `iph run [--arg k=v]` / `iph scripts` | Run a saved script, list saved scripts | | `iph mcp [--tools a,b]` | MCP server on stdio | | `iph dnd ` | Turn Do Not Disturb on, put the earlier Focus back, or show the current state | -| `iph syslog [--process name] [--pid N] [--level L] [-o file] [--max-mb N] [--grep RE] [--max N]` | Write the phone's log to a file while other commands run; `stop` can return the latest matching entries. See [Phone log](#phone-log) | +| `iph syslog [--process name] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o file]` | Capture the phone's log in memory while other commands run; `read` returns what is new without stopping it, `stop` can return the latest matching entries. See [Phone log](#phone-log) | | `iph stop` | Stop the resident process for this phone | ### Selectors @@ -239,24 +239,33 @@ iph does not judge what it presses. Pay, send and order buttons are pressed like ### Phone log -`iph syslog start` writes what the phone logs to a JSON Lines file while taps, reads and scripts go on as usual. `iph syslog stop` ends it, so a test or an agent can check what an app logged after a tap. No `sudo log collect` on the Mac is needed. +`iph syslog start` collects what the phone logs, in a buffer inside the resident process, while taps, reads and scripts go on as usual. `iph syslog read` returns what arrived since the last read without stopping the capture, so a test or an agent can check what an app logged after each tap. No `sudo log collect` on the Mac is needed. ```sh iph syslog start --process Preferences # Settings' executable name iph launch com.apple.Preferences --restart iph tap "Battery" -iph syslog stop --grep "battery" --max 20 # the 20 latest entries whose message matches +iph syslog read --grep "battery" # what was logged since start; the result has "cursor": 12 +iph tap "General" +iph syslog read --after 12 --grep "general" # only what is newer than the last read +iph syslog stop # or: stop --grep "general" --max 20 ``` -- **The file:** `~/Library/Application Support/iph/.syslog.jsonl` (readable by you only), or `-o `. Each entry is one line: `time` (UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`. A capture begins with a `{"event": "start", …}` line and finishes with `{"event": "end", "reason": …}`. A file without an `end` line was cut off by a killed resident process. Starting again empties the file once the phone has started sending; a `start` that fails leaves it as it was. +- **The buffer:** kept entries go into a ring buffer in memory, at most 100,000 entries and 64 MiB (`--buffer-entries`, `--buffer-mb`); the oldest are dropped first. Each entry gets a `seq`: 1 for the first of a capture, one more for each after it. Nothing is written to disk unless you ask with `-o`. The buffer lives in the resident process, so it goes with the capture when `iph stop` ends it, a newer build replaces it, or it exits after its idle time. `status` shows how full it is under `buffer` (`entries`, `bytes`, `oldest_seq`, `newest_seq`, `evicted`). +- **`read`:** returns the entries newer than `--after SEQ` whose message matches `--grep` (a regular expression), oldest first, at most `--max` (50 by default, at most 1000). Each message is cut to 500 characters (`message_cut`; `-o` keeps the whole message). Without `--after` it starts at the oldest entry the buffer still holds. The result has `entries`, `count`, `cursor`, `more`, `dropped` and `state`, and `ended_reason` once the capture has ended. + - `cursor`: pass it as the next `--after`. It is the last entry returned when `--max` cut the page short, and the newest `seq` when the whole buffer was looked through, even if nothing matched. So a loop never reads an entry twice and never skips one that is still in the buffer. A cursor belongs to the capture that gave it: seqs start again at 1 with each capture, so after a new `start` read without `--after`. + - `more`: `true` when `--max` cut the page short and another matching entry is already waiting. + - `dropped`: entries newer than `--after` that were pushed out of the buffer before this read. Anything but 0 means entries were lost; read more often or filter. + - A capture that ended (a dropped connection) can still be read until you `stop` it. +- **The file (optional):** `-o ` also writes every kept entry to a JSON Lines file with its whole message, readable by you only: a `{"event": "start", …}` line, one line per entry (`seq`, `time` (UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`) and a final `{"event": "end", "reason": …}` line. A file without an `end` line was cut off by a killed resident process. At `--max-mb` MiB (1 to 4096, 64 by default; it needs `-o`) the file moves to `.1`, replacing the previous one (the `start` line goes with it). Starting again empties the file once the phone has started sending; a `start` that fails leaves it as it was. - **Filters:** `--process` keeps entries by executable name, exactly (repeatable). It keeps matching across app restarts. Settings is `Preferences`; for another app, start without a filter and look at the `process` field. `--level` drops anything below debug, info, notice, error or fault. `--pid` makes the phone send only that process's entries. -- **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At `--max-mb` MiB (1 to 4096, 64 by default) the file moves to `.1`, replacing the previous one (the `start` line goes with it), so an unfiltered capture keeps roughly the last minute or two. Filter with `--process` for anything longer. +- **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At that rate the default buffer holds about 20 s (100,000 entries), so read often or filter with `--process` for anything longer. An entry of about 290 B as JSON weighs about 430 B in memory, so a full default buffer takes about 41 MiB; the 64 MiB limit applies when messages run long. - **Cost to other commands:** with an unfiltered capture running, the median tap and the median read each took under 10% longer (10 taps and 5 reads each way, one run). -- **`stop`:** returns `seen` (entries the phone sent), `kept` (written), `rotations` and why it ended. With `--grep` (a regular expression on the message) or `--max`, it also returns up to `--max` of the latest matching entries (50 by default, at most 1000), each message cut to 500 characters, and `matched`, the number that matched in all. -- **What ends a capture:** `stop`, a dropped connection, iph rebuilding its connections (after a command times out or the phone stops answering), `iph stop`, a newer build of iph replacing the resident process, or the resident process exiting after its idle time (a capture does not keep it alive). The `end` line and `status` say which. A capture is not restarted by itself, so a gap in the log is never hidden. One capture runs at a time; a second `start` fails with `capture_running`. -- **After a dropped connection** the phone sends nothing to the next capture for about 20 to 30 s. `status` says so in a `hint` while nothing has arrived. +- **`stop`:** returns `seen` (entries the phone sent), `kept` (put in the buffer), `buffer` and why it ended, and with `-o` also `rotations` and `path`. With `--grep` or `--max` it also returns `matched`, the number of entries in the buffer that matched, and `entries`, the latest `--max` of them, oldest first (50 by default, at most 1000, cut like `read`'s). The buffer is gone after `stop`, so read what you need first. +- **What ends a capture:** `stop`, a dropped connection, iph rebuilding its connections (after a command times out or the phone stops answering), `iph stop`, a newer build of iph replacing the resident process, or the resident process exiting after its idle time (a capture does not keep it alive). The `end` line (with `-o`) and `status` say which. A capture is not restarted by itself, so a gap in the log is never hidden. One capture runs at a time: a second `start` fails with `capture_running`, or with `capture_ended` while an ended capture waits to be read; `stop` it first. +- **After a dropped connection** the phone sends nothing to the next capture for about 20 to 30 s. `status` and `read` say so in a `hint` while nothing has arrived. - **Private values:** values an app marks private in its log calls arrive as ``, as in Console. In one app's launch, about a fifth of its entries carried one. -- Also in scripts as `syslog(action, opts)` and over MCP as `iph_syslog`. A script cannot choose the file. Not in `batch`: a capture outlives the call that started it. +- Also in scripts as `syslog(action, opts)` and over MCP as `iph_syslog`. A script cannot write a file. Not in `batch`: a capture outlives the call that started it. ## Scripts @@ -300,7 +309,7 @@ iph scripts # list saved scripts | `readField({selector, take, regex})` | One value, as text. `take`: `value` (default), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | Collect a list while scrolling, each row once; returns `{rows, scrolls, ended}` | | `sleep(ms)` · `log(…)` · `output(k, v)` | Wait, note, add a value to the result | -| `syslog(action, {process, pid, level, grep, max})` | `iph syslog` without `-o`: the file stays in iph's state directory. Not counted in `inputs_sent` | +| `syslog(action, {process, pid, level, after, grep, max})` | `iph syslog`: the log stays in memory and `syslog("read", {after})` returns it, a script cannot write a file. Not counted in `inputs_sent` | - A function returns the JSON object the CLI command of the same name prints (`tap("일반").screen_changed`, `read().elements`). Selectors can be strings or objects. - **A failure is an exception.** A call that fails throws an `Error` carrying `e.code`, `e.outcome`, `e.hint` and `e.result` (the whole result object). Uncaught, it ends the script, and the result has `failed_call: {cmd, line, outcome}`, `reason: {code, message}` and `screen_summary`. Nothing is guessed. Use `try { … } catch (e) { … }` only around something that may legitimately be missing. diff --git a/skills/iph/SKILL.md b/skills/iph/SKILL.md index badcedd..4f5caca 100644 --- a/skills/iph/SKILL.md +++ b/skills/iph/SKILL.md @@ -79,7 +79,7 @@ A script is the body of a function, so `return` ends it. The commands are functi - `readList({row, columns, key, group, stop_below, max_scrolls})` scrolls a list and returns `{rows, scrolls, ended}` with each row once. `columns: {name: {take, regex}}`, or `{name: {value: "…"}}` for a constant. `group: {selector, regex, as}` gives each row the heading it stands under (a date line), and `stop_below: N` stops once a heading's number falls below N. `key: "column"` names the column that identifies a row; use it when rows change while the list is read (a clock, time left). - `args` holds the `--arg k=v` values as text (`Number(args.n)` for a number). Return an object, or call `output(key, value)`, and it comes back as `outputs`. `log(…)` lines come back as `logs`. `sleep(ms)` waits. - Any call takes `hint: "…"`: what to tell the person if the script stops there. A screen that waits for Face ID: `waitFor(sel, { timeout_ms: 40000, hint: "폰을 봐 주세요" })`. -- `syslog(action, {process, pid, level, grep, max})` captures the phone's log, as `iph syslog` does below. +- `syslog(action, {process, pid, level, after, grep, max})` captures the phone's log and returns what `iph syslog` does below (`syslog("read", {after: cursor})` for what is new). A script cannot write a file. - There are no files, no network and no timers. `Date`, `JSON`, `RegExp` and the rest of the language work. ### When a call fails @@ -120,7 +120,7 @@ After `launch`, that app must stay in front; if another one comes up, the script ## What the app logged -To check what an app logged after a tap, wrap the steps in a capture: `iph syslog start --process `, the steps, then `iph syslog stop --grep --max 20` (MCP: `iph_syslog` with `action`). The executable name is not the app's display name (Settings is `Preferences`); when you do not know it, start without `--process`, stop after a second, and look at the `process` field of the entries for the app's pid. Unfiltered over Wi-Fi the phone sends thousands of entries a second, so filter for anything longer. If `stop` says `seen: 0`, nothing arrived: after a dropped connection the phone sends nothing for about 30 s, and `status` gives a `hint` while it waits. Values the app marked private arrive as ``; that is the app's choice, not a failure. The entries are the user's data: quote only what the task needs. +To check what an app logged after a tap, start a capture, act, and read: `iph syslog start --process `, a step, `iph syslog read --grep `, the next step, `iph syslog read --after --grep `, and so on, then `iph syslog stop` (MCP: `iph_syslog` with `action`). The capture keeps its entries in memory, each with a `seq`; nothing is written to disk unless you pass `-o `. `read` does not stop the capture and returns `entries` newer than `--after`, oldest first, with a `cursor`: pass it as the next `--after` and no entry is read twice or skipped. A cursor belongs to the capture that gave it: after a new `start`, read without `--after`. Without `--after` it starts at the oldest entry the buffer holds. `more: true` means `--max` cut the page short (read again from the `cursor`); `dropped` above 0 means that many newer entries were pushed out of the buffer before you read, so read more often or filter. The buffer keeps the last 100,000 entries and goes with the capture, so `read` what you need before `stop`. A capture whose `state` is `ended` (the connection dropped) can still be read, and a new `start` fails with `capture_ended` until you `stop` it. The executable name is not the app's display name (Settings is `Preferences`); when you do not know it, start without `--process`, read after a second, and look at the `process` field of the entries for the app's pid. Unfiltered over Wi-Fi the phone sends thousands of entries a second (the buffer then holds about 20 s), so filter for anything longer. If `seen` is 0, nothing arrived: after a dropped connection the phone sends nothing for about 30 s, and `status` and `read` give a `hint` while it waits. Values the app marked private arrive as ``; that is the app's choice, not a failure. Messages come back cut to 500 characters (`message_cut`); `-o` keeps them whole. The entries are the user's data: quote only what the task needs. ## Commands at a glance diff --git a/src/human.rs b/src/human.rs index b797009..e615b0f 100644 --- a/src/human.rs +++ b/src/human.rs @@ -69,6 +69,80 @@ fn type_observation(v: &Value, out: &mut Vec) { } } +fn size(bytes: u64) -> String { + match bytes { + b if b < 1024 => format!("{b} B"), + b if b < 1024 * 1024 => format!("{} KiB", b / 1024), + b => format!("{:.1} MiB", b as f64 / (1024.0 * 1024.0)), + } +} + +fn syslog_entry(e: &Value) -> String { + let mut line = format!(" {:>7} {} {:<6} {}[{}]", s(&e["seq"]), s(&e["time"]), s(&e["level"]), s(&e["process"]), s(&e["pid"])); + if let Some(sub) = e["subsystem"].as_str() { + line.push_str(&format!(" {sub}/{}", s(&e["category"]))); + } + line.push_str(&format!(": {}", s(&e["message"]).replace('\n', " ⏎ "))); + if e["message_cut"] == true { + line.push_str(" …"); + } + line +} + +/// What a capture is and holds: `start`, `status` and `stop`. +fn syslog_status(v: &Value, out: &mut Vec) { + if v["state"] == "none" { + out.push("✓ syslog: no capture".into()); + return; + } + out.push(format!( + "✓ syslog {} seen {} kept {} unparsed {}", + s(&v["state"]), + s(&v["seen"]), + s(&v["kept"]), + s(&v["unparsed"]) + )); + let b = &v["buffer"]; + let mut buffer = format!( + " buffer {}/{} entries, {} of {}", + s(&b["entries"]), + s(&b["max_entries"]), + size(b["bytes"].as_u64().unwrap_or(0)), + size(b["max_bytes"].as_u64().unwrap_or(0)) + ); + if let (Some(oldest), Some(newest)) = (b["oldest_seq"].as_u64(), b["newest_seq"].as_u64()) { + buffer.push_str(&format!(", seq {oldest} to {newest}")); + } + buffer.push_str(&format!(", {} evicted", s(&b["evicted"]))); + out.push(buffer); + let mut only = Vec::new(); + if let Some(p) = v["process"].as_array() { + only.push(format!("process {}", p.iter().map(s).collect::>().join(", "))); + } + if !v["pid"].is_null() { + only.push(format!("pid {}", s(&v["pid"]))); + } + if !v["level"].is_null() { + only.push(format!("level {} and up", s(&v["level"]))); + } + if !only.is_empty() { + out.push(format!(" only {}", only.join(" "))); + } + if let Some(path) = v["path"].as_str() { + out.push(format!(" file {path} {} rotations", s(&v["rotations"]))); + } + syslog_tail(v, out); +} + +fn syslog_tail(v: &Value, out: &mut Vec) { + if let Some(reason) = v["ended_reason"].as_str() { + out.push(format!(" ended: {reason}")); + } + if let Some(hint) = v["hint"].as_str() { + out.push(format!(" → {hint}")); + } +} + pub fn render(cmd: &str, v: &Value) -> String { let mut out = Vec::new(); if v["ok"] != true { @@ -189,6 +263,26 @@ pub fn render(cmd: &str, v: &Value) -> String { out.push(format!("{:<24} {} [{}]", s(&r["name"]), s(&r["description"]), s(&r["source"]))); } } + "syslog" => match v["entries"].as_array() { + Some(entries) if v.get("cursor").is_some() => { + let mut head = format!("✓ syslog {} {} entries cursor {}", s(&v["state"]), entries.len(), s(&v["cursor"])); + if v["more"] == true { + head.push_str(" more waiting"); + } + if let Some(dropped) = v["dropped"].as_u64().filter(|d| *d > 0) { + head.push_str(&format!(" {dropped} dropped before this read")); + } + out.push(head); + out.extend(entries.iter().map(syslog_entry)); + syslog_tail(v, &mut out); + } + Some(entries) => { + syslog_status(v, &mut out); + out.push(format!(" matched {}, the latest {} below", s(&v["matched"]), entries.len())); + out.extend(entries.iter().map(syslog_entry)); + } + None => syslog_status(v, &mut out), + }, "script" | "batch" => { for line in v["logs"].as_array().into_iter().flatten() { out.push(format!(" {}", s(line))); @@ -273,6 +367,47 @@ mod tests { assert!(text.contains("value_unchanged: value is unchanged")); } + #[test] + fn syslog_prints_counts_a_page_and_the_matches_of_a_stop() { + let status = json!({ + "ok": true, "state": "running", "seen": 5000, "kept": 1234, "unparsed": 0, + "buffer": {"entries": 1234, "bytes": 700_000, "max_entries": 100_000, "max_bytes": 67_108_864, + "oldest_seq": 1, "newest_seq": 1234, "evicted": 0}, + "started_at": "2026-11-19T01:00:00Z", "process": ["Papago", "Preferences"], "level": "info", + "path": "/tmp/cap.jsonl", "rotations": 2, + }); + let text = render("syslog", &status); + assert!(text.contains("syslog running seen 5000 kept 1234 unparsed 0")); + assert!(text.contains("buffer 1234/100000 entries, 683 KiB of 64.0 MiB, seq 1 to 1234, 0 evicted")); + assert!(text.contains("only process Papago, Preferences level info and up")); + assert!(text.contains("file /tmp/cap.jsonl 2 rotations")); + assert!(render("syslog", &json!({"ok": true, "state": "none"})).contains("no capture")); + + let entry = json!({"seq": 12, "time": "2026-11-19T01:02:03.004005Z", "pid": 412, "process": "Papago", "level": "error", + "subsystem": "com.naver.papago", "category": "ui", "message": "line one\nline two", "message_cut": true}); + let page = json!({"ok": true, "state": "ended", "count": 1, "entries": [entry], "cursor": 12, "more": true, "dropped": 3, + "ended_reason": "the connection to the phone was reset"}); + let text = render("syslog", &page); + assert!(text.starts_with("✓ syslog ended 1 entries cursor 12 more waiting 3 dropped before this read")); + assert!(text.contains("12 2026-11-19T01:02:03.004005Z error Papago[412] com.naver.papago/ui: line one ⏎ line two …")); + assert!(text.contains("ended: the connection to the phone was reset")); + + let mut stopped = status.clone(); + stopped["state"] = json!("ended"); + stopped["matched"] = json!(7); + stopped["entries"] = json!([entry]); + let text = render("syslog", &stopped); + assert!(text.contains("syslog ended seen 5000")); + assert!(text.contains("matched 7, the latest 1 below")); + assert!(text.contains("Papago[412]")); + + let empty = json!({"ok": true, "state": "running", "count": 0, "entries": [], "cursor": 0, "more": false, "dropped": 0, + "hint": "No entries yet."}); + let text = render("syslog", &empty); + assert!(text.starts_with("✓ syslog running 0 entries cursor 0\n")); + assert!(!text.contains("dropped") && text.contains("→ No entries yet.")); + } + #[test] fn element_without_label() { let v = json!({"ok": true, "element": {"role": "search_field", "value": "검색"}, "elapsed_ms": 5}); diff --git a/src/main.rs b/src/main.rs index e803bef..5e636dd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -188,7 +188,7 @@ enum Cmd { }, /// Do Not Disturb on the phone: on, off (back to the Focus that was on), status. Dnd { action: String }, - /// Write the phone's log to a JSON Lines file while a test runs: start, stop, status. + /// Capture the phone's log while a test runs and read it back: start, read, stop, status. Syslog { action: String, /// start: keep only this process, by executable name (Settings is Preferences). Repeatable. @@ -200,16 +200,25 @@ enum Cmd { /// start: lowest level kept: debug, info, notice, error, fault. #[arg(long)] level: Option, - /// start: the file to write (default: .syslog.jsonl in the state directory). + /// start: also write the kept entries to this JSON Lines file. Without it nothing is written to disk. #[arg(short, long)] output: Option, - /// start: move the file to .1 when it reaches this size in MiB (1 to 4096, default 64). + /// start, with -o: move the file to .1 when it reaches this size in MiB (1 to 4096, default 64). #[arg(long)] max_mb: Option, - /// stop: return the entries whose message matches this regular expression. + /// start: most entries the buffer holds (1 to 1000000, default 100000). The oldest are dropped. + #[arg(long)] + buffer_entries: Option, + /// start: most memory the buffer takes in MiB (1 to 1024, default 64). + #[arg(long)] + buffer_mb: Option, + /// read: only entries after this seq: the `cursor` of the previous read (default: from the oldest kept). + #[arg(long)] + after: Option, + /// read, stop: only entries whose message matches this regular expression. #[arg(long)] grep: Option, - /// stop: most entries to return, the latest ones (default 50, at most 1000). + /// read: most entries returned, the oldest first. stop: most entries returned, the latest (default 50, at most 1000). #[arg(long)] max: Option, }, @@ -420,13 +429,14 @@ async fn run(cli: Cli) -> i32 { Cmd::Key { key } => ("key", json!({ "key": key })), Cmd::Button { button } => ("button", json!({ "button": button })), Cmd::Dnd { action } => ("dnd", json!({ "action": action })), - Cmd::Syslog { action, process, pid, level, output, max_mb, grep, max } => { + Cmd::Syslog { action, process, pid, level, output, max_mb, buffer_entries, buffer_mb, after, grep, max } => { // The daemon writes the file, so the path must not depend on its cwd. let output = output.map(|o| std::path::absolute(&o).map(|p| p.display().to_string()).unwrap_or(o)); let process = (!process.is_empty()).then_some(process); ("syslog", json!({ "action": action, "process": process, "pid": pid, "level": level, "output": output, - "max_mb": max_mb, "grep": grep, "max": max, + "max_mb": max_mb, "buffer_entries": buffer_entries, "buffer_mb": buffer_mb, + "after": after, "grep": grep, "max": max, })) } Cmd::Launch { app, restart, env, arguments } => match launch_args(&app, restart, &env, &arguments) { @@ -529,6 +539,27 @@ mod tests { assert_eq!(v["arguments"], json!(["-k", "v"])); } + #[test] + fn syslog_flags_reach_the_command() { + use clap::Parser; + let parse = |args: &[&str]| Cli::try_parse_from(std::iter::once("iph").chain(args.iter().copied())).unwrap(); + let Cmd::Syslog { action, after, grep, max, .. } = + parse(&["syslog", "read", "--after", "120", "--grep", "row", "--max", "5"]).command + else { + panic!("syslog read") + }; + assert_eq!((action.as_str(), after, grep.as_deref(), max), ("read", Some(120), Some("row"), Some(5))); + let Cmd::Syslog { process, output, max_mb, buffer_entries, buffer_mb, .. } = parse(&[ + "syslog", "start", "--process", "A", "--process", "B", "-o", "cap.jsonl", "--max-mb", "8", + "--buffer-entries", "500", "--buffer-mb", "2", + ]) + .command + else { + panic!("syslog start") + }; + assert_eq!((process, output.as_deref(), max_mb, buffer_entries, buffer_mb), (strings(&["A", "B"]), Some("cap.jsonl"), Some(8), Some(500), Some(2))); + } + #[test] fn launch_env_without_a_name_or_equals_is_not_sent() { for bad in ["NOEQUALS", "=v", ""] { diff --git a/src/mcp.rs b/src/mcp.rs index 1159881..425d927 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -18,7 +18,7 @@ const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loo The commands are functions that return what the tool of the same name returns: read(opts), find(selector), tap(target, opts), swipe(direction | {from, to}, opts), \ pinch(direction | {scale, rotate, at}, opts), scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart, arguments, environment}), apps(). Also waitFor(selector, {timeout_ms}), \ readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \ -syslog(\"start\" | \"stop\" | \"status\", {process, pid, level, grep, max}) captures the phone's log as iph_syslog does; a script cannot choose the file. \ +syslog(\"start\" | \"read\" | \"stop\" | \"status\", {process, pid, level, after, grep, max}) captures the phone's log as iph_syslog does and returns what it returns; a script cannot write a file. \ tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \ A call that fails throws an Error with .code, .outcome, .hint and .result (the full result object); uncaught, it ends the script and the result says which call and line. \ After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \ @@ -171,18 +171,24 @@ fn tools() -> Vec { ), tool( "iph_syslog", - "Capture the phone's log to a JSON Lines file while other calls run, to check what an app logged after a tap. \ - \"start\" (one capture at a time), \"stop\" (ends it; with grep or max it returns the latest matching entries), \"status\". \ - Filter with process (executable names such as Preferences; survives app restarts) or pid; unfiltered over Wi-Fi it is a lot of data.", + "Capture the phone's log in the background while other calls run, to check what an app logged after a tap. \ + \"start\" (one capture at a time; stop an ended one before starting again) keeps the entries in a buffer in memory, newest last, each with a seq; \ + \"read\" returns the entries newer than `after` (the `cursor` of the previous read) without stopping the capture, \ + so the loop is start, tap, read, tap, read, stop; \"stop\" ends it (with grep or max it returns the latest matching entries); \"status\". \ + Filter with process (executable names such as Preferences; survives app restarts) or pid; unfiltered over Wi-Fi it is thousands of entries a second, \ + and the buffer keeps the last 100,000. A read says how many entries were `dropped` before it could get them.", json!({ - "action": { "type": "string", "enum": ["start", "stop", "status"] }, + "action": { "type": "string", "enum": ["start", "read", "stop", "status"] }, "process": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these executables." }, "pid": { "type": "integer", "description": "start: keep only this pid (filtered on the phone)." }, "level": { "type": "string", "enum": ["debug", "info", "notice", "error", "fault"], "description": "start: lowest level kept." }, - "output": { "type": "string", "description": "start: absolute path of the file (default: in iph's state directory)." }, - "max_mb": { "type": "integer", "description": "start: move the file to .1 at this size in MiB (1 to 4096, default 64)." }, - "grep": { "type": "string", "description": "stop: regular expression matched against each message." }, - "max": { "type": "integer", "description": "stop: most entries returned, the latest (default 50, at most 1000)." }, + "buffer_entries": { "type": "integer", "description": "start: most entries the buffer holds, 1 to 1000000 (default 100000); the oldest are dropped." }, + "buffer_mb": { "type": "integer", "description": "start: most memory the buffer takes in MiB, 1 to 1024 (default 64)." }, + "output": { "type": "string", "description": "start: absolute path of a JSON Lines file that also gets every kept entry (whole messages). Without it nothing is written to disk." }, + "max_mb": { "type": "integer", "description": "start, with output: move the file to .1 at this size in MiB, 1 to 4096 (default 64)." }, + "after": { "type": "integer", "description": "read: only entries after this seq; pass the previous read's cursor. Omit for the oldest the buffer holds." }, + "grep": { "type": "string", "description": "read, stop: regular expression matched against each message." }, + "max": { "type": "integer", "description": "read: most entries returned, the oldest first. stop: most entries returned, the latest. Default 50, at most 1000." }, }), &["action"], ), @@ -389,6 +395,17 @@ mod tests { assert_eq!(props["environment"]["additionalProperties"]["type"], "string"); } + #[test] + fn syslog_offers_read_with_a_cursor_and_a_file_only_on_request() { + let tool = tools().into_iter().find(|t| t["name"] == "iph_syslog").unwrap(); + let props = tool["inputSchema"]["properties"].as_object().unwrap(); + assert_eq!(props["action"]["enum"], json!(["start", "read", "stop", "status"])); + for key in ["after", "grep", "max", "output", "max_mb", "buffer_entries", "buffer_mb", "process", "pid", "level"] { + assert!(props.contains_key(key), "missing {key}"); + } + assert_eq!(tool["inputSchema"]["required"], json!(["action"])); + } + #[test] fn tool_list_covers_the_spec() { let names: Vec = tools() diff --git a/src/script.rs b/src/script.rs index 04965df..2cc09b9 100644 --- a/src/script.rs +++ b/src/script.rs @@ -461,8 +461,8 @@ impl RunState { return Err(Fail::invalid(format!("`{cmd}` takes an object of arguments"))); }; if cmd == "syslog" && map.get("output").is_some_and(|v| !v.is_null()) { - // Saved scripts come from anywhere; the file stays where iph keeps its own. - return Err(Fail::invalid("a script cannot choose the file; the capture goes to iph's state directory")); + // Saved scripts come from anywhere; they do not get to write files. + return Err(Fail::invalid("a script cannot write a file; read the log back with syslog(\"read\")")); } let hint = map.remove("hint").and_then(|v| v.as_str().map(String::from)); Ok(Prepared { args: Value::Object(map), hint }) @@ -889,11 +889,14 @@ mod tests { } #[test] - fn syslog_is_not_an_input_and_cannot_choose_its_file() { + fn syslog_is_not_an_input_reads_with_a_cursor_and_cannot_write_a_file() { let mut fake = Fake::default(); let code = r#" syslog("start", {process: ["Preferences"], level: "info"}); - tap("일반"); tap("정보"); + tap("일반"); + const page = syslog("read", {after: 0, grep: "row", max: 5}); + tap("정보"); + syslog("read", {after: page.cursor}); const done = syslog("stop", {grep: "row", max: 5}); let refused = null; try { syslog("start", {output: "/tmp/elsewhere.jsonl"}); } catch (e) { refused = e.code; } @@ -903,8 +906,11 @@ mod tests { let out = res.unwrap(); let asked: Vec<(&str, &Value)> = fake.asked.iter().map(|(c, a)| (c.as_str(), a)).collect(); assert_eq!(asked[0], ("syslog", &json!({"process": ["Preferences"], "level": "info", "action": "start"}))); - assert_eq!(asked[3], ("syslog", &json!({"grep": "row", "max": 5, "action": "stop"}))); - assert_eq!(asked.len(), 4, "the refused start never reached the phone"); + assert_eq!(asked[2], ("syslog", &json!({"after": 0, "grep": "row", "max": 5, "action": "read"}))); + assert_eq!(asked[4].0, "syslog"); + assert_eq!(asked[4].1["action"], "read"); + assert_eq!(asked[5], ("syslog", &json!({"grep": "row", "max": 5, "action": "stop"}))); + assert_eq!(asked.len(), 6, "the refused start never reached the phone"); assert_eq!(out["outputs"]["refused"], "invalid_argument"); assert_eq!(out["inputs_sent"], 2); } diff --git a/src/syslog.rs b/src/syslog.rs index 10ef6fb..2ef876a 100644 --- a/src/syslog.rs +++ b/src/syslog.rs @@ -1,16 +1,20 @@ -//! `iph syslog`: the phone's log stream, written to a file while a test runs, -//! so what an app logged after a tap can be checked afterwards. +//! `iph syslog`: the phone's log stream, kept in the daemon while a test +//! runs, so what an app logged after a tap can be read back. //! //! One capture per daemon. The stream is read by a task of its own that never -//! touches the session, so commands keep working while it runs. The file is -//! JSON Lines: a `start` line, the kept entries, and an `end` line that says +//! touches the session, so commands keep working while it runs. An entry that +//! passes the filters goes into a ring buffer bounded by entry count and by +//! bytes and gets a `seq` (1 for the first). `read` returns what is newer than +//! a `seq` the caller already has and says where to continue; the buffer goes +//! with the capture. With `output` the kept entries are also written to a +//! JSON Lines file: a `start` line, the entries, and an `end` line that says //! why the capture ended. A file without an `end` line belongs to a daemon //! that was killed. use std::{ collections::VecDeque, fs::File, - io::{BufRead, BufReader, BufWriter, Write}, + io::{BufWriter, Write}, path::{Path, PathBuf}, sync::{Arc, Mutex, Weak}, time::Duration, @@ -31,16 +35,27 @@ use crate::{ tcp::handle::Reset, }; +/// The buffer's defaults. Unfiltered over Wi-Fi the phone sent about 4,800 +/// entries/s, 1.4 MB/s, 290 B an entry as JSON; 100,000 entries hold about +/// 20 s of that worst case, longer than a sensible gap between a tap and the +/// `read` after it, and minutes of a filtered capture. In memory an entry +/// weighs more than its JSON (see `Entry::weight`): about 430 B for one of +/// 290 B of JSON, so 100,000 of them take about 41 MiB. The 64 MiB limit +/// binds once messages average more than about 540 B. +const DEFAULT_BUFFER_ENTRIES: u64 = 100_000; +const MAX_BUFFER_ENTRIES: u64 = 1_000_000; +const DEFAULT_BUFFER_MB: u64 = 64; +const MAX_BUFFER_MB: u64 = 1024; const DEFAULT_MAX_MB: u64 = 64; /// The most `max_mb` takes. A part is read back whole by whoever opens it. const MAX_FILE_MB: u64 = 4096; -/// How long a written line may wait in the buffer before it is flushed. -const FLUSH_EVERY: Duration = Duration::from_millis(250); -const FILE_BUFFER: usize = 32 * 1024; const DEFAULT_MATCHES: u64 = 50; const MAX_MATCHES: u64 = 1000; -/// Longest message a match returns; the file keeps the whole message. +/// Longest message a reply returns; the file keeps the whole message. const MATCH_CHARS: usize = 500; +/// How long a written line may wait in the buffer before it is flushed. +const FLUSH_EVERY: Duration = Duration::from_millis(250); +const FILE_BUFFER: usize = 32 * 1024; /// Severity, lowest first. The device's own codes are not in this order. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -88,7 +103,7 @@ impl From for Level { } } -/// One log entry as the file keeps it. +/// One log entry as it is kept. Its `seq` belongs to the buffer, not to it. #[derive(Debug, Clone, PartialEq)] pub struct Entry { /// UTC. @@ -135,8 +150,11 @@ impl From for Entry { } impl Entry { - pub fn line(&self) -> String { + /// The entry as a reply or the file shows it. A message longer than + /// `max_chars` is cut and marked with `message_cut`. + fn value(&self, seq: u64, max_chars: usize) -> Value { let mut v = json!({ + "seq": seq, "time": self.time, "pid": self.pid, "process": self.process, @@ -149,8 +167,33 @@ impl Entry { if let Some(c) = &self.category { v["category"] = json!(c); } - v["message"] = json!(self.message); - v.to_string() + if self.message.len() > max_chars && self.message.chars().count() > max_chars { + v["message"] = json!(self.message.chars().take(max_chars).collect::()); + v["message_cut"] = json!(true); + } else { + v["message"] = json!(self.message); + } + v + } + + /// The file's line: the whole message. + pub fn line(&self, seq: u64) -> String { + self.value(seq, usize::MAX).to_string() + } + + /// What the buffer counts against its byte budget: the text, the struct + /// and a flat allowance for the six allocations behind it. An estimate, + /// not an allocator's figure; above the entry's JSON. + fn weight(&self) -> usize { + const ALLOCATOR_SLACK: usize = 96; + std::mem::size_of::() + + ALLOCATOR_SLACK + + self.time.len() + + self.process.len() + + self.sender.len() + + self.subsystem.as_ref().map_or(0, String::len) + + self.category.as_ref().map_or(0, String::len) + + self.message.len() } } @@ -168,12 +211,25 @@ impl Filter { } } +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Limits { + pub entries: usize, + pub bytes: usize, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct FileSpec { + pub path: PathBuf, + pub max_bytes: u64, +} + #[derive(Debug, Clone, PartialEq)] pub struct Spec { pub filter: Filter, pub pid: Option, - pub path: PathBuf, - pub max_bytes: u64, + pub limits: Limits, + /// Only when `output` is given: nothing is written to disk otherwise. + pub file: Option, } #[derive(Debug)] @@ -185,14 +241,16 @@ pub struct Query { #[derive(Debug)] pub enum Request { Start(Spec), + /// Entries newer than `after` (0: from the start), without stopping. + Read { after: u64, query: Query }, /// `None`: report the counts only. Stop(Option), Status, } -/// Parse the arguments every surface sends. `default_path` is used when no -/// `output` is given; a given one must be absolute, since the daemon writes it. -pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res { +/// Parse the arguments every surface sends. A given `output` must be +/// absolute, since the daemon writes it. +pub fn parse(args: &Value) -> Res { let given: Map = match args { Value::Null => Map::new(), Value::Object(m) => m.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(), @@ -201,12 +259,13 @@ pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res &["action", "process", "pid", "level", "output", "max_mb"], + "start" => &["action", "process", "pid", "level", "output", "max_mb", "buffer_entries", "buffer_mb"], + "read" => &["action", "after", "grep", "max"], "stop" => &["action", "grep", "max"], "status" => &["action"], - other => return Err(Fail::invalid(format!("unknown syslog action `{other}` (start, stop, status)"))), + other => return Err(Fail::invalid(format!("unknown syslog action `{other}` (start, read, stop, status)"))), }; if let Some(key) = given.keys().find(|k| !allowed.contains(&k.as_str())) { return Err(Fail::invalid(format!("`syslog {action}` takes no `{key}`"))); @@ -217,6 +276,23 @@ pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res v.as_u64().map(Some).ok_or_else(|| Fail::invalid(format!("`{key}` takes a whole number"))), } }; + let sized = |key: &str, default: u64, most: u64| -> Res { + let n = number(key)?.unwrap_or(default); + if (1..=most).contains(&n) { + Ok(n) + } else { + Err(Fail::invalid(format!("`{key}` takes a whole number from 1 to {most}"))) + } + }; + let grep = || -> Res> { + match given.get("grep") { + None => Ok(None), + Some(v) => { + let pattern = v.as_str().ok_or_else(|| Fail::invalid("`grep` takes a regular expression"))?; + Ok(Some(Regex::new(pattern).map_err(|e| Fail::invalid(format!("`grep`: {e}")))?)) + } + } + }; match action { "start" => { let processes = match given.get("process") { @@ -242,37 +318,44 @@ pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res None, Some(n) => Some(u32::try_from(n).map_err(|_| Fail::invalid("`pid` is out of range"))?), }; - let path = match given.get("output") { - None => default_path(), + let limits = Limits { + entries: usize::try_from(sized("buffer_entries", DEFAULT_BUFFER_ENTRIES, MAX_BUFFER_ENTRIES)?) + .map_err(|_| Fail::invalid("`buffer_entries` is out of range"))?, + bytes: sized("buffer_mb", DEFAULT_BUFFER_MB, MAX_BUFFER_MB)? + .checked_mul(1024 * 1024) + .and_then(|b| usize::try_from(b).ok()) + .ok_or_else(|| Fail::invalid("`buffer_mb` is out of range"))?, + }; + let file = match given.get("output") { + None if given.contains_key("max_mb") => { + return Err(Fail::invalid("`max_mb` sizes the file that `output` names")); + } + None => None, Some(v) => { let path = PathBuf::from(v.as_str().ok_or_else(|| Fail::invalid("`output` takes a path"))?); if !path.is_absolute() { return Err(Fail::invalid("`output` must be an absolute path")); } - path + let max_bytes = sized("max_mb", DEFAULT_MAX_MB, MAX_FILE_MB)? + .checked_mul(1024 * 1024) + .ok_or_else(|| Fail::invalid("`max_mb` is out of range"))?; + Some(FileSpec { path, max_bytes }) } }; - let max_mb = number("max_mb")?.unwrap_or(DEFAULT_MAX_MB); - let max_bytes = (1..=MAX_FILE_MB) - .contains(&max_mb) - .then(|| max_mb.checked_mul(1024 * 1024)) - .flatten() - .ok_or_else(|| Fail::invalid(format!("`max_mb` takes a whole number from 1 to {MAX_FILE_MB}")))?; - Ok(Request::Start(Spec { - filter: Filter { processes, min_level }, - pid, - path, - max_bytes, - })) + Ok(Request::Start(Spec { filter: Filter { processes, min_level }, pid, limits, file })) + } + "read" => { + let max = number("max")?.unwrap_or(DEFAULT_MATCHES); + if max == 0 { + return Err(Fail::invalid("`max` must be at least 1")); + } + Ok(Request::Read { + after: number("after")?.unwrap_or(0), + query: Query { grep: grep()?, max: max.min(MAX_MATCHES) as usize }, + }) } "stop" => { - let grep = match given.get("grep") { - None => None, - Some(v) => { - let pattern = v.as_str().ok_or_else(|| Fail::invalid("`grep` takes a regular expression"))?; - Some(Regex::new(pattern).map_err(|e| Fail::invalid(format!("`grep`: {e}")))?) - } - }; + let grep = grep()?; let max = number("max")?; if grep.is_none() && max.is_none() { return Ok(Request::Stop(None)); @@ -284,6 +367,132 @@ pub fn parse(args: &Value, default_path: impl FnOnce() -> PathBuf) -> Res, + bytes: usize, + /// The seq of the next entry kept. The first is 1. + next_seq: u64, + limits: Limits, +} + +/// One `read`: the matching entries oldest first and where to go on. +#[derive(Debug, PartialEq)] +pub struct Page { + pub entries: Vec, + /// Pass it as `after` to the next read. Everything up to it has been + /// returned or did not match; nothing after it has been looked at, except + /// when it is the newest seq, which means everything has. + pub cursor: u64, + /// `max` cut the page short: another matching entry is already waiting. + pub more: bool, + /// Entries newer than `after` that were evicted before this read. + pub dropped: u64, +} + +impl Ring { + pub fn new(limits: Limits) -> Self { + Self { entries: VecDeque::new(), bytes: 0, next_seq: 1, limits } + } + + fn first_seq(&self) -> u64 { + self.next_seq - self.entries.len() as u64 + } + + fn newest_seq(&self) -> u64 { + self.next_seq - 1 + } + + /// Keep an entry, evicting the oldest while over a limit. An entry larger + /// than the byte budget evicts itself and everything before it. + pub fn push(&mut self, entry: Entry) -> u64 { + let seq = self.next_seq; + self.next_seq += 1; + self.bytes += entry.weight(); + self.entries.push_back(entry); + while self.entries.len() > self.limits.entries || self.bytes > self.limits.bytes { + let Some(old) = self.entries.pop_front() else { break }; + self.bytes = self.bytes.saturating_sub(old.weight()); + } + seq + } + + pub fn usage(&self) -> Value { + let mut v = json!({ + "entries": self.entries.len(), + "bytes": self.bytes, + "max_entries": self.limits.entries, + "max_bytes": self.limits.bytes, + "evicted": self.first_seq() - 1, + }); + if !self.entries.is_empty() { + v["oldest_seq"] = json!(self.first_seq()); + } + if self.next_seq > 1 { + v["newest_seq"] = json!(self.newest_seq()); + } + v + } + + /// The entries newer than `after` whose message matches, at most `max`, + /// oldest first. A cursor is only meaningful in the capture that issued + /// it, since seqs begin again at 1 with each capture. One that is newer + /// than every entry returns nothing and gets the newest seq back, so it + /// cannot run ahead of the buffer. + pub fn read(&self, after: u64, grep: Option<&Regex>, max: usize) -> Page { + let first = self.first_seq(); + let newest = self.newest_seq(); + let next = after.saturating_add(1); + let skip = usize::try_from(next.saturating_sub(first)).unwrap_or(usize::MAX); + let mut entries = Vec::new(); + let mut last = None; + let mut more = false; + for (i, entry) in self.entries.iter().enumerate().skip(skip) { + if grep.is_some_and(|re| !re.is_match(&entry.message)) { + continue; + } + if entries.len() == max { + more = true; + break; + } + let seq = first + i as u64; + entries.push(entry.value(seq, MATCH_CHARS)); + last = Some(seq); + } + Page { + entries, + cursor: if more { last.unwrap_or(after.min(newest)) } else { newest }, + more, + dropped: first.saturating_sub(next), + } + } + + /// The latest `max` entries whose message matches, oldest first, with + /// the number that matched in all. + pub fn latest(&self, grep: Option<&Regex>, max: usize) -> (Vec, u64) { + let first = self.first_seq(); + let mut found = VecDeque::new(); + let mut matched = 0; + for (i, entry) in self.entries.iter().enumerate() { + if grep.is_some_and(|re| !re.is_match(&entry.message)) { + continue; + } + matched += 1; + if max == 0 { + continue; + } + if found.len() == max { + found.pop_front(); + } + found.push_back(i); + } + let entries = found.into_iter().map(|i| self.entries[i].value(first + i as u64, MATCH_CHARS)).collect(); + (entries, matched) + } +} + /// Where the previous part goes when the file reaches its size. pub fn rotated(path: &Path) -> PathBuf { let mut name = path.file_name().unwrap_or_default().to_os_string(); @@ -349,8 +558,9 @@ impl Sink { /// On failure the file that holds the last entry stays open, so the /// `end` line still lands after it. fn rotate(&mut self) -> std::io::Result<()> { - // The handle goes first: Windows renames neither an open file nor - // over an existing one. + // Close the file and clear the old `.1` before the rename, so it + // does not depend on how a platform treats an open file or an + // existing target. if let Some(writer) = self.writer.as_mut() { writer.flush()?; } @@ -388,7 +598,8 @@ fn reopen(path: &Path) -> Option> { /// What the reading task and the session share. pub struct Live { - sink: Sink, + ring: Ring, + sink: Option, filter: Filter, pub seen: u64, pub kept: u64, @@ -398,20 +609,30 @@ pub struct Live { } impl Live { - pub fn new(sink: Sink, filter: Filter) -> Self { - Self { sink, filter, seen: 0, kept: 0, unparsed: 0, ended: None } + pub fn new(ring: Ring, sink: Option, filter: Filter) -> Self { + Self { ring, sink, filter, seen: 0, kept: 0, unparsed: 0, ended: None } } - pub fn take(&mut self, entry: &Entry) -> std::io::Result<()> { + pub fn take(&mut self, entry: Entry) -> std::io::Result<()> { if self.ended.is_some() { return Ok(()); } self.seen += 1; - if self.filter.keeps(entry) { - self.sink.write(&entry.line())?; - self.kept += 1; + if !self.filter.keeps(&entry) { + return Ok(()); } - Ok(()) + let line = self.sink.is_some().then(|| entry.line(self.ring.next_seq)); + self.ring.push(entry); + self.kept += 1; + match (self.sink.as_mut(), line) { + (Some(sink), Some(line)) => sink.write(&line), + _ => Ok(()), + } + } + + /// A line that is not an entry (`start`, `end`), for the file only. + fn note(&mut self, line: &Value) -> std::io::Result<()> { + self.sink.as_mut().map_or(Ok(()), |s| s.write(&line.to_string())) } /// Write the `end` line once; later calls change nothing. @@ -426,12 +647,58 @@ impl Live { "seen": self.seen, "kept": self.kept, "unparsed": self.unparsed, - "rotations": self.sink.rotations, + "rotations": self.sink.as_ref().map_or(0, |s| s.rotations), }); // The end line is what tells a reader the capture finished. - let _ = self.sink.append(&line.to_string()).and_then(|()| self.sink.flush()); + if let Some(sink) = self.sink.as_mut() { + let _ = sink.append(&line.to_string()).and_then(|()| sink.flush()); + } self.ended = Some(reason.to_string()); } + + fn flush(&mut self) { + let _ = self.sink.as_mut().map(Sink::flush); + } + + fn state(&self) -> &'static str { + if self.ended.is_none() { "running" } else { "ended" } + } + + /// `status`: what was received, and what the buffer holds. + fn counts(&self) -> Map { + let mut out = fields! { + "state": self.state(), + "seen": self.seen, + "kept": self.kept, + "unparsed": self.unparsed, + "buffer": self.ring.usage(), + }; + if let Some(sink) = &self.sink { + out.insert("rotations".into(), json!(sink.rotations)); + } + if let Some(reason) = &self.ended { + out.insert("ended_reason".into(), json!(reason)); + } + out + } + + /// `read`: the page, and whether the capture is still running, so a + /// caller that polls sees it end. + fn read(&self, after: u64, q: &Query) -> Map { + let page = self.ring.read(after, q.grep.as_ref(), q.max); + let mut out = fields! { + "state": self.state(), + "count": page.entries.len(), + "entries": page.entries, + "cursor": page.cursor, + "more": page.more, + "dropped": page.dropped, + }; + if let Some(reason) = &self.ended { + out.insert("ended_reason".into(), json!(reason)); + } + out + } } /// Puts buffered lines in the file while the stream is quiet. Not part of @@ -445,7 +712,7 @@ async fn flusher(live: Weak>) { if live.ended.is_some() { return; } - let _ = live.sink.flush(); + live.flush(); } } @@ -461,7 +728,7 @@ async fn pump(mut stream: OsTraceRelayReceiver, live: Arc>) { // Never under a timeout: an entry is several reads, and giving up // between them would leave the stream mid-entry. let reason = match stream.next().await { - Ok(log) => match live.lock().unwrap().take(&Entry::from(log)) { + Ok(log) => match live.lock().unwrap().take(Entry::from(log)) { Ok(()) => continue, Err(e) => format!("cannot write the file: {e}"), }, @@ -482,7 +749,8 @@ pub struct Capture { started: std::time::Instant, live: Arc>, task: tokio::task::JoinHandle<()>, - flusher: tokio::task::JoinHandle<()>, + /// Only with a file. + flusher: Option>, reset: Reset, } @@ -493,14 +761,16 @@ impl Capture { pub fn end(&self, reason: &str) { self.reset.now(); self.task.abort(); - self.flusher.abort(); + if let Some(flusher) = &self.flusher { + flusher.abort(); + } self.live.lock().unwrap().end(reason); } /// After `end`: wait until the connection has been reset, so the relay /// has let go of it before the next capture connects or the daemon exits. pub async fn settle(&mut self) { - let _ = tokio::time::timeout(std::time::Duration::from_secs(1), self.reset.sent()).await; + let _ = tokio::time::timeout(Duration::from_secs(1), self.reset.sent()).await; } /// A task that stopped without saying why (a panic in the parser). @@ -515,38 +785,13 @@ impl Capture { self.live.lock().unwrap().ended.is_none() } - pub fn report(&self) -> Map { - self.check(); - let live = self.live.lock().unwrap(); - let mut out = fields! { - "state": if live.ended.is_none() { "running" } else { "ended" }, - "path": self.spec.path.display().to_string(), - "started_at": self.started_at, - "seen": live.seen, - "kept": live.kept, - "unparsed": live.unparsed, - "rotations": live.sink.rotations, - }; - if !self.spec.filter.processes.is_empty() { - out.insert("process".into(), json!(self.spec.filter.processes)); - } - if let Some(pid) = self.spec.pid { - out.insert("pid".into(), json!(pid)); - } - if let Some(level) = self.spec.filter.min_level { - out.insert("level".into(), json!(level.name())); - } - if live.sink.rotations > 0 { - out.insert("previous_part".into(), json!(rotated(&self.spec.path).display().to_string())); - } - if let Some(reason) = &live.ended { - out.insert("ended_reason".into(), json!(reason)); - } - // Not with a pid: a quiet process sends nothing either. + /// While nothing has arrived for a while: why that can be. Not with + /// `--pid`, where a quiet process sends nothing either. + fn hint_if_silent(&self, live: &Live, out: &mut Map) { if live.ended.is_none() && self.spec.pid.is_none() && live.seen == 0 - && self.started.elapsed() > std::time::Duration::from_secs(5) + && self.started.elapsed() > Duration::from_secs(5) { // Seen live: a relay connection that was dropped, not reset, // held the next capture for about 30 s. @@ -555,83 +800,99 @@ impl Capture { "No entries yet. Right after a dropped connection the phone starts sending about 30 s later.", ))); } + } + + pub fn read(&self, after: u64, q: &Query) -> Map { + self.check(); + let live = self.live.lock().unwrap(); + let mut out = live.read(after, q); + self.hint_if_silent(&live, &mut out); out } -} -/// Entries in `files` (oldest first) whose message matches, the most recent -/// `max` of them, with the number that matched in all. -pub fn search(files: &[PathBuf], grep: Option<&Regex>, max: usize) -> (Vec, u64) { - let mut found = VecDeque::new(); - let mut matched = 0; - for path in files { - let Ok(file) = File::open(path) else { continue }; - for line in BufReader::new(file).lines().map_while(Result::ok) { - let Ok(Value::Object(mut entry)) = serde_json::from_str::(&line) else { continue }; - if entry.contains_key("event") { - continue; - } - let message = entry.get("message").and_then(|m| m.as_str()).unwrap_or("").to_string(); - if grep.is_some_and(|re| !re.is_match(&message)) { - continue; - } - matched += 1; - if max == 0 { - continue; - } - if message.chars().count() > MATCH_CHARS { - entry.insert("message".into(), json!(message.chars().take(MATCH_CHARS).collect::())); - entry.insert("message_cut".into(), json!(true)); - } - if found.len() == max { - found.pop_front(); + pub fn report(&self) -> Map { + self.check(); + let live = self.live.lock().unwrap(); + let mut out = live.counts(); + out.insert("started_at".into(), json!(self.started_at)); + if !self.spec.filter.processes.is_empty() { + out.insert("process".into(), json!(self.spec.filter.processes)); + } + if let Some(pid) = self.spec.pid { + out.insert("pid".into(), json!(pid)); + } + if let Some(level) = self.spec.filter.min_level { + out.insert("level".into(), json!(level.name())); + } + if let Some(file) = &self.spec.file { + out.insert("path".into(), json!(file.path.display().to_string())); + if live.sink.as_ref().is_some_and(|s| s.rotations > 0) { + out.insert("previous_part".into(), json!(rotated(&file.path).display().to_string())); } - found.push_back(Value::Object(entry)); } + self.hint_if_silent(&live, &mut out); + out } - (found.into(), matched) } impl Session { pub async fn cmd_syslog(&mut self, args: &Value) -> Res { let udid = self.udid.clone(); - let request = parse(args, || paths::state_dir().join(format!("{udid}.syslog.jsonl")))?; - match request { + match parse(args)? { Request::Status => Ok(match &self.capture { Some(c) => c.report(), None => fields! { "state": "none" }, }), + Request::Read { after, query } => match &self.capture { + Some(c) => Ok(c.read(after, &query)), + None => Err(Fail::not_sent("no_capture", "no capture to read").hint(crate::i18n::t( + "`iph syslog start`로 먼저 시작하세요.", + "Start one with `iph syslog start`.", + ))), + }, Request::Start(spec) => { - if let Some(c) = self.capture.as_ref().filter(|c| c.is_running()) { - return Err(Fail::not_sent("capture_running", "a capture is already running") - .with("path", c.spec.path.display().to_string()) - .hint(crate::i18n::t( + if let Some(c) = &self.capture { + // An ended capture is kept for `read` until `stop`. + let (code, message) = if c.is_running() { + ("capture_running", "a capture is already running") + } else { + ("capture_ended", "an ended capture has not been stopped") + }; + return Err(Fail::not_sent(code, message).with("started_at", c.started_at.clone()).hint( + crate::i18n::t( "`iph syslog stop`으로 끝낸 뒤 다시 시작하세요.", "End it with `iph syslog stop` first.", - ))); + ), + )); } // The file is opened only once the relay runs: a start that // fails leaves an earlier capture's file as it was. let (stream, reset) = self.os_trace(spec.pid).await?; - let sink = Sink::create(&spec.path, spec.max_bytes) - .map_err(|e| Fail::invalid(format!("{}: {e}", spec.path.display())))?; - let mut live = Live::new(sink, spec.filter.clone()); + let sink = spec + .file + .as_ref() + .map(|f| { + Sink::create(&f.path, f.max_bytes).map_err(|e| Fail::invalid(format!("{}: {e}", f.path.display()))) + }) + .transpose()?; + let mut live = Live::new(Ring::new(spec.limits), sink, spec.filter.clone()); let started_at = clock::now_utc(); let start = json!({ "event": "start", "time": started_at, - "udid": self.udid, + "udid": udid, "process": spec.filter.processes, "pid": spec.pid, "level": spec.filter.min_level.map(Level::name), - "max_mb": spec.max_bytes / (1024 * 1024), + "max_mb": spec.file.as_ref().map(|f| f.max_bytes / (1024 * 1024)), }); - if let Err(e) = live.sink.write(&start.to_string()) { - return Err(Fail::invalid(format!("{}: {e}", spec.path.display()))); + if let Err(e) = live.note(&start) { + let path = spec.file.as_ref().map(|f| f.path.display().to_string()).unwrap_or_default(); + return Err(Fail::invalid(format!("{path}: {e}"))); } let live = Arc::new(Mutex::new(live)); let task = tokio::task::spawn_local(pump(stream, live.clone())); - let flusher = tokio::task::spawn_local(flusher(Arc::downgrade(&live))); + let flusher = spec.file.is_some().then(|| tokio::task::spawn_local(flusher(Arc::downgrade(&live)))); let started = std::time::Instant::now(); let capture = Capture { spec, started_at, started, live, task, flusher, reset }; let report = capture.report(); @@ -646,17 +907,16 @@ impl Session { capture.settle().await; let mut out = capture.report(); if let Some(q) = query { - let files = [rotated(&capture.spec.path), capture.spec.path.clone()]; - let (matches, matched) = search(&files, q.grep.as_ref(), q.max); + let (entries, matched) = capture.live.lock().unwrap().ring.latest(q.grep.as_ref(), q.max); out.insert("matched".into(), json!(matched)); - out.insert("matches".into(), json!(matches)); + out.insert("entries".into(), json!(entries)); } Ok(out) } } } - /// End the capture, keeping it for `status` and `stop` to report. + /// End the capture, keeping it for `status`, `read` and `stop`. pub fn end_capture(&mut self, reason: &str) { if let Some(c) = &self.capture { c.end(reason); @@ -713,6 +973,14 @@ mod tests { } } + fn note(message: &str) -> Entry { + entry("Papago", Level::Info, message) + } + + fn roomy() -> Limits { + Limits { entries: 1000, bytes: 1 << 20 } + } + fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("iph-syslog-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); @@ -728,24 +996,57 @@ mod tests { .collect() } + fn seqs(page: &Page) -> Vec { + page.entries.iter().map(|e| e["seq"].as_u64().unwrap()).collect() + } + + fn messages(page: &Page) -> Vec<&str> { + page.entries.iter().map(|e| e["message"].as_str().unwrap()).collect() + } + + /// A ring holding `n` entries "m1".."mN" (seq 1..=N). + fn filled(limits: Limits, n: u64) -> Ring { + let mut ring = Ring::new(limits); + for i in 1..=n { + assert_eq!(ring.push(note(&format!("m{i}"))), i); + } + ring + } + #[test] fn an_entry_becomes_one_json_line_named_by_its_executable() { let e = Entry::from(log("/Applications/Preferences.app/Preferences", "Error", Some(("com.apple.settings", "ui")))); - let v: Value = serde_json::from_str(&e.line()).unwrap(); + let v: Value = serde_json::from_str(&e.line(7)).unwrap(); assert_eq!( v, json!({ - "time": "2026-11-19T01:02:03.004005Z", "pid": 412, "process": "Preferences", "sender": "UIKitCore", + "seq": 7, "time": "2026-11-19T01:02:03.004005Z", "pid": 412, "process": "Preferences", "sender": "UIKitCore", "level": "error", "subsystem": "com.apple.settings", "category": "ui", "message": "tapped row", }) ); let plain = Entry::from(log("/usr/libexec/backboardd", "Notice", None)); - let v: Value = serde_json::from_str(&plain.line()).unwrap(); + let v: Value = serde_json::from_str(&plain.line(1)).unwrap(); assert_eq!(v["process"], "backboardd"); assert_eq!(v["level"], "notice"); assert!(v.get("subsystem").is_none()); } + #[test] + fn a_long_message_is_cut_in_a_reply_and_whole_in_the_file() { + let long = note(&"y".repeat(900)); + let cut = long.value(3, MATCH_CHARS); + assert_eq!(cut["message"].as_str().unwrap().chars().count(), MATCH_CHARS); + assert_eq!(cut["message_cut"], true); + let whole: Value = serde_json::from_str(&long.line(3)).unwrap(); + assert_eq!(whole["message"].as_str().unwrap().len(), 900); + assert!(whole.get("message_cut").is_none()); + let short = note("short").value(3, MATCH_CHARS); + assert!(short.get("message_cut").is_none()); + // Cut by characters, not bytes. + let korean = note(&"가".repeat(600)).value(1, MATCH_CHARS); + assert_eq!(korean["message"].as_str().unwrap().chars().count(), MATCH_CHARS); + } + #[test] fn the_filter_keeps_named_processes_at_or_above_a_level() { let any = Filter::default(); @@ -780,6 +1081,200 @@ mod tests { assert_eq!(sorted, [Level::Debug, Level::Info, Level::Notice, Level::Error, Level::Fault]); } + #[test] + fn kept_entries_get_seqs_from_one_and_the_oldest_are_evicted_by_count() { + let mut ring = filled(Limits { entries: 3, bytes: 1 << 20 }, 5); + let usage = ring.usage(); + assert_eq!( + (usage["entries"].as_u64(), usage["oldest_seq"].as_u64(), usage["newest_seq"].as_u64(), usage["evicted"].as_u64()), + (Some(3), Some(3), Some(5), Some(2)) + ); + assert_eq!(usage["max_entries"], 3); + assert_eq!(ring.push(note("m6")), 6, "a seq is never reused"); + assert_eq!(messages(&ring.read(0, None, 10)), ["m4", "m5", "m6"]); + let fresh = Ring::new(roomy()).usage(); + assert!(fresh.get("oldest_seq").is_none() && fresh.get("newest_seq").is_none()); + assert_eq!(fresh["evicted"], 0); + } + + #[test] + fn the_byte_budget_evicts_by_weight_and_the_count_stays_exact() { + let w = note("m1").weight(); + let mut ring = Ring::new(Limits { entries: 100, bytes: 3 * w }); + for i in 1..=5 { + ring.push(note(&format!("m{i}"))); + } + let usage = ring.usage(); + assert_eq!(usage["entries"], 3); + assert_eq!(usage["bytes"], 3 * w); + assert_eq!(usage["oldest_seq"], 3); + // A heavy entry pushes out as many light ones as it takes. + ring.push(note(&"z".repeat(w))); + let usage = ring.usage(); + assert!(usage["bytes"].as_u64().unwrap() <= 3 * w as u64); + assert_eq!((usage["newest_seq"].as_u64(), usage["oldest_seq"].as_u64(), usage["entries"].as_u64()), (Some(6), Some(5), Some(2))); + } + + #[test] + fn an_entry_larger_than_the_whole_budget_evicts_itself_and_the_ring_goes_on() { + let mut ring = Ring::new(Limits { entries: 10, bytes: note("m1").weight() * 2 }); + ring.push(note("m1")); + assert_eq!(ring.push(note(&"z".repeat(10_000))), 2); + let usage = ring.usage(); + assert_eq!((usage["entries"].as_u64(), usage["bytes"].as_u64(), usage["evicted"].as_u64()), (Some(0), Some(0), Some(2))); + let page = ring.read(0, None, 10); + assert_eq!((page.entries.len(), page.cursor, page.dropped), (0, 2, 2)); + ring.push(note("m3")); + assert_eq!(seqs(&ring.read(2, None, 10)), [3]); + } + + #[test] + fn a_read_without_after_starts_at_the_oldest_kept_entry() { + let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 6); + let page = ring.read(0, None, 10); + assert_eq!(seqs(&page), [3, 4, 5, 6]); + assert_eq!((page.cursor, page.more, page.dropped), (6, false, 2), "the two evicted before this first read are reported"); + let untouched = filled(roomy(), 3).read(0, None, 10); + assert_eq!((seqs(&untouched), untouched.cursor, untouched.dropped), (vec![1, 2, 3], 3, 0)); + } + + #[test] + fn a_read_after_a_seq_the_ring_still_holds_returns_only_what_is_newer() { + let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 6); + let page = ring.read(4, None, 10); + assert_eq!((seqs(&page), page.cursor, page.dropped, page.more), (vec![5, 6], 6, 0, false)); + let page = ring.read(2, None, 10); + assert_eq!((seqs(&page), page.dropped), (vec![3, 4, 5, 6], 0), "seq 2 was the last one the caller had; 3 is still here"); + } + + #[test] + fn a_read_after_a_seq_older_than_the_ring_counts_what_was_lost() { + let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 10); + // Held: 7..=10. The caller has 3, so 4, 5 and 6 are gone. + let page = ring.read(3, None, 10); + assert_eq!(seqs(&page), [7, 8, 9, 10]); + assert_eq!((page.dropped, page.cursor), (3, 10)); + } + + #[test] + fn a_read_after_the_newest_seq_is_empty_and_a_cursor_beyond_it_is_pulled_back() { + let ring = filled(roomy(), 3); + let caught_up = ring.read(3, None, 10); + assert_eq!((caught_up.entries.len(), caught_up.cursor, caught_up.more, caught_up.dropped), (0, 3, false, 0)); + // A cursor from an earlier capture, whose seqs ran higher. + let stale = ring.read(5000, None, 10); + assert_eq!((stale.entries.len(), stale.cursor, stale.dropped), (0, 3, 0)); + let empty = Ring::new(roomy()).read(0, None, 10); + assert_eq!((empty.entries.len(), empty.cursor, empty.more, empty.dropped), (0, 0, false, 0)); + assert_eq!(Ring::new(roomy()).read(u64::MAX, None, 10).cursor, 0); + } + + #[test] + fn a_grep_with_no_match_returns_nothing_and_still_moves_the_cursor() { + let ring = filled(roomy(), 5); + let re = Regex::new("nothing like this").unwrap(); + let page = ring.read(1, Some(&re), 10); + assert_eq!((page.entries.len(), page.cursor, page.more, page.dropped), (0, 5, false, 0)); + // Reading on from that cursor looks at nothing already looked at. + let mut ring = ring; + ring.push(note("nothing like this, at last")); + assert_eq!(seqs(&ring.read(page.cursor, Some(&re), 10)), [6]); + } + + #[test] + fn max_cuts_a_page_and_the_cursor_continues_exactly_after_the_last_entry_returned() { + let ring = filled(roomy(), 7); + let first = ring.read(0, None, 3); + assert_eq!((seqs(&first), first.cursor, first.more), (vec![1, 2, 3], 3, true)); + let second = ring.read(first.cursor, None, 3); + assert_eq!((seqs(&second), second.cursor, second.more), (vec![4, 5, 6], 6, true)); + let last = ring.read(second.cursor, None, 3); + assert_eq!((seqs(&last), last.cursor, last.more), (vec![7], 7, false)); + // A page that is exactly full and has nothing behind it is not "more". + let exact = ring.read(4, None, 3); + assert_eq!((seqs(&exact), exact.cursor, exact.more), (vec![5, 6, 7], 7, false)); + } + + #[test] + fn a_grep_cut_by_max_leaves_the_cursor_on_the_last_match_so_nothing_between_is_skipped() { + let mut ring = Ring::new(roomy()); + for i in 1..=10 { + ring.push(note(&if i % 3 == 0 { format!("hit {i}") } else { format!("miss {i}") })); + } + let re = Regex::new("^hit").unwrap(); + let first = ring.read(0, Some(&re), 2); + assert_eq!((seqs(&first), first.cursor, first.more), (vec![3, 6], 6, true)); + let second = ring.read(first.cursor, Some(&re), 2); + assert_eq!((seqs(&second), second.cursor, second.more), (vec![9], 10, false)); + } + + #[test] + fn paging_to_the_end_equals_one_read_of_the_same_filter() { + let mut ring = Ring::new(roomy()); + for i in 1..=60 { + ring.push(note(&if i % 4 == 0 { format!("hit {i}") } else { format!("miss {i}") })); + } + let re = Regex::new("^hit").unwrap(); + let whole = seqs(&ring.read(0, Some(&re), 1000)); + for max in [1, 2, 3, 7, 15] { + let (mut cursor, mut got) = (0, Vec::new()); + loop { + let page = ring.read(cursor, Some(&re), max); + assert_eq!(page.dropped, 0); + assert!(page.cursor >= cursor, "the cursor never goes back"); + got.extend(seqs(&page)); + cursor = page.cursor; + if !page.more { + break; + } + } + assert_eq!(got, whole, "max {max}"); + assert_eq!(cursor, 60); + } + } + + #[test] + fn eviction_between_pages_is_reported_and_the_cursor_still_leaves_no_gap_in_what_remains() { + let mut ring = Ring::new(Limits { entries: 5, bytes: 1 << 20 }); + let push = |ring: &mut Ring, from: u64, to: u64| { + for i in from..=to { + ring.push(note(&if i % 2 == 0 { format!("hit {i}") } else { format!("miss {i}") })); + } + }; + let re = Regex::new("^hit").unwrap(); + push(&mut ring, 1, 8); + // Held: 4..=8. Seqs 1, 2 and 3 went before anything was read. + let a = ring.read(0, Some(&re), 2); + assert_eq!((seqs(&a), a.cursor, a.more, a.dropped), (vec![4, 6], 6, true, 3)); + push(&mut ring, 9, 12); + // Held: 8..=12. Seq 7 went while the caller was away. + let b = ring.read(a.cursor, Some(&re), 2); + assert_eq!((seqs(&b), b.cursor, b.more, b.dropped), (vec![8, 10], 10, true, 1)); + let c = ring.read(b.cursor, Some(&re), 2); + assert_eq!((seqs(&c), c.cursor, c.more, c.dropped), (vec![12], 12, false, 0)); + } + + #[test] + fn latest_returns_the_most_recent_matches_oldest_first_with_the_total() { + let mut ring = Ring::new(roomy()); + for i in 0..3 { + ring.push(note(&format!("hit {i}"))); + } + ring.push(note("miss")); + ring.push(note(&format!("hit 3 {}", "y".repeat(900)))); + let re = Regex::new("^hit").unwrap(); + let (found, matched) = ring.latest(Some(&re), 2); + assert_eq!(matched, 4); + assert_eq!(found.iter().map(|e| e["seq"].as_u64().unwrap()).collect::>(), [3, 5]); + assert_eq!(found[0]["message"], "hit 2"); + assert_eq!(found[1]["message"].as_str().unwrap().chars().count(), MATCH_CHARS); + assert_eq!(found[1]["message_cut"], true); + let (all, matched) = ring.latest(None, 0); + assert_eq!((all.len(), matched), (0, 5), "max 0 only counts"); + let (everything, _) = ring.latest(None, 1000); + assert_eq!(everything.len(), 5); + } + #[test] fn the_file_rolls_over_at_its_size_with_whole_lines_in_both_parts() { let dir = temp_dir("rotate"); @@ -821,7 +1316,7 @@ mod tests { std::fs::create_dir_all(rotated(&path).join("x")).unwrap(); sink.write(&json!({ "message": "a".repeat(100) }).to_string()).unwrap(); assert!(sink.write(&json!({ "message": "b".repeat(100) }).to_string()).is_err()); - let mut live = Live::new(sink, Filter::default()); + let mut live = Live::new(Ring::new(roomy()), Some(sink), Filter::default()); live.end("cannot write the file"); let got = lines(&path); assert_eq!(got.len(), 2, "the entry before the failed rotation, then the end line"); @@ -848,9 +1343,10 @@ mod tests { fn the_flusher_puts_a_quiet_capture_in_the_file() { let dir = temp_dir("flusher"); let path = dir.join("cap.jsonl"); - let live = Arc::new(Mutex::new(Live::new(Sink::create(&path, 1 << 20).unwrap(), Filter::default()))); - live.lock().unwrap().take(&entry("Papago", Level::Info, "quiet")).unwrap(); - let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap(); + let sink = Sink::create(&path, 1 << 20).unwrap(); + let live = Arc::new(Mutex::new(Live::new(Ring::new(roomy()), Some(sink), Filter::default()))); + live.lock().unwrap().take(note("quiet")).unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread().enable_time().start_paused(true).build().unwrap(); runtime.block_on(async { let task = tokio::spawn(flusher(Arc::downgrade(&live))); tokio::time::sleep(FLUSH_EVERY * 4).await; @@ -866,15 +1362,15 @@ mod tests { let dir = temp_dir("end"); let path = dir.join("cap.jsonl"); let filter = Filter { processes: vec!["Papago".into()], min_level: None }; - let mut live = Live::new(Sink::create(&path, 1 << 20).unwrap(), filter); - live.take(&entry("Papago", Level::Info, "one")).unwrap(); - live.take(&entry("SpringBoard", Level::Info, "other")).unwrap(); + let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), filter); + live.take(note("one")).unwrap(); + live.take(entry("SpringBoard", Level::Info, "other")).unwrap(); live.end("the log stream ended: socket closed"); live.end("stopped"); - live.take(&entry("Papago", Level::Info, "late")).unwrap(); + live.take(note("late")).unwrap(); let got = lines(&path); - assert_eq!(got.len(), 2); - assert_eq!(got[0]["message"], "one"); + assert_eq!(got.len(), 2, "the end line is flushed without anyone asking"); + assert_eq!((got[0]["seq"].as_u64(), got[0]["message"].as_str()), (Some(1), Some("one"))); assert_eq!(got[1]["event"], "end"); assert_eq!(got[1]["reason"], "the log stream ended: socket closed"); assert_eq!((got[1]["seen"].as_u64(), got[1]["kept"].as_u64()), (Some(2), Some(1))); @@ -883,37 +1379,64 @@ mod tests { } #[test] - fn search_returns_the_latest_matches_cut_to_length() { - let dir = temp_dir("search"); - let older = dir.join("cap.jsonl.1"); - let newer = dir.join("cap.jsonl"); - // The current part first: starting it removes an earlier `.1`. - let mut b = Sink::create(&newer, 1 << 20).unwrap(); - let mut a = Sink::create(&older, 1 << 20).unwrap(); - a.write(r#"{"event":"start"}"#).unwrap(); - for i in 0..3 { - a.write(&entry("Papago", Level::Info, &format!("hit {i}")).line()).unwrap(); - } - b.write(&entry("Papago", Level::Info, "miss").line()).unwrap(); - b.write(&entry("Papago", Level::Info, &format!("hit 3 {}", "y".repeat(900))).line()).unwrap(); - b.write(r#"{"event":"end","reason":"hit"}"#).unwrap(); - a.flush().unwrap(); - b.flush().unwrap(); - let files = [older, newer]; - let re = Regex::new("^hit").unwrap(); - let (found, matched) = search(&files, Some(&re), 2); - assert_eq!(matched, 4); - assert_eq!(found.len(), 2); - assert_eq!(found[0]["message"], "hit 2"); - assert_eq!(found[1]["message"].as_str().unwrap().chars().count(), MATCH_CHARS); - assert_eq!(found[1]["message_cut"], true); - let (all, matched) = search(&files, None, 0); - assert_eq!((all.len(), matched), (0, 5)); + fn without_a_file_nothing_is_written_and_the_ring_alone_serves_reads() { + let dir = temp_dir("memory"); + let mut live = Live::new(Ring::new(roomy()), None, Filter::default()); + live.take(note("one")).unwrap(); + live.note(&json!({ "event": "start" })).unwrap(); + live.end("stopped"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + let out = live.read(0, &Query { grep: None, max: 10 }); + assert_eq!(out["count"], 1); + assert!(live.counts().get("rotations").is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_file_and_the_ring_number_an_entry_alike() { + let dir = temp_dir("seq"); + let path = dir.join("cap.jsonl"); + let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), Filter::default()); + for m in ["a", "b", "c"] { + live.take(note(m)).unwrap(); + } + live.end("stopped"); + let in_file: Vec<(u64, String)> = lines(&path) + .iter() + .filter(|v| v.get("event").is_none()) + .map(|v| (v["seq"].as_u64().unwrap(), v["message"].as_str().unwrap().to_string())) + .collect(); + let page = live.ring.read(0, None, 10); + let in_ring: Vec<(u64, String)> = + page.entries.iter().map(|e| (e["seq"].as_u64().unwrap(), e["message"].as_str().unwrap().to_string())).collect(); + assert_eq!(in_file, in_ring); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn only_kept_entries_are_numbered_and_a_read_keeps_working_after_the_capture_ended() { + let filter = Filter { processes: vec!["Papago".into()], min_level: None }; + let mut live = Live::new(Ring::new(roomy()), None, filter); + live.take(note("one")).unwrap(); + live.take(entry("SpringBoard", Level::Info, "skipped")).unwrap(); + live.take(note("two")).unwrap(); + let q = Query { grep: None, max: 10 }; + let running = live.read(0, &q); + assert_eq!((running["state"].as_str(), running["cursor"].as_u64(), running["dropped"].as_u64()), (Some("running"), Some(2), Some(0))); + assert!(running.get("ended_reason").is_none()); + live.end("the connection to the phone was reset"); + let ended = live.read(1, &q); + assert_eq!(ended["state"], "ended"); + assert_eq!(ended["ended_reason"], "the connection to the phone was reset"); + assert_eq!(ended["entries"][0]["message"], "two"); + assert_eq!(ended["entries"][0]["seq"], 2); + let counts = live.counts(); + assert_eq!((counts["seen"].as_u64(), counts["kept"].as_u64()), (Some(3), Some(2))); + assert_eq!(counts["buffer"]["entries"], 2); + } + fn parsed(args: Value) -> Res { - parse(&args, || PathBuf::from("/state/u.syslog.jsonl")) + parse(&args) } fn absolute(name: &str) -> PathBuf { @@ -921,49 +1444,93 @@ mod tests { } #[test] - fn each_action_takes_only_its_own_arguments() { - let Ok(Request::Start(spec)) = parsed(json!({ - "action": "start", "process": "Preferences", "level": "default", "pid": null, "max_mb": 2, - })) else { + fn a_start_keeps_to_memory_unless_a_file_is_asked_for() { + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": "Preferences", "level": "default", "pid": null })) else { panic!("start") }; assert_eq!(spec.filter.processes, ["Preferences"]); assert_eq!(spec.filter.min_level, Some(Level::Notice)); - assert_eq!(spec.path, PathBuf::from("/state/u.syslog.jsonl")); - assert_eq!(spec.max_bytes, 2 * 1024 * 1024); - let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "max_mb": MAX_FILE_MB })) else { - panic!("the largest max_mb") - }; - assert_eq!(spec.max_bytes, MAX_FILE_MB * 1024 * 1024); + assert_eq!(spec.file, None); + assert_eq!(spec.limits, Limits { entries: 100_000, bytes: 64 * 1024 * 1024 }); let out = absolute("x.jsonl"); - let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": out })) else { - panic!("start with a list") + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": out, "max_mb": 2 })) else { + panic!("start with a file") }; assert_eq!((spec.filter.processes.len(), spec.pid), (2, Some(7))); - assert_eq!(spec.path, out); + assert_eq!(spec.file, Some(FileSpec { path: out.clone(), max_bytes: 2 * 1024 * 1024 })); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "output": out })) else { panic!("default size") }; + assert_eq!(spec.file.unwrap().max_bytes, DEFAULT_MAX_MB * 1024 * 1024); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "output": absolute("y.jsonl"), "max_mb": MAX_FILE_MB })) else { + panic!("the largest max_mb") + }; + assert_eq!(spec.file.unwrap().max_bytes, MAX_FILE_MB * 1024 * 1024); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "buffer_entries": 500, "buffer_mb": 2 })) else { + panic!("buffer limits") + }; + assert_eq!(spec.limits, Limits { entries: 500, bytes: 2 * 1024 * 1024 }); + } + #[test] + fn read_and_stop_take_a_cursor_a_pattern_and_a_count() { + let Ok(Request::Read { after, query }) = parsed(json!({ "action": "read" })) else { panic!("bare read") }; + assert_eq!((after, query.max, query.grep.is_none()), (0, DEFAULT_MATCHES as usize, true)); + let Ok(Request::Read { after, query }) = parsed(json!({ "action": "read", "after": 120, "grep": "a+", "max": 5000 })) else { + panic!("read") + }; + assert_eq!((after, query.max, query.grep.unwrap().as_str()), (120, MAX_MATCHES as usize, "a+")); assert!(matches!(parsed(json!({ "action": "stop" })), Ok(Request::Stop(None)))); let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "grep": "a+", "max": 5000 })) else { panic!("stop with grep") }; assert_eq!(q.max, MAX_MATCHES as usize); + let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "max": 0 })) else { panic!("stop to count") }; + assert_eq!(q.max, 0); assert!(matches!(parsed(json!({ "action": "status" })), Ok(Request::Status))); + } + #[test] + fn each_action_takes_only_its_own_arguments() { for bad in [ json!({}), json!({ "action": "pause" }), json!({ "action": "stop", "process": "A" }), + json!({ "action": "stop", "after": 3 }), + json!({ "action": "read", "process": "A" }), + json!({ "action": "read", "output": absolute("x.jsonl") }), + json!({ "action": "start", "after": 3 }), + json!({ "action": "start", "grep": "a" }), json!({ "action": "status", "grep": "a" }), + json!({ "action": "read", "after": "three" }), + json!({ "action": "read", "after": -1 }), + json!({ "action": "read", "max": 0 }), + json!({ "action": "read", "grep": "(" }), + json!({ "action": "stop", "grep": "(" }), json!({ "action": "start", "output": "relative.jsonl" }), json!({ "action": "start", "level": "loud" }), json!({ "action": "start", "process": "/Applications/Preferences.app/Preferences" }), - json!({ "action": "start", "max_mb": 0 }), - json!({ "action": "start", "max_mb": MAX_FILE_MB + 1 }), - json!({ "action": "start", "max_mb": u64::MAX }), - json!({ "action": "stop", "grep": "(" }), ] { let err = parsed(bad.clone()).expect_err(&bad.to_string()); assert_eq!(err.code, "invalid_argument", "{bad}"); } } + + #[test] + fn sizes_are_bounded_and_a_file_size_needs_a_file() { + let file = absolute("z.jsonl"); + for bad in [ + json!({ "action": "start", "output": file, "max_mb": 0 }), + json!({ "action": "start", "output": file, "max_mb": MAX_FILE_MB + 1 }), + json!({ "action": "start", "output": file, "max_mb": u64::MAX }), + json!({ "action": "start", "max_mb": 8 }), + json!({ "action": "start", "buffer_entries": 0 }), + json!({ "action": "start", "buffer_entries": MAX_BUFFER_ENTRIES + 1 }), + json!({ "action": "start", "buffer_mb": 0 }), + json!({ "action": "start", "buffer_mb": MAX_BUFFER_MB + 1 }), + json!({ "action": "start", "buffer_mb": u64::MAX }), + ] { + let err = parsed(bad.clone()).expect_err(&bad.to_string()); + assert_eq!(err.code, "invalid_argument", "{bad}"); + } + assert!(parsed(json!({ "action": "start", "buffer_entries": MAX_BUFFER_ENTRIES, "buffer_mb": MAX_BUFFER_MB })).is_ok()); + } } From 88c9ac24498a6bea4f0701eba74f29a7fe2c1cec Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 15:53:14 +0900 Subject: [PATCH 6/7] feat: filter `iph syslog` by app with `--app` An app's executable name is not something a person or an agent knows (Settings is `Preferences`), so `--process` meant a first capture just to look it up. `--app ` takes what `iph launch` takes: the name is resolved with the same `resolve_bundle`, then looked up in the phone's app list (refreshed once when the cached list lacks it) for the bundle's path. An entry is kept when the path of the executable that logged it, normalized as the app list's path is (`plain_path`: file URL, percent escapes, trailing slash, `/private/var` against `/var`), lies inside that bundle, so the app's extensions are included and the filter survives a restart of the app. An unknown or ambiguous app, or one the phone gave no path for, is a `not_sent` error before the capture slot, the file or the relay is touched. `--app` and `--process` each select: an entry is kept if it is from any listed app or process, and `--level` applies on top; `--pid` is filtered by the phone, so it narrows what either can match. The check runs on the raw executable path before the entry is built, so the buffer keeps only the file name. CLI `--app` (repeatable), MCP `iph_syslog` `app`, script `syslog("start", {app})`; `status` and the file's `start` line report the bundle ids. Co-Authored-By: Claude Opus 5.5 --- README.ko.md | 10 +- README.md | 10 +- skills/iph/SKILL.md | 20 ++- src/actions.rs | 2 +- src/device/session.rs | 2 +- src/human.rs | 7 +- src/main.rs | 17 +- src/mcp.rs | 13 +- src/syslog.rs | 370 ++++++++++++++++++++++++++++++++++-------- 9 files changed, 358 insertions(+), 93 deletions(-) diff --git a/README.ko.md b/README.ko.md index 04a2e99..d1df649 100644 --- a/README.ko.md +++ b/README.ko.md @@ -159,7 +159,7 @@ Apple 기기 연결 서비스가 필요합니다. CLI·MCP·스크립트는 선 | `iph run <이름> [--arg k=v]` / `iph scripts` | 저장된 스크립트 실행 · 목록 | | `iph mcp [--tools a,b]` | MCP 서버 (stdio) | | `iph dnd ` | 방해금지 모드를 켜기, 원래 집중 모드로 되돌리기, 지금 상태 보기 | -| `iph syslog [--process 이름] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o 파일]` | 다른 명령을 쓰는 동안 폰의 로그를 메모리에 모읍니다. `read`는 끝내지 않고 새로 들어온 항목만 돌려주고, `stop`은 조건에 맞는 최근 항목을 돌려줄 수 있습니다. 아래 [폰 로그](#폰-로그) | +| `iph syslog [--app 앱] [--process 이름] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o 파일]` | 다른 명령을 쓰는 동안 폰의 로그를 메모리에 모읍니다. `read`는 끝내지 않고 새로 들어온 항목만 돌려주고, `stop`은 조건에 맞는 최근 항목을 돌려줄 수 있습니다. 아래 [폰 로그](#폰-로그) | | `iph stop` | 이 폰의 상주 프로세스 종료 | ### 셀렉터 @@ -245,7 +245,7 @@ memory_mb = 64 # 스크립트가 쓸 수 있는 메모리 `iph syslog start`는 탭 · 읽기 · 스크립트를 그대로 쓰는 동안 폰이 남기는 로그를 상주 프로세스 안의 버퍼에 모읍니다. `iph syslog read`는 기록을 끝내지 않고 그 뒤에 들어온 항목만 돌려주므로, 탭을 할 때마다 앱이 무엇을 남겼는지 테스트나 에이전트가 확인할 수 있습니다. 맥에서 `sudo log collect`를 돌리지 않아도 됩니다. ```sh -iph syslog start --process Preferences # 설정 앱의 실행 파일 이름 +iph syslog start --app com.apple.Preferences # 앱을 bundle id나 이름으로 (`iph launch`와 같은 방식) iph launch com.apple.Preferences --restart iph tap "배터리" iph syslog read --grep "battery" # 시작한 뒤 남은 로그. 결과에 "cursor": 12가 있습니다 @@ -261,9 +261,9 @@ iph syslog stop # 또는 stop --grep "general" --m - `dropped`: `--after`보다 새 항목 가운데 이번 읽기 전에 버퍼에서 밀려난 수입니다. 0이 아니면 빠진 항목이 있다는 뜻이니, 더 자주 읽거나 거르세요. - 연결이 끊겨 끝난 기록도 `stop`하기 전에는 읽을 수 있습니다. - **파일(선택):** `-o <파일>`을 주면 남긴 항목을 메시지 전체와 함께 JSON Lines 파일에도 씁니다(나만 읽을 수 있습니다). `{"event": "start", …}` 줄, 항목마다 한 줄(`seq`, `time`(UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`), 마지막 `{"event": "end", "reason": …}` 줄입니다. `end` 줄이 없으면 상주 프로세스가 강제로 끝난 것입니다. `--max-mb` MiB(1~4096, 기본 64이며 `-o`가 있어야 합니다)에 닿으면 파일을 `<파일>.1`로 옮기고(이전 것은 지우고, `start` 줄도 함께 옮겨 갑니다) 새로 씁니다. 다시 시작하면 폰이 로그를 보내기 시작한 뒤에 파일을 비웁니다. 실패한 `start`는 파일을 건드리지 않습니다. -- **거르기:** `--process`는 실행 파일 이름이 정확히 같은 항목만 남깁니다 (여러 번 줄 수 있습니다). 앱을 다시 띄워도 계속 걸립니다. 설정 앱은 `Preferences`입니다. 다른 앱은 거르지 않고 한 번 받아서 `process` 칸을 보세요. `--level`은 debug, info, notice, error, fault 중 고른 것보다 낮은 항목을 뺍니다. `--pid`는 폰이 그 프로세스의 항목만 보내게 합니다. +- **거르기:** `--app`은 앱의 항목만 남깁니다. `iph launch`처럼 bundle id나 표시 이름으로 지정하고, 여러 번 줄 수 있습니다. `iph`가 앱이 설치된 위치를 찾아, 실행 파일이 그 번들 안에 있는 항목을 남깁니다. 그래서 앱의 확장도 포함되고, 앱을 다시 띄워도 계속 걸립니다. 설치되지 않은 앱이거나 이름이 둘 이상에 맞으면 아무것도 시작하기 전에 실패합니다. `--process`는 실행 파일 이름이 정확히 같은 항목만 남깁니다 (여러 번 줄 수 있습니다). 설정 앱은 `Preferences`입니다. 둘을 함께 주면 지정한 앱이나 프로세스 어느 쪽에든 맞는 항목을 남깁니다. `--level`은 debug, info, notice, error, fault 중 고른 것보다 낮은 항목을 뺍니다. 앱이나 프로세스로 고른 항목에도 똑같이 적용됩니다. `--pid`는 폰이 그 프로세스의 항목만 보내게 하므로, `--app`과 `--process`가 맞출 수 있는 범위를 좁힙니다. - **양:** 거르지 않으면 Wi-Fi에서 꽤 많습니다. 가만히 둔 60초 동안 초당 약 4,800개, 1.4MB가 왔습니다. 이 속도면 기본 버퍼는 약 20초(100,000개)를 담습니다. 더 길게 받을 때는 자주 읽거나 `--process`로 거르세요. JSON으로 약 290바이트인 항목은 메모리에서 약 430바이트라서, 기본 버퍼가 가득 차면 약 41MiB를 씁니다. 메시지가 길면 64MiB 제한이 걸립니다. -- **다른 명령에 주는 부담:** 거르지 않은 기록을 켜 둔 동안 탭과 읽기 모두 중앙값이 10% 안쪽으로 늘었습니다 (탭 10회 · 읽기 5회씩 비교, 한 번 측정). +- **다른 명령에 주는 부담:** Wi-Fi로 한 번 측정했을 때(iPhone 16 Pro, `iph`를 띄운 뒤 첫 탭. 기록 없이 6회, 초당 2,900~9,900개를 받는 거르지 않은 기록으로 4회, `--pid`로 3회) 기록은 탭을 늦추지 않았습니다. 중앙값은 10.0초, 10.1초, 9.7초였습니다. 6초를 넘은 탭은 기록이 있든 없든 모두 폰이 답하지 않은 화면 읽기 한 번을 기다렸고, `iph`는 6.5초 뒤에 다시 묻습니다. 상주 프로세스는 CPU 코어 하나의 12%를 넘지 않았습니다. 양 자체는 읽기에 부담을 줍니다. 폰이 잠긴 상태에서 거르지 않은 항목이 초당 9,000개 올 때 `read`는 2.3초, 기록이 없을 때는 1.0초 걸렸습니다. 그러니 Wi-Fi에서 읽기가 빨라야 하면 `--pid`를 쓰세요(`--app`과 `--process`는 항목이 네트워크를 건너온 뒤 컴퓨터에서 거릅니다). - **`stop`:** `seen`(폰이 보낸 항목 수), `kept`(버퍼에 넣은 수), `buffer`, 끝난 이유를 돌려주고, `-o`를 썼다면 `rotations`와 `path`도 줍니다. `--grep`이나 `--max`를 주면 버퍼에서 맞은 항목 전체 수 `matched`와, 그중 최근 `--max`개를 오래된 순서로 담은 `entries`(기본 50, 최대 1000, 메시지는 `read`처럼 자름)도 돌려줍니다. `stop`하면 버퍼가 사라지니 필요한 것은 먼저 읽으세요. - **기록이 끝나는 때:** `stop`, 연결이 끊겼을 때, `iph`가 연결을 새로 맺을 때 (명령이 시간을 넘기거나 폰이 답하지 않을 때), `iph stop`, 새 빌드의 `iph`가 상주 프로세스를 바꿀 때, 상주 프로세스가 오래 쓰이지 않아 끝날 때 (기록 중이어도 상주 프로세스는 그대로 끝납니다). 어느 것인지는 `end` 줄(`-o`를 썼을 때)과 `status`에 나옵니다. 저절로 다시 시작하지 않으므로 로그에 빈 구간이 생기면 드러납니다. 기록은 한 번에 하나입니다. 두 번째 `start`는 `capture_running`으로, 끝났지만 아직 `stop`하지 않은 기록이 있으면 `capture_ended`로 실패하니 먼저 `stop`하세요. - **연결이 끊긴 직후**에는 폰이 다음 기록에 약 20~30초 동안 아무것도 보내지 않습니다. 그동안 `status`와 `read`의 `hint`가 이를 알려 줍니다. @@ -312,7 +312,7 @@ iph scripts # 저장된 스크립트 목록 | `readField({selector, take, regex})` | 값 하나를 글자로. `take`: `value`(기본), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | 목록을 스크롤하며 겹치지 않게 모아 `{rows, scrolls, ended}`로 돌려줍니다 | | `sleep(ms)` · `log(…)` · `output(k, v)` | 대기 · 기록 · 결과에 값 넣기 | -| `syslog(action, {process, pid, level, after, grep, max})` | `iph syslog`입니다. 로그는 메모리에 남고 `syslog("read", {after})`로 읽습니다. 스크립트는 파일을 쓰지 못합니다. `inputs_sent`에 세지 않습니다 | +| `syslog(action, {app, process, pid, level, after, grep, max})` | `iph syslog`입니다. 로그는 메모리에 남고 `syslog("read", {after})`로 읽습니다. 스크립트는 파일을 쓰지 못합니다. `inputs_sent`에 세지 않습니다 | - 함수가 돌려주는 것은 같은 이름의 CLI 명령이 내는 JSON 객체 그대로입니다 (`tap("일반").screen_changed`, `read().elements`). 셀렉터는 문자열과 객체 둘 다 됩니다. - **실패는 예외입니다.** 실패한 호출은 `Error`를 던지고, `e.code`, `e.outcome`, `e.hint`, `e.result`(결과 객체 전체)가 붙어 있습니다. 잡지 않으면 스크립트가 거기서 멈추고 결과에 `failed_call: {cmd, line, outcome}`, `reason: {code, message}`, `screen_summary`가 담깁니다. 추측해서 진행하지 않습니다. 없어도 되는 것을 눌러 볼 때만 `try { … } catch (e) { … }`로 잡으세요. diff --git a/README.md b/README.md index ad19a00..ede7a8c 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ Every command prints JSON; add `--human` for people. The device is chosen by `-- | `iph run [--arg k=v]` / `iph scripts` | Run a saved script, list saved scripts | | `iph mcp [--tools a,b]` | MCP server on stdio | | `iph dnd ` | Turn Do Not Disturb on, put the earlier Focus back, or show the current state | -| `iph syslog [--process name] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o file]` | Capture the phone's log in memory while other commands run; `read` returns what is new without stopping it, `stop` can return the latest matching entries. See [Phone log](#phone-log) | +| `iph syslog [--app app] [--process name] [--pid N] [--level L] [--after SEQ] [--grep RE] [--max N] [-o file]` | Capture the phone's log in memory while other commands run; `read` returns what is new without stopping it, `stop` can return the latest matching entries. See [Phone log](#phone-log) | | `iph stop` | Stop the resident process for this phone | ### Selectors @@ -242,7 +242,7 @@ iph does not judge what it presses. Pay, send and order buttons are pressed like `iph syslog start` collects what the phone logs, in a buffer inside the resident process, while taps, reads and scripts go on as usual. `iph syslog read` returns what arrived since the last read without stopping the capture, so a test or an agent can check what an app logged after each tap. No `sudo log collect` on the Mac is needed. ```sh -iph syslog start --process Preferences # Settings' executable name +iph syslog start --app com.apple.Preferences # an app by bundle id or name, as `iph launch` takes it iph launch com.apple.Preferences --restart iph tap "Battery" iph syslog read --grep "battery" # what was logged since start; the result has "cursor": 12 @@ -258,9 +258,9 @@ iph syslog stop # or: stop --grep "general" --max - `dropped`: entries newer than `--after` that were pushed out of the buffer before this read. Anything but 0 means entries were lost; read more often or filter. - A capture that ended (a dropped connection) can still be read until you `stop` it. - **The file (optional):** `-o ` also writes every kept entry to a JSON Lines file with its whole message, readable by you only: a `{"event": "start", …}` line, one line per entry (`seq`, `time` (UTC), `pid`, `process`, `sender`, `level`, `subsystem`, `category`, `message`) and a final `{"event": "end", "reason": …}` line. A file without an `end` line was cut off by a killed resident process. At `--max-mb` MiB (1 to 4096, 64 by default; it needs `-o`) the file moves to `.1`, replacing the previous one (the `start` line goes with it). Starting again empties the file once the phone has started sending; a `start` that fails leaves it as it was. -- **Filters:** `--process` keeps entries by executable name, exactly (repeatable). It keeps matching across app restarts. Settings is `Preferences`; for another app, start without a filter and look at the `process` field. `--level` drops anything below debug, info, notice, error or fault. `--pid` makes the phone send only that process's entries. +- **Filters:** `--app` keeps the entries of an app, named by bundle id or display name the way `iph launch` takes it (repeatable). iph looks up where the app is installed and keeps an entry when its executable lies in that bundle, so the app's extensions count too and the filter keeps matching across restarts of the app. An app that is not installed (or a name that fits two) fails before anything starts. `--process` keeps entries by executable name, exactly (repeatable); Settings is `Preferences`. With both, an entry is kept if it is from any listed app or any listed process. `--level` drops anything below debug, info, notice, error or fault, whichever of those selected it. `--pid` makes the phone send only that process's entries, so it narrows what `--app` and `--process` can match. - **Volume:** unfiltered over Wi-Fi it is a lot. In one 60 s idle run the phone sent about 4,800 entries/s, 1.4 MB/s. At that rate the default buffer holds about 20 s (100,000 entries), so read often or filter with `--process` for anything longer. An entry of about 290 B as JSON weighs about 430 B in memory, so a full default buffer takes about 41 MiB; the 64 MiB limit applies when messages run long. -- **Cost to other commands:** with an unfiltered capture running, the median tap and the median read each took under 10% longer (10 taps and 5 reads each way, one run). +- **Cost to other commands:** in one run over Wi-Fi (an iPhone 16 Pro, the first tap after starting iph: 6 taps without a capture, 4 with an unfiltered capture receiving 2,900 to 9,900 entries/s, 3 with `--pid`), the capture did not slow taps: the medians were 10.0, 10.1 and 9.7 s. Every tap over 6 s, with a capture or without, waited for one screen reading the phone did not answer, which iph asks again after 6.5 s. The resident process used at most 12% of one core. The volume itself costs reads: with the phone locked, a `read` took 2.3 s at 9,000 unfiltered entries/s against 1.0 s without a capture, so over Wi-Fi use `--pid` when reads must stay quick (`--app` and `--process` filter on the computer, after the entries have crossed the network). - **`stop`:** returns `seen` (entries the phone sent), `kept` (put in the buffer), `buffer` and why it ended, and with `-o` also `rotations` and `path`. With `--grep` or `--max` it also returns `matched`, the number of entries in the buffer that matched, and `entries`, the latest `--max` of them, oldest first (50 by default, at most 1000, cut like `read`'s). The buffer is gone after `stop`, so read what you need first. - **What ends a capture:** `stop`, a dropped connection, iph rebuilding its connections (after a command times out or the phone stops answering), `iph stop`, a newer build of iph replacing the resident process, or the resident process exiting after its idle time (a capture does not keep it alive). The `end` line (with `-o`) and `status` say which. A capture is not restarted by itself, so a gap in the log is never hidden. One capture runs at a time: a second `start` fails with `capture_running`, or with `capture_ended` while an ended capture waits to be read; `stop` it first. - **After a dropped connection** the phone sends nothing to the next capture for about 20 to 30 s. `status` and `read` say so in a `hint` while nothing has arrived. @@ -309,7 +309,7 @@ iph scripts # list saved scripts | `readField({selector, take, regex})` | One value, as text. `take`: `value` (default), `label`, `identifier`, `text` | | `readList({row, columns, key, group, stop_below, until, max_scrolls, limit})` | Collect a list while scrolling, each row once; returns `{rows, scrolls, ended}` | | `sleep(ms)` · `log(…)` · `output(k, v)` | Wait, note, add a value to the result | -| `syslog(action, {process, pid, level, after, grep, max})` | `iph syslog`: the log stays in memory and `syslog("read", {after})` returns it, a script cannot write a file. Not counted in `inputs_sent` | +| `syslog(action, {app, process, pid, level, after, grep, max})` | `iph syslog`: the log stays in memory and `syslog("read", {after})` returns it, a script cannot write a file. Not counted in `inputs_sent` | - A function returns the JSON object the CLI command of the same name prints (`tap("일반").screen_changed`, `read().elements`). Selectors can be strings or objects. - **A failure is an exception.** A call that fails throws an `Error` carrying `e.code`, `e.outcome`, `e.hint` and `e.result` (the whole result object). Uncaught, it ends the script, and the result has `failed_call: {cmd, line, outcome}`, `reason: {code, message}` and `screen_summary`. Nothing is guessed. Use `try { … } catch (e) { … }` only around something that may legitimately be missing. diff --git a/skills/iph/SKILL.md b/skills/iph/SKILL.md index 4f5caca..a9b5502 100644 --- a/skills/iph/SKILL.md +++ b/skills/iph/SKILL.md @@ -79,7 +79,7 @@ A script is the body of a function, so `return` ends it. The commands are functi - `readList({row, columns, key, group, stop_below, max_scrolls})` scrolls a list and returns `{rows, scrolls, ended}` with each row once. `columns: {name: {take, regex}}`, or `{name: {value: "…"}}` for a constant. `group: {selector, regex, as}` gives each row the heading it stands under (a date line), and `stop_below: N` stops once a heading's number falls below N. `key: "column"` names the column that identifies a row; use it when rows change while the list is read (a clock, time left). - `args` holds the `--arg k=v` values as text (`Number(args.n)` for a number). Return an object, or call `output(key, value)`, and it comes back as `outputs`. `log(…)` lines come back as `logs`. `sleep(ms)` waits. - Any call takes `hint: "…"`: what to tell the person if the script stops there. A screen that waits for Face ID: `waitFor(sel, { timeout_ms: 40000, hint: "폰을 봐 주세요" })`. -- `syslog(action, {process, pid, level, after, grep, max})` captures the phone's log and returns what `iph syslog` does below (`syslog("read", {after: cursor})` for what is new). A script cannot write a file. +- `syslog(action, {app, process, pid, level, after, grep, max})` captures the phone's log and returns what `iph syslog` does below (`syslog("read", {after: cursor})` for what is new). A script cannot write a file. - There are no files, no network and no timers. `Date`, `JSON`, `RegExp` and the rest of the language work. ### When a call fails @@ -120,7 +120,23 @@ After `launch`, that app must stay in front; if another one comes up, the script ## What the app logged -To check what an app logged after a tap, start a capture, act, and read: `iph syslog start --process `, a step, `iph syslog read --grep `, the next step, `iph syslog read --after --grep `, and so on, then `iph syslog stop` (MCP: `iph_syslog` with `action`). The capture keeps its entries in memory, each with a `seq`; nothing is written to disk unless you pass `-o `. `read` does not stop the capture and returns `entries` newer than `--after`, oldest first, with a `cursor`: pass it as the next `--after` and no entry is read twice or skipped. A cursor belongs to the capture that gave it: after a new `start`, read without `--after`. Without `--after` it starts at the oldest entry the buffer holds. `more: true` means `--max` cut the page short (read again from the `cursor`); `dropped` above 0 means that many newer entries were pushed out of the buffer before you read, so read more often or filter. The buffer keeps the last 100,000 entries and goes with the capture, so `read` what you need before `stop`. A capture whose `state` is `ended` (the connection dropped) can still be read, and a new `start` fails with `capture_ended` until you `stop` it. The executable name is not the app's display name (Settings is `Preferences`); when you do not know it, start without `--process`, read after a second, and look at the `process` field of the entries for the app's pid. Unfiltered over Wi-Fi the phone sends thousands of entries a second (the buffer then holds about 20 s), so filter for anything longer. If `seen` is 0, nothing arrived: after a dropped connection the phone sends nothing for about 30 s, and `status` and `read` give a `hint` while it waits. Values the app marked private arrive as ``; that is the app's choice, not a failure. Messages come back cut to 500 characters (`message_cut`); `-o` keeps them whole. The entries are the user's data: quote only what the task needs. +To check what an app logged after a tap, start a capture, act, and read it as you go (MCP: `iph_syslog` with `action`): + +```sh +iph syslog start --app # entries are kept in memory; nothing is written to disk +iph tap "…" +iph syslog read --grep # entries, each with a seq, and "cursor": 12 +iph tap "…" +iph syslog read --after 12 --grep # only what is newer than the cursor +iph syslog stop +``` + +- `read` does not stop the capture. It returns `entries` newer than `--after`, oldest first, and a `cursor`: pass it as the next `--after` and no entry is read twice or skipped, even when `--grep` matched nothing. A cursor belongs to the capture that gave it: after a new `start`, read without `--after`. Without `--after` it starts at the oldest entry the buffer holds. +- `more: true` means `--max` cut the page short, so read again from the `cursor`. `dropped` above 0 means that many newer entries were pushed out of the buffer before you read: read more often or filter. A capture whose `state` is `ended` (the connection dropped) can still be read, and a new `start` fails with `capture_ended` until you `stop` it. +- The buffer keeps the last 100,000 entries and goes with the capture, so `read` what you need before `stop`. Messages come back cut to 500 characters (`message_cut`); `-o ` also writes them whole to a file. +- `--app` takes what `iph launch` takes (a bundle id or the display name) and keeps every entry from that app's install location, extensions included, across restarts; an app that is not installed fails before the capture starts. `--process ` names an executable instead (Settings is `Preferences`, not its display name). With both, an entry is kept if it matches any of them, and `--level` narrows the result. +- Unfiltered over Wi-Fi the phone sends thousands of entries a second, and the buffer then holds about 20 s: filter for anything longer. If `seen` is 0, nothing arrived: after a dropped connection the phone sends nothing for about 30 s, and `status` and `read` give a `hint` while it waits. +- Values the app marked private arrive as ``; that is the app's choice, not a failure. The entries are the user's data: quote only what the task needs. ## Commands at a glance diff --git a/src/actions.rs b/src/actions.rs index 1a4f46a..fa425b5 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1198,7 +1198,7 @@ impl Session { Ok(fields! { "count": list.len(), "apps": list }) } - async fn resolve_bundle(&mut self, app: &str) -> Res { + pub(crate) async fn resolve_bundle(&mut self, app: &str) -> Res { // Something with a dot and no spaces is a bundle id; anything else is // looked up by name. if app.contains('.') && !app.contains(' ') { diff --git a/src/device/session.rs b/src/device/session.rs index bf9688b..e3cd777 100644 --- a/src/device/session.rs +++ b/src/device/session.rs @@ -150,7 +150,7 @@ pub struct Session { } /// A file URL or path as a plain path without a trailing slash. -fn plain_path(s: &str) -> String { +pub(crate) fn plain_path(s: &str) -> String { let s = s.strip_prefix("file://").unwrap_or(s); let raw = s.as_bytes(); let mut bytes = Vec::with_capacity(raw.len()); diff --git a/src/human.rs b/src/human.rs index e615b0f..e980b05 100644 --- a/src/human.rs +++ b/src/human.rs @@ -116,6 +116,9 @@ fn syslog_status(v: &Value, out: &mut Vec) { buffer.push_str(&format!(", {} evicted", s(&b["evicted"]))); out.push(buffer); let mut only = Vec::new(); + if let Some(a) = v["app"].as_array() { + only.push(format!("app {}", a.iter().map(s).collect::>().join(", "))); + } if let Some(p) = v["process"].as_array() { only.push(format!("process {}", p.iter().map(s).collect::>().join(", "))); } @@ -373,13 +376,13 @@ mod tests { "ok": true, "state": "running", "seen": 5000, "kept": 1234, "unparsed": 0, "buffer": {"entries": 1234, "bytes": 700_000, "max_entries": 100_000, "max_bytes": 67_108_864, "oldest_seq": 1, "newest_seq": 1234, "evicted": 0}, - "started_at": "2026-11-19T01:00:00Z", "process": ["Papago", "Preferences"], "level": "info", + "started_at": "2026-11-19T01:00:00Z", "app": ["com.naver.papago"], "process": ["Preferences"], "level": "info", "path": "/tmp/cap.jsonl", "rotations": 2, }); let text = render("syslog", &status); assert!(text.contains("syslog running seen 5000 kept 1234 unparsed 0")); assert!(text.contains("buffer 1234/100000 entries, 683 KiB of 64.0 MiB, seq 1 to 1234, 0 evicted")); - assert!(text.contains("only process Papago, Preferences level info and up")); + assert!(text.contains("only app com.naver.papago process Preferences level info and up")); assert!(text.contains("file /tmp/cap.jsonl 2 rotations")); assert!(render("syslog", &json!({"ok": true, "state": "none"})).contains("no capture")); diff --git a/src/main.rs b/src/main.rs index 5e636dd..d640f16 100644 --- a/src/main.rs +++ b/src/main.rs @@ -194,6 +194,9 @@ enum Cmd { /// start: keep only this process, by executable name (Settings is Preferences). Repeatable. #[arg(long)] process: Vec, + /// start: keep only this app's entries, by bundle id or name as `iph launch` takes it. Repeatable; with --process an entry passes if it matches any. + #[arg(long)] + app: Vec, /// start: keep only this pid (the phone filters it). #[arg(long)] pid: Option, @@ -429,12 +432,13 @@ async fn run(cli: Cli) -> i32 { Cmd::Key { key } => ("key", json!({ "key": key })), Cmd::Button { button } => ("button", json!({ "button": button })), Cmd::Dnd { action } => ("dnd", json!({ "action": action })), - Cmd::Syslog { action, process, pid, level, output, max_mb, buffer_entries, buffer_mb, after, grep, max } => { + Cmd::Syslog { action, process, app, pid, level, output, max_mb, buffer_entries, buffer_mb, after, grep, max } => { // The daemon writes the file, so the path must not depend on its cwd. let output = output.map(|o| std::path::absolute(&o).map(|p| p.display().to_string()).unwrap_or(o)); let process = (!process.is_empty()).then_some(process); + let app = (!app.is_empty()).then_some(app); ("syslog", json!({ - "action": action, "process": process, "pid": pid, "level": level, "output": output, + "action": action, "process": process, "app": app, "pid": pid, "level": level, "output": output, "max_mb": max_mb, "buffer_entries": buffer_entries, "buffer_mb": buffer_mb, "after": after, "grep": grep, "max": max, })) @@ -549,15 +553,16 @@ mod tests { panic!("syslog read") }; assert_eq!((action.as_str(), after, grep.as_deref(), max), ("read", Some(120), Some("row"), Some(5))); - let Cmd::Syslog { process, output, max_mb, buffer_entries, buffer_mb, .. } = parse(&[ - "syslog", "start", "--process", "A", "--process", "B", "-o", "cap.jsonl", "--max-mb", "8", - "--buffer-entries", "500", "--buffer-mb", "2", + let Cmd::Syslog { process, app, output, max_mb, buffer_entries, buffer_mb, .. } = parse(&[ + "syslog", "start", "--process", "A", "--process", "B", "--app", "com.naver.papago", "--app", "설정", + "-o", "cap.jsonl", "--max-mb", "8", "--buffer-entries", "500", "--buffer-mb", "2", ]) .command else { panic!("syslog start") }; - assert_eq!((process, output.as_deref(), max_mb, buffer_entries, buffer_mb), (strings(&["A", "B"]), Some("cap.jsonl"), Some(8), Some(500), Some(2))); + assert_eq!((process, app), (strings(&["A", "B"]), strings(&["com.naver.papago", "설정"]))); + assert_eq!((output.as_deref(), max_mb, buffer_entries, buffer_mb), (Some("cap.jsonl"), Some(8), Some(500), Some(2))); } #[test] diff --git a/src/mcp.rs b/src/mcp.rs index 425d927..2be1fce 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -18,7 +18,7 @@ const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loo The commands are functions that return what the tool of the same name returns: read(opts), find(selector), tap(target, opts), swipe(direction | {from, to}, opts), \ pinch(direction | {scale, rotate, at}, opts), scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart, arguments, environment}), apps(). Also waitFor(selector, {timeout_ms}), \ readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \ -syslog(\"start\" | \"read\" | \"stop\" | \"status\", {process, pid, level, after, grep, max}) captures the phone's log as iph_syslog does and returns what it returns; a script cannot write a file. \ +syslog(\"start\" | \"read\" | \"stop\" | \"status\", {app, process, pid, level, after, grep, max}) captures the phone's log as iph_syslog does and returns what it returns; a script cannot write a file. \ tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \ A call that fails throws an Error with .code, .outcome, .hint and .result (the full result object); uncaught, it ends the script and the result says which call and line. \ After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \ @@ -175,11 +175,13 @@ fn tools() -> Vec { \"start\" (one capture at a time; stop an ended one before starting again) keeps the entries in a buffer in memory, newest last, each with a seq; \ \"read\" returns the entries newer than `after` (the `cursor` of the previous read) without stopping the capture, \ so the loop is start, tap, read, tap, read, stop; \"stop\" ends it (with grep or max it returns the latest matching entries); \"status\". \ - Filter with process (executable names such as Preferences; survives app restarts) or pid; unfiltered over Wi-Fi it is thousands of entries a second, \ - and the buffer keeps the last 100,000. A read says how many entries were `dropped` before it could get them.", + Filter with app (bundle id or name, as iph_launch takes it; matched by where the app is installed, so it survives restarts and includes its extensions), \ + process (executable names such as Preferences; survives app restarts) or pid; an entry is kept if it is from any listed app or process; unfiltered over Wi-Fi it is thousands of entries a second, \ + and the buffer keeps the last 100,000 entries by default. A read says how many entries were `dropped` before it could get them.", json!({ "action": { "type": "string", "enum": ["start", "read", "stop", "status"] }, - "process": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these executables." }, + "app": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these apps' entries, each a bundle id or an app name; an unknown app fails before anything starts." }, + "process": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these executables. With app, an entry is kept if it matches either." }, "pid": { "type": "integer", "description": "start: keep only this pid (filtered on the phone)." }, "level": { "type": "string", "enum": ["debug", "info", "notice", "error", "fault"], "description": "start: lowest level kept." }, "buffer_entries": { "type": "integer", "description": "start: most entries the buffer holds, 1 to 1000000 (default 100000); the oldest are dropped." }, @@ -400,9 +402,10 @@ mod tests { let tool = tools().into_iter().find(|t| t["name"] == "iph_syslog").unwrap(); let props = tool["inputSchema"]["properties"].as_object().unwrap(); assert_eq!(props["action"]["enum"], json!(["start", "read", "stop", "status"])); - for key in ["after", "grep", "max", "output", "max_mb", "buffer_entries", "buffer_mb", "process", "pid", "level"] { + for key in ["after", "grep", "max", "output", "max_mb", "buffer_entries", "buffer_mb", "app", "process", "pid", "level"] { assert!(props.contains_key(key), "missing {key}"); } + assert_eq!(props["app"]["items"]["type"], "string"); assert_eq!(tool["inputSchema"]["required"], json!(["action"])); } diff --git a/src/syslog.rs b/src/syslog.rs index 2ef876a..eecf6f3 100644 --- a/src/syslog.rs +++ b/src/syslog.rs @@ -22,6 +22,7 @@ use std::{ use idevice::{ IdeviceError, + core_device::AppListEntry, os_trace_relay::{LogLevel, OsTraceLog, OsTraceRelayReceiver}, }; use regex::Regex; @@ -29,7 +30,7 @@ use serde_json::{Map, Value, json}; use crate::{ clock, - device::session::Session, + device::session::{Session, plain_path}, fields, paths, reply::{Fail, Res}, tcp::handle::Reset, @@ -132,23 +133,30 @@ fn file_name(path: &str) -> &str { impl From for Entry { fn from(log: OsTraceLog) -> Self { - let (subsystem, category) = match log.label { - Some(l) => (Some(l.subsystem), Some(l.category)), - None => (None, None), - }; - Self { - time: utc_micros(log.timestamp.and_utc().timestamp(), log.timestamp.and_utc().timestamp_subsec_nanos()), - pid: log.pid, - process: file_name(&log.filename).to_string(), - sender: file_name(&log.image_name).to_string(), - level: log.level.into(), - subsystem, - category, - message: log.message, - } + entry_and_executable(log).0 } } +/// The entry, and the path of the executable that logged it, which is only +/// for the filter: the buffer keeps the file name alone. +fn entry_and_executable(log: OsTraceLog) -> (Entry, String) { + let (subsystem, category) = match log.label { + Some(l) => (Some(l.subsystem), Some(l.category)), + None => (None, None), + }; + let entry = Entry { + time: utc_micros(log.timestamp.and_utc().timestamp(), log.timestamp.and_utc().timestamp_subsec_nanos()), + pid: log.pid, + process: file_name(&log.filename).to_string(), + sender: file_name(&log.image_name).to_string(), + level: log.level.into(), + subsystem, + category, + message: log.message, + }; + (entry, log.filename) +} + impl Entry { /// The entry as a reply or the file shows it. A message longer than /// `max_chars` is cut and marked with `message_cut`. @@ -197,17 +205,56 @@ impl Entry { } } +/// An installed app, by where it lives on the phone. +#[derive(Debug, Clone, PartialEq)] +pub struct AppBundle { + pub bundle_id: String, + /// The bundle directory (`.../Papago.app`), as `plain_path` spells it. + pub path: String, +} + +impl AppBundle { + /// `None` when the phone gave no absolute path to match against. + pub fn new(bundle_id: &str, path: &str) -> Option { + let path = plain_path(path); + path.starts_with('/').then(|| Self { bundle_id: bundle_id.to_string(), path }) + } + + /// Whether `executable` (already `plain_path`ed) lies in the bundle: the + /// app's own executable and its extensions, not a path that only starts + /// with the same letters. + fn contains(&self, executable: &str) -> bool { + executable.strip_prefix(self.path.as_str()).is_some_and(|rest| rest.starts_with('/')) + } +} + +/// The app in `apps` with this bundle id. +fn find_bundle(apps: &[AppListEntry], bundle_id: &str) -> Option { + apps.iter().find(|a| a.bundle_identifier == bundle_id).and_then(|a| AppBundle::new(bundle_id, &a.path)) +} + /// What is kept on this side. A pid is filtered by the phone instead. +/// +/// With neither `processes` nor `apps` every entry passes. With either, an +/// entry passes when it is from any listed process or any listed app; +/// `min_level` then applies on top of that. #[derive(Debug, Clone, Default, PartialEq)] pub struct Filter { pub processes: Vec, + pub apps: Vec, pub min_level: Option, } impl Filter { - pub fn keeps(&self, e: &Entry) -> bool { - (self.processes.is_empty() || self.processes.contains(&e.process)) - && self.min_level.is_none_or(|min| e.level >= min) + /// `executable` is the logging process's path as the phone gave it. + pub fn keeps(&self, e: &Entry, executable: &str) -> bool { + let selected = (self.processes.is_empty() && self.apps.is_empty()) + || self.processes.contains(&e.process) + || (!self.apps.is_empty() && { + let executable = plain_path(executable); + self.apps.iter().any(|app| app.contains(&executable)) + }); + selected && self.min_level.is_none_or(|min| e.level >= min) } } @@ -225,7 +272,10 @@ pub struct FileSpec { #[derive(Debug, Clone, PartialEq)] pub struct Spec { - pub filter: Filter, + pub processes: Vec, + /// As given: a bundle id or a name, resolved when the capture starts. + pub apps: Vec, + pub min_level: Option, pub pid: Option, pub limits: Limits, /// Only when `output` is given: nothing is written to disk otherwise. @@ -261,7 +311,7 @@ pub fn parse(args: &Value) -> Res { .and_then(|v| v.as_str()) .ok_or_else(|| Fail::invalid("syslog needs an action: start, read, stop or status"))?; let allowed: &[&str] = match action { - "start" => &["action", "process", "pid", "level", "output", "max_mb", "buffer_entries", "buffer_mb"], + "start" => &["action", "process", "app", "pid", "level", "output", "max_mb", "buffer_entries", "buffer_mb"], "read" => &["action", "after", "grep", "max"], "stop" => &["action", "grep", "max"], "status" => &["action"], @@ -284,6 +334,18 @@ pub fn parse(args: &Value) -> Res { Err(Fail::invalid(format!("`{key}` takes a whole number from 1 to {most}"))) } }; + let names = |key: &str| -> Res> { + match given.get(key) { + None => Ok(Vec::new()), + Some(Value::String(s)) => Ok(vec![s.clone()]), + Some(Value::Array(a)) => a + .iter() + .map(|v| v.as_str().map(String::from)) + .collect::>>() + .ok_or_else(|| Fail::invalid(format!("`{key}` takes names"))), + Some(_) => Err(Fail::invalid(format!("`{key}` takes a name or a list of names"))), + } + }; let grep = || -> Res> { match given.get("grep") { None => Ok(None), @@ -295,19 +357,14 @@ pub fn parse(args: &Value) -> Res { }; match action { "start" => { - let processes = match given.get("process") { - None => Vec::new(), - Some(Value::String(s)) => vec![s.clone()], - Some(Value::Array(a)) => a - .iter() - .map(|v| v.as_str().map(String::from)) - .collect::>>() - .ok_or_else(|| Fail::invalid("`process` takes names"))?, - Some(_) => return Err(Fail::invalid("`process` takes a name or a list of names")), - }; + let processes = names("process")?; if processes.iter().any(|p| p.is_empty() || p.contains('/')) { return Err(Fail::invalid("`process` takes executable names such as Preferences, not paths")); } + let apps = names("app")?; + if apps.iter().any(|a| a.trim().is_empty()) { + return Err(Fail::invalid("`app` takes a bundle id or an app's name, as `iph launch` does")); + } let min_level = match given.get("level") { None => None, Some(v) => Some(v.as_str().and_then(Level::parse).ok_or_else(|| { @@ -342,7 +399,7 @@ pub fn parse(args: &Value) -> Res { Some(FileSpec { path, max_bytes }) } }; - Ok(Request::Start(Spec { filter: Filter { processes, min_level }, pid, limits, file })) + Ok(Request::Start(Spec { processes, apps, min_level, pid, limits, file })) } "read" => { let max = number("max")?.unwrap_or(DEFAULT_MATCHES); @@ -613,12 +670,12 @@ impl Live { Self { ring, sink, filter, seen: 0, kept: 0, unparsed: 0, ended: None } } - pub fn take(&mut self, entry: Entry) -> std::io::Result<()> { + pub fn take(&mut self, entry: Entry, executable: &str) -> std::io::Result<()> { if self.ended.is_some() { return Ok(()); } self.seen += 1; - if !self.filter.keeps(&entry) { + if !self.filter.keeps(&entry, executable) { return Ok(()); } let line = self.sink.is_some().then(|| entry.line(self.ring.next_seq)); @@ -728,10 +785,13 @@ async fn pump(mut stream: OsTraceRelayReceiver, live: Arc>) { // Never under a timeout: an entry is several reads, and giving up // between them would leave the stream mid-entry. let reason = match stream.next().await { - Ok(log) => match live.lock().unwrap().take(Entry::from(log)) { - Ok(()) => continue, - Err(e) => format!("cannot write the file: {e}"), - }, + Ok(log) => { + let (entry, executable) = entry_and_executable(log); + match live.lock().unwrap().take(entry, &executable) { + Ok(()) => continue, + Err(e) => format!("cannot write the file: {e}"), + } + } Err(e) if skippable(&e) => { live.lock().unwrap().unparsed += 1; continue; @@ -745,6 +805,8 @@ async fn pump(mut stream: OsTraceRelayReceiver, live: Arc>) { pub struct Capture { spec: Spec, + /// `spec`'s apps resolved to where they live. + filter: Filter, started_at: String, started: std::time::Instant, live: Arc>, @@ -815,13 +877,16 @@ impl Capture { let live = self.live.lock().unwrap(); let mut out = live.counts(); out.insert("started_at".into(), json!(self.started_at)); - if !self.spec.filter.processes.is_empty() { - out.insert("process".into(), json!(self.spec.filter.processes)); + if !self.filter.processes.is_empty() { + out.insert("process".into(), json!(self.filter.processes)); + } + if !self.filter.apps.is_empty() { + out.insert("app".into(), json!(self.filter.apps.iter().map(|a| &a.bundle_id).collect::>())); } if let Some(pid) = self.spec.pid { out.insert("pid".into(), json!(pid)); } - if let Some(level) = self.spec.filter.min_level { + if let Some(level) = self.filter.min_level { out.insert("level".into(), json!(level.name())); } if let Some(file) = &self.spec.file { @@ -865,6 +930,9 @@ impl Session { ), )); } + // Before anything is created or opened: an unknown app is an error. + let apps = self.app_bundles(&spec.apps).await?; + let filter = Filter { processes: spec.processes.clone(), apps, min_level: spec.min_level }; // The file is opened only once the relay runs: a start that // fails leaves an earlier capture's file as it was. let (stream, reset) = self.os_trace(spec.pid).await?; @@ -875,15 +943,16 @@ impl Session { Sink::create(&f.path, f.max_bytes).map_err(|e| Fail::invalid(format!("{}: {e}", f.path.display()))) }) .transpose()?; - let mut live = Live::new(Ring::new(spec.limits), sink, spec.filter.clone()); + let mut live = Live::new(Ring::new(spec.limits), sink, filter.clone()); let started_at = clock::now_utc(); let start = json!({ "event": "start", "time": started_at, "udid": udid, - "process": spec.filter.processes, + "process": filter.processes, + "app": filter.apps.iter().map(|a| &a.bundle_id).collect::>(), "pid": spec.pid, - "level": spec.filter.min_level.map(Level::name), + "level": filter.min_level.map(Level::name), "max_mb": spec.file.as_ref().map(|f| f.max_bytes / (1024 * 1024)), }); if let Err(e) = live.note(&start) { @@ -894,7 +963,7 @@ impl Session { let task = tokio::task::spawn_local(pump(stream, live.clone())); let flusher = spec.file.is_some().then(|| tokio::task::spawn_local(flusher(Arc::downgrade(&live)))); let started = std::time::Instant::now(); - let capture = Capture { spec, started_at, started, live, task, flusher, reset }; + let capture = Capture { spec, filter, started_at, started, live, task, flusher, reset }; let report = capture.report(); self.capture = Some(capture); Ok(report) @@ -916,6 +985,30 @@ impl Session { } } + /// Each app, named as `iph launch` takes it, with where it is installed. + async fn app_bundles(&mut self, apps: &[String]) -> Res> { + let mut found: Vec = Vec::new(); + for app in apps { + let bundle_id = self.resolve_bundle(app).await?; + if found.iter().any(|b| b.bundle_id == bundle_id) { + continue; + } + // The list is cached; an app installed since is not in it. + let mut bundle = find_bundle(&self.list_apps(false).await?, &bundle_id); + if bundle.is_none() { + bundle = find_bundle(&self.list_apps(true).await?, &bundle_id); + } + found.push(bundle.ok_or_else(|| { + Fail::not_sent("app_not_found", format!("no installed app has the bundle id {bundle_id}, or the phone gave no path for it")) + .hint(crate::i18n::t( + "`iph apps`로 이름과 bundle id를 확인하세요.", + "See names and bundle ids with `iph apps`.", + )) + })?); + } + Ok(found) + } + /// End the capture, keeping it for `status`, `read` and `stop`. pub fn end_capture(&mut self, reason: &str) { if let Some(c) = &self.capture { @@ -977,6 +1070,12 @@ mod tests { entry("Papago", Level::Info, message) } + /// Where an entry's process lives, as far as tests without apps care. + fn feed(live: &mut Live, e: Entry) { + let executable = format!("/usr/libexec/{}", e.process); + live.take(e, &executable).unwrap(); + } + fn roomy() -> Limits { Limits { entries: 1000, bytes: 1 << 20 } } @@ -1050,14 +1149,96 @@ mod tests { #[test] fn the_filter_keeps_named_processes_at_or_above_a_level() { let any = Filter::default(); - assert!(any.keeps(&entry("SpringBoard", Level::Debug, ""))); - let f = Filter { processes: vec!["Preferences".into(), "Papago".into()], min_level: Some(Level::Notice) }; - assert!(f.keeps(&entry("Preferences", Level::Notice, ""))); - assert!(f.keeps(&entry("Papago", Level::Fault, ""))); - assert!(!f.keeps(&entry("Preferences", Level::Info, ""))); - assert!(!f.keeps(&entry("SpringBoard", Level::Error, ""))); + assert!(any.keeps(&entry("SpringBoard", Level::Debug, ""), "/usr/libexec/SpringBoard")); + let f = Filter { processes: vec!["Preferences".into(), "Papago".into()], min_level: Some(Level::Notice), ..Filter::default() }; + let keeps = |e: Entry| f.keeps(&e, "/somewhere/else"); + assert!(keeps(entry("Preferences", Level::Notice, ""))); + assert!(keeps(entry("Papago", Level::Fault, ""))); + assert!(!keeps(entry("Preferences", Level::Info, ""))); + assert!(!keeps(entry("SpringBoard", Level::Error, ""))); // Exact names only: a prefix is another process. - assert!(!f.keeps(&entry("PreferencesExtension", Level::Error, ""))); + assert!(!keeps(entry("PreferencesExtension", Level::Error, ""))); + } + + fn papago() -> AppBundle { + AppBundle::new("com.naver.papago", "file:///private/var/containers/Bundle/Application/AAAA-1111/Papago.app/").unwrap() + } + + #[test] + fn an_app_is_matched_by_where_it_is_installed_whichever_way_the_prefix_is_spelled() { + let app = papago(); + assert_eq!(app.path, "/var/containers/Bundle/Application/AAAA-1111/Papago.app"); + let f = Filter { apps: vec![app], ..Filter::default() }; + let from = |executable: &str| f.keeps(¬e(""), executable); + assert!(from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago")); + assert!(from("/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago"), "without /private"); + assert!(from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/PlugIns/Share.appex/Share"), "an extension of the app"); + assert!(!from("/private/var/containers/Bundle/Application/BBBB-2222/Papago.app/Papago"), "the same name from another install"); + assert!(!from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.appex/Papago"), "a directory that only starts like the bundle"); + assert!(!from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app"), "the bundle directory itself is not an executable in it"); + assert!(!from("/usr/libexec/backboardd")); + assert!(!from("")); + // The same bundle given with a /var path, a URL, a trailing slash. + for spelling in [ + "/var/containers/Bundle/Application/AAAA-1111/Papago.app", + "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/", + "file:///var/containers/Bundle/Application/AAAA-1111/Papago.app/", + ] { + assert_eq!(AppBundle::new("com.naver.papago", spelling).unwrap(), papago(), "{spelling}"); + } + } + + #[test] + fn an_app_filter_follows_the_app_across_a_restart_and_matches_non_ascii_paths() { + let f = Filter { apps: vec![papago()], ..Filter::default() }; + let executable = "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago"; + for pid in [412, 977] { + let mut e = note(""); + e.pid = pid; + assert!(f.keeps(&e, executable), "pid {pid}"); + } + let notes = AppBundle::new("com.apple.mobilenotes", "file:///Applications/%EB%A9%94%EB%AA%A8.app/").unwrap(); + assert_eq!(notes.path, "/Applications/메모.app"); + let f = Filter { apps: vec![notes], ..Filter::default() }; + assert!(f.keeps(¬e(""), "/Applications/메모.app/메모")); + } + + #[test] + fn a_process_and_an_app_each_select_and_the_level_narrows_both() { + let f = Filter { processes: vec!["SpringBoard".into()], apps: vec![papago()], min_level: Some(Level::Notice) }; + let papago_exe = "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago"; + assert!(f.keeps(&entry("SpringBoard", Level::Notice, ""), "/usr/libexec/SpringBoard"), "a listed process"); + assert!(f.keeps(&entry("Papago", Level::Error, ""), papago_exe), "a listed app"); + assert!(!f.keeps(&entry("Papago", Level::Info, ""), papago_exe), "the level applies to the app"); + assert!(!f.keeps(&entry("SpringBoard", Level::Debug, ""), "/usr/libexec/SpringBoard"), "and to the process"); + assert!(!f.keeps(&entry("backboardd", Level::Fault, ""), "/usr/libexec/backboardd"), "neither listed"); + // A process named like the app's executable is its own selector. + let only_process = Filter { processes: vec!["Papago".into()], ..Filter::default() }; + assert!(only_process.keeps(&entry("Papago", Level::Debug, ""), "/elsewhere/Papago")); + // An app listed alone does not let other processes through. + let only_app = Filter { apps: vec![papago()], ..Filter::default() }; + assert!(!only_app.keeps(&entry("Papago", Level::Debug, ""), "/elsewhere/Papago")); + } + + fn listed(bundle_id: &str, name: &str, path: &str) -> AppListEntry { + serde_json::from_value(json!({ + "isRemovable": true, "name": name, "isFirstParty": false, "path": path, "bundleIdentifier": bundle_id, + "isDeveloperApp": false, "isInternal": false, "isHidden": false, "isAppClip": false, + })) + .unwrap() + } + + #[test] + fn an_app_is_found_by_bundle_id_in_the_phones_list_and_needs_a_usable_path() { + let apps = vec![ + listed("com.apple.Preferences", "설정", "file:///Applications/Preferences.app/"), + listed("com.naver.papago", "Papago", "file:///private/var/containers/Bundle/Application/AAAA-1111/Papago.app/"), + listed("com.example.nopath", "No path", ""), + ]; + assert_eq!(find_bundle(&apps, "com.naver.papago"), Some(papago())); + assert_eq!(find_bundle(&apps, "com.apple.Preferences").unwrap().path, "/Applications/Preferences.app"); + assert_eq!(find_bundle(&apps, "com.example.missing"), None); + assert_eq!(find_bundle(&apps, "com.example.nopath"), None, "an empty path would match nothing useful"); } #[test] @@ -1254,6 +1435,37 @@ mod tests { assert_eq!((seqs(&c), c.cursor, c.more, c.dropped), (vec![12], 12, false, 0)); } + #[test] + fn paging_while_entries_are_evicted_returns_or_reports_every_seq_exactly_once() { + for (capacity, page_size, burst) in [(6, 3, 4), (5, 1, 2), (10, 4, 9), (3, 2, 5), (50, 7, 1)] { + let mut ring = Ring::new(Limits { entries: capacity, bytes: 1 << 20 }); + let (mut pushed, mut cursor, mut returned, mut dropped) = (0u64, 0u64, Vec::new(), 0u64); + for round in 0..40 { + for _ in 0..burst { + pushed += 1; + ring.push(note(&format!("m{pushed}"))); + } + // Read at an uneven pace: some rounds skip, so evictions pile up. + if round % 3 == 2 { + continue; + } + loop { + let page = ring.read(cursor, None, page_size); + dropped += page.dropped; + returned.extend(seqs(&page)); + assert!(page.cursor >= cursor, "the cursor never goes back"); + cursor = page.cursor; + if !page.more { + break; + } + } + assert_eq!(cursor, pushed, "a page that is not cut short has looked at everything"); + } + assert!(returned.windows(2).all(|w| w[0] < w[1]), "oldest first, never twice ({capacity}, {page_size}, {burst})"); + assert_eq!(returned.len() as u64 + dropped, pushed, "every seq was returned or counted as dropped ({capacity}, {page_size}, {burst})"); + } + } + #[test] fn latest_returns_the_most_recent_matches_oldest_first_with_the_total() { let mut ring = Ring::new(roomy()); @@ -1345,7 +1557,7 @@ mod tests { let path = dir.join("cap.jsonl"); let sink = Sink::create(&path, 1 << 20).unwrap(); let live = Arc::new(Mutex::new(Live::new(Ring::new(roomy()), Some(sink), Filter::default()))); - live.lock().unwrap().take(note("quiet")).unwrap(); + feed(&mut live.lock().unwrap(), note("quiet")); let runtime = tokio::runtime::Builder::new_current_thread().enable_time().start_paused(true).build().unwrap(); runtime.block_on(async { let task = tokio::spawn(flusher(Arc::downgrade(&live))); @@ -1361,13 +1573,13 @@ mod tests { fn a_capture_ends_with_one_end_line_and_keeps_nothing_after_it() { let dir = temp_dir("end"); let path = dir.join("cap.jsonl"); - let filter = Filter { processes: vec!["Papago".into()], min_level: None }; + let filter = Filter { processes: vec!["Papago".into()], ..Filter::default() }; let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), filter); - live.take(note("one")).unwrap(); - live.take(entry("SpringBoard", Level::Info, "other")).unwrap(); + feed(&mut live, note("one")); + feed(&mut live, entry("SpringBoard", Level::Info, "other")); live.end("the log stream ended: socket closed"); live.end("stopped"); - live.take(note("late")).unwrap(); + feed(&mut live, note("late")); let got = lines(&path); assert_eq!(got.len(), 2, "the end line is flushed without anyone asking"); assert_eq!((got[0]["seq"].as_u64(), got[0]["message"].as_str()), (Some(1), Some("one"))); @@ -1382,7 +1594,7 @@ mod tests { fn without_a_file_nothing_is_written_and_the_ring_alone_serves_reads() { let dir = temp_dir("memory"); let mut live = Live::new(Ring::new(roomy()), None, Filter::default()); - live.take(note("one")).unwrap(); + feed(&mut live, note("one")); live.note(&json!({ "event": "start" })).unwrap(); live.end("stopped"); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); @@ -1398,7 +1610,7 @@ mod tests { let path = dir.join("cap.jsonl"); let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), Filter::default()); for m in ["a", "b", "c"] { - live.take(note(m)).unwrap(); + feed(&mut live, note(m)); } live.end("stopped"); let in_file: Vec<(u64, String)> = lines(&path) @@ -1415,11 +1627,11 @@ mod tests { #[test] fn only_kept_entries_are_numbered_and_a_read_keeps_working_after_the_capture_ended() { - let filter = Filter { processes: vec!["Papago".into()], min_level: None }; + let filter = Filter { processes: vec!["Papago".into()], ..Filter::default() }; let mut live = Live::new(Ring::new(roomy()), None, filter); - live.take(note("one")).unwrap(); - live.take(entry("SpringBoard", Level::Info, "skipped")).unwrap(); - live.take(note("two")).unwrap(); + feed(&mut live, note("one")); + feed(&mut live, entry("SpringBoard", Level::Info, "skipped")); + feed(&mut live, note("two")); let q = Query { grep: None, max: 10 }; let running = live.read(0, &q); assert_eq!((running["state"].as_str(), running["cursor"].as_u64(), running["dropped"].as_u64()), (Some("running"), Some(2), Some(0))); @@ -1448,15 +1660,15 @@ mod tests { let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": "Preferences", "level": "default", "pid": null })) else { panic!("start") }; - assert_eq!(spec.filter.processes, ["Preferences"]); - assert_eq!(spec.filter.min_level, Some(Level::Notice)); - assert_eq!(spec.file, None); + assert_eq!(spec.processes, ["Preferences"]); + assert_eq!(spec.min_level, Some(Level::Notice)); + assert_eq!((spec.apps.len(), spec.file), (0, None)); assert_eq!(spec.limits, Limits { entries: 100_000, bytes: 64 * 1024 * 1024 }); let out = absolute("x.jsonl"); let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": out, "max_mb": 2 })) else { panic!("start with a file") }; - assert_eq!((spec.filter.processes.len(), spec.pid), (2, Some(7))); + assert_eq!((spec.processes.len(), spec.pid), (2, Some(7))); assert_eq!(spec.file, Some(FileSpec { path: out.clone(), max_bytes: 2 * 1024 * 1024 })); let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "output": out })) else { panic!("default size") }; assert_eq!(spec.file.unwrap().max_bytes, DEFAULT_MAX_MB * 1024 * 1024); @@ -1470,6 +1682,32 @@ mod tests { assert_eq!(spec.limits, Limits { entries: 500, bytes: 2 * 1024 * 1024 }); } + #[test] + fn an_app_is_a_name_or_a_list_of_names_for_start_only() { + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "app": "Papago", "process": "Preferences" })) else { + panic!("one app") + }; + assert_eq!((spec.apps, spec.processes), (strings(&["Papago"]), strings(&["Preferences"]))); + let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "app": ["com.naver.papago", "설정"] })) else { + panic!("two apps") + }; + assert_eq!(spec.apps, strings(&["com.naver.papago", "설정"])); + for bad in [ + json!({ "action": "start", "app": "" }), + json!({ "action": "start", "app": ["a", " "] }), + json!({ "action": "start", "app": 7 }), + json!({ "action": "start", "app": [1] }), + json!({ "action": "read", "app": "Papago" }), + json!({ "action": "stop", "app": "Papago" }), + ] { + assert_eq!(parsed(bad.clone()).expect_err(&bad.to_string()).code, "invalid_argument", "{bad}"); + } + } + + fn strings(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + #[test] fn read_and_stop_take_a_cursor_a_pattern_and_a_count() { let Ok(Request::Read { after, query }) = parsed(json!({ "action": "read" })) else { panic!("bare read") }; From aef82db92c3b1487565e6aacc0b5e75410d8300d Mon Sep 17 00:00:00 2001 From: Kofktu Date: Thu, 19 Nov 2026 21:16:48 +0900 Subject: [PATCH 7/7] fix: resolve `iph syslog --app` against a fresh app list The daemon caches the phone's app list, and `--app` read both the name and the bundle path from that cache, refreshing only when a bundle id was missing from it. Two cases slipped through: - An app reinstalled while the daemon runs (a rebuild from Xcode) moves to a new `/var/containers/Bundle/Application//`. Its bundle id is still in the cached list, so the old path was used, the capture started, and every entry was dropped (`kept: 0`). - An app installed since, named by display name, was looked up in the cached list and failed with `app_not_found` before the refresh. A start with `--app` now fetches the list once and resolves every name and every bundle path from that one snapshot. The name lookup moved out of `resolve_bundle` into `bundle_id_in`, which takes the list, so both `launch` (still on the cached list) and `syslog` share it. A start without `--app` does not fetch the list at all. Co-Authored-By: Claude Opus 5.5 --- src/actions.rs | 62 ++++++++++++++++++++++++++++---------------------- src/syslog.rs | 55 ++++++++++++++++++++++++++++---------------- 2 files changed, 71 insertions(+), 46 deletions(-) diff --git a/src/actions.rs b/src/actions.rs index fa425b5..ce53790 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -479,6 +479,39 @@ fn app_changed(before: &Screen, after: &Screen) -> Option { (!was.contains(&now.pid)).then(|| json!({ "name": now.name, "pid": now.pid })) } +/// Something with a dot and no spaces is a bundle id; anything else is a name. +fn is_bundle_id(app: &str) -> bool { + app.contains('.') && !app.contains(' ') +} + +/// The bundle id `app` names, looked up by name in `apps` unless it is one already. +pub(crate) fn bundle_id_in(apps: &[idevice::core_device::AppListEntry], app: &str) -> Res { + if is_bundle_id(app) { + return Ok(app.to_string()); + } + let want = nfc(app).to_lowercase(); + let hits: Vec<&idevice::core_device::AppListEntry> = apps + .iter() + .filter(|a| nfc(&a.name).to_lowercase() == want) + .collect(); + match hits.len() { + 1 => Ok(hits[0].bundle_identifier.clone()), + 0 => Err(Fail::not_sent("app_not_found", format!("no installed app is named \"{app}\"")) + .hint(t( + "`iph apps`로 이름과 bundle id를 확인하세요.", + "See names and bundle ids with `iph apps`.", + ))), + _ => Err(Fail::not_sent( + "ambiguous_app", + format!("{} apps are named \"{app}\"", hits.len()), + ) + .with( + "candidates", + Value::Array(hits.iter().map(|a| json!(a.bundle_identifier)).collect()), + )), + } +} + impl Session { fn build_opts(all: bool, raw: bool) -> BuildOptions { BuildOptions { include_offscreen: all, raw } @@ -1199,33 +1232,8 @@ impl Session { } pub(crate) async fn resolve_bundle(&mut self, app: &str) -> Res { - // Something with a dot and no spaces is a bundle id; anything else is - // looked up by name. - if app.contains('.') && !app.contains(' ') { - return Ok(app.to_string()); - } - let want = nfc(app).to_lowercase(); - let apps = self.list_apps(false).await?; - let hits: Vec<&idevice::core_device::AppListEntry> = apps - .iter() - .filter(|a| nfc(&a.name).to_lowercase() == want) - .collect(); - match hits.len() { - 1 => Ok(hits[0].bundle_identifier.clone()), - 0 => Err(Fail::not_sent("app_not_found", format!("no installed app is named \"{app}\"")) - .hint(t( - "`iph apps`로 이름과 bundle id를 확인하세요.", - "See names and bundle ids with `iph apps`.", - ))), - _ => Err(Fail::not_sent( - "ambiguous_app", - format!("{} apps are named \"{app}\"", hits.len()), - ) - .with( - "candidates", - Value::Array(hits.iter().map(|a| json!(a.bundle_identifier)).collect()), - )), - } + let apps = if is_bundle_id(app) { Vec::new() } else { self.list_apps(false).await? }; + bundle_id_in(&apps, app) } pub async fn cmd_launch(&mut self, args: LaunchArgs) -> Res { diff --git a/src/syslog.rs b/src/syslog.rs index eecf6f3..0e8b2fb 100644 --- a/src/syslog.rs +++ b/src/syslog.rs @@ -233,6 +233,24 @@ fn find_bundle(apps: &[AppListEntry], bundle_id: &str) -> Option { apps.iter().find(|a| a.bundle_identifier == bundle_id).and_then(|a| AppBundle::new(bundle_id, &a.path)) } +fn bundles_in(listed: &[AppListEntry], apps: &[String]) -> Res> { + let mut found: Vec = Vec::new(); + for app in apps { + let bundle_id = crate::actions::bundle_id_in(listed, app)?; + if found.iter().any(|b| b.bundle_id == bundle_id) { + continue; + } + found.push(find_bundle(listed, &bundle_id).ok_or_else(|| { + Fail::not_sent("app_not_found", format!("no installed app has the bundle id {bundle_id}, or the phone gave no path for it")) + .hint(crate::i18n::t( + "`iph apps`로 이름과 bundle id를 확인하세요.", + "See names and bundle ids with `iph apps`.", + )) + })?); + } + Ok(found) +} + /// What is kept on this side. A pid is filtered by the phone instead. /// /// With neither `processes` nor `apps` every entry passes. With either, an @@ -987,26 +1005,12 @@ impl Session { /// Each app, named as `iph launch` takes it, with where it is installed. async fn app_bundles(&mut self, apps: &[String]) -> Res> { - let mut found: Vec = Vec::new(); - for app in apps { - let bundle_id = self.resolve_bundle(app).await?; - if found.iter().any(|b| b.bundle_id == bundle_id) { - continue; - } - // The list is cached; an app installed since is not in it. - let mut bundle = find_bundle(&self.list_apps(false).await?, &bundle_id); - if bundle.is_none() { - bundle = find_bundle(&self.list_apps(true).await?, &bundle_id); - } - found.push(bundle.ok_or_else(|| { - Fail::not_sent("app_not_found", format!("no installed app has the bundle id {bundle_id}, or the phone gave no path for it")) - .hint(crate::i18n::t( - "`iph apps`로 이름과 bundle id를 확인하세요.", - "See names and bundle ids with `iph apps`.", - )) - })?); + if apps.is_empty() { + return Ok(Vec::new()); } - Ok(found) + // Not the cached list: a reinstall moves an app to a new container, + // and its old path would match no entry at all. + bundles_in(&self.list_apps(true).await?, apps) } /// End the capture, keeping it for `status`, `read` and `stop`. @@ -1241,6 +1245,19 @@ mod tests { assert_eq!(find_bundle(&apps, "com.example.nopath"), None, "an empty path would match nothing useful"); } + #[test] + fn apps_named_either_way_resolve_to_one_bundle_from_the_same_list() { + let reinstalled = vec![ + listed("com.apple.Preferences", "설정", "file:///Applications/Preferences.app/"), + listed("com.naver.papago", "Papago", "file:///private/var/containers/Bundle/Application/BBBB-2222/Papago.app/"), + ]; + let bundles = bundles_in(&reinstalled, &["Papago".into(), "com.naver.papago".into()]).unwrap(); + assert_eq!(bundles.len(), 1); + assert_eq!(bundles[0].path, "/var/containers/Bundle/Application/BBBB-2222/Papago.app"); + assert_eq!(bundles_in(&reinstalled, &["Unknown".into()]).unwrap_err().code, "app_not_found"); + assert_eq!(bundles_in(&reinstalled, &["com.example.missing".into()]).unwrap_err().code, "app_not_found"); + } + #[test] fn only_an_entry_the_library_could_not_parse_is_skipped() { let unparsed = IdeviceError::UnexpectedResponse("unknown log level byte value".into());