Skip to content

feat: capture the phone's log to a file with iph syslog - #9

Merged
HyunSeob merged 7 commits into
HyunSeob:mainfrom
Kofktu:feat/syslog
Nov 19, 2026
Merged

HyunSeob merged 7 commits into
HyunSeob:mainfrom
Kofktu:feat/syslog

Conversation

@Kofktu

@Kofktu Kofktu commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Why

To check what an app logged after a tap, a real-device test needs the phone's log while the test keeps running. Today the only route is log collect --device-udid on macOS, which requires root. The pinned idevice 0.1.68 reads the structured log through RSD (com.apple.os_trace_relay.shim.remote), so the daemon now captures it in the background.

What changed

  • iph syslog start|read|status|stop, also as MCP iph_syslog and script syslog(action, opts). The daemon's session holds one capture. A background task reads the stream without taking the session lock, so taps, reads and scripts keep working.
  • Entries go into a bounded ring buffer (100,000 entries or 64 MiB by default). read [--after SEQ] [--grep RE] [--max N] returns newer entries with a cursor, more and dropped, without stopping the capture. stop --grep reads the same buffer. -o <file> with --max-mb rotation is opt-in.
  • Filters: --app <bundle id | name> (inside the app's bundle, survives restarts), --process NAME, --pid N (filtered on the phone) and --level.
  • A capture closes its connection with a TCP reset instead of a FIN. After a FIN the phone's log relay kept writing to the closed connection and served no new capture for about 30 s. StreamHandle::reset_on_drop() in src/tcp makes a stream send exactly one RST, early or on drop, and never a FIN.
  • Entry times are corrected: idevice 0.1.68 puts the phone's microseconds where chrono expects nanoseconds.

Scope

  • Pulling a log archive and a script function that waits for a log line are left for follow-ups.
  • When the tunnel drops, the capture ends and records the reason. It does not reconnect on its own, so a gap is never hidden. An ended capture can be read until stop.
  • Batch is left out, because a capture outlives the call that started it. A capture started by a script also outlives the script.
  • No version bump.

Blast Radius

Enabling idevice's syslog_relay feature adds chrono, num-traits and autocfg to Cargo.lock. The src/tcp change adds an opt-in reset on drop; other connections still close with a FIN. Nothing new runs unless syslog is used.

Verification

  • cargo test --locked: 230 passed, including tests for the reset on drop (one RST, no FIN), the ring buffer cursor and eviction, --app path matching (/private/var against /var), rotating twice over an existing .1, and --human. Clippy: no new warning.
  • On an iPhone17,1 with iOS 27.2.1 over Wi-Fi, from macOS:
    • --app com.apple.Preferences kept only Settings entries, and a second read --after <cursor> returned only newer ones. --app com.naver.papago kept entries from two pids across a restart.
    • Paging with --max 3 returned the same 47 entries as one unbounded read, with no repeat and no gap.
    • Stop then start, 5 times, and iph stop then start, 3 times: entries arrived within 0.1 s each time. After a forced script timeout that drops the tunnel, the next capture recovered in 0.1 to 0.4 s (30 s with a FIN).
    • -o lines landed within one flush, the end line was present after stop and after iph stop, and --max-mb 1 rotated 14 times with both files parsing.
    • Tap latency did not change with an unfiltered capture (medians 10.0 s without, 10.1 s with, 9.7 s with --pid, 13 taps). Unfiltered volume does slow screen reads over Wi-Fi (1.0 s to 2.3 s at about 9,000 entries/s), so the README recommends --pid there.

🤖 Generated with Claude Code

@HyunSeob

Copy link
Copy Markdown
Owner

Thanks for this PR and for the thorough real-device verification! The src/tcp Aborter (TCP RST) fix for the ~30 s os_trace_relay stall after FIN is a great find, and we definitely want to keep that part.

Before merging, we'd like to align on a few design points so iph syslog fits agent and script workflows as cleanly as possible:

1. In-memory ring buffer + live read by default (optional -o <file>)

Right now, every capture writes continuously to a JSONL file (rotating at 64 MB) and requires stop (which re-parses up to 128 MB of JSONL synchronously on the daemon's single-threaded LocalSet) before entries can be inspected.

For AI agents and multi-step scripts, the common loop is:
start → tap → inspect new logs → tap → inspect new logs → stop

Could we make a bounded in-memory ring buffer (e.g., capped by entry count / byte budget, with a monotonic seq per kept entry) the default backing store, and include read in this PR?

  • iph syslog read [--after <seq>] [--grep RE] [--max N] (and syslog("read", ...) / iph_syslog) returns new matching entries since after without stopping the capture, plus the latest seq cursor.
  • stop [--grep RE] [--max N] can still return matching entries from the buffer without re-parsing files from disk.
  • -o <file> (with --max-mb rotation) can remain as an opt-in flag when someone explicitly wants a persistent JSONL dump on disk.

2. Support --app <bundle id | name> filtering

Across iph, users and agents refer to apps by bundle ID or display name (iph launch, iph apps) rather than internal executable names like Preferences. Since Session::list_apps already provides each app's .app bundle path and OsTraceLog.filename starts with that bundle path (normalizable with plain_path), supporting --app alongside --process and --pid would make common usage much smoother while still surviving app restarts.

3. Small implementation details to tighten up

  • Windows file rotation (if -o rotation is kept): Sink::write calls std::fs::rename(&self.path, rotated(&self.path)) while self.file is still open. On Windows, renaming an open file handle (or renaming over an existing .1 file) fails, so we should drop the handle and remove any existing .1 before renaming. We just added a macOS + Windows cargo test --locked CI workflow (.github/workflows/ci.yml) on main, so once rebased, CI will automatically verify the rotation unit test on Windows without needing a local Windows machine.
  • File I/O & max_mb safety: When writing to -o, wrapping the file in a BufWriter (flushed periodically and on end/stop) avoids an unbuffered write per log line, and using checked_mul (or an upper bound) for max_mb * 1024 * 1024 avoids integer overflow.
  • --human output: Please add a syslog case in src/human.rs so status, read, and stop --grep display counts and matched entries cleanly with --human.
  • Rebase on main: feat: pass launch arguments and environment variables to the app #8 and feat: add iph pinch for two-finger pinch and rotate #10 have just been merged, so this will need a rebase onto the latest main.

How does this direction sound to you? If you'd prefer to land the src/tcp Aborter commit as a small standalone PR first or iterate directly on this branch, either works great for us—happy to discuss any tradeoffs!

Kofktu and others added 6 commits November 19, 2026 17:08
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 <[email protected]>
`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
`<file>.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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <file>`
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 <[email protected]>
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 <bundle id | name>` 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 <[email protected]>
@Kofktu

Kofktu commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. I agreed with all of it and kept iterating on this branch, rebased onto the latest main so the new CI runs. The earlier commits stay as they were; the review changes are new commits on top, except the RST commit, which changed shape (below).

1. Memory buffer and read. A capture now keeps entries in a bounded ring buffer (100,000 entries or 64 MiB by default, adjustable with --buffer-entries / --buffer-mb), and each kept entry gets a seq. iph syslog read [--after SEQ] [--grep RE] [--max N] (also syslog("read") and iph_syslog) returns newer entries without stopping the capture, with a cursor for the next call, more when another page is waiting, and dropped when entries were evicted before they were read. stop --grep reads the buffer, so the file re-parsing is gone. -o <file> with --max-mb rotation is now opt-in.

2. --app. --app <bundle id | name> resolves the app the same way launch does and keeps entries whose executable path is inside that bundle, so it survives restarts. It combines with --process as "either matches", and --level applies on top.

3. Details.

  • Rotation flushes and drops the handle, removes an existing .1, then renames. The test rotates twice, so the Windows CI covers renaming over .1.
  • The file is behind a BufWriter, flushed every 250 ms and on end/stop.
  • --max-mb is limited to 1..4096 and computed with checked_mul.
  • src/human.rs has a syslog case for status, read and stop.

About the RST. A review pass found that the relay could still be closed with a FIN: when a start failed after connecting, when a capture ended on its own, and when a tunnel reset dropped everything before the separate Aborter message went out. A reset aimed at a saved port could also hit a later connection that reused it. So the reset is now part of the stream: StreamHandle::reset_on_drop() marks it before idevice takes it, and it sends exactly one RST, either early through the returned handle (a capture ends with it before the tunnel can go) or on drop, and never a FIN. The behaviour you wanted to keep is the same, and it is still its own commit.

The new CI passes on macOS and Windows, including the rotation test that renames over an existing .1. Checked on an iPhone 16 Pro over Wi-Fi: --app, gap-free paging with read --after, stop/start and a forced tunnel drop recovering within 0.4 s, -o with rotation, and --human. I also re-measured the cost to other commands and replaced the README line: taps did not slow down with an unfiltered capture, but at about 9,000 entries/s screen reads went from 1.0 s to 2.3 s over Wi-Fi, so the README now recommends --pid there. I updated the PR description to match.

Separately, the slow taps I saw while measuring (about 8 to 10 s instead of about 3 s) each waited on one screen reading the phone never answered, which iph asks again after 6.5 s. That happens on main without a capture too, so it is not part of this PR; I can open an issue with the trace if that helps.

I kept it as one PR, since the RST change has no caller without syslog, but I'm happy to split it out if you prefer.

@HyunSeob

Copy link
Copy Markdown
Owner

Thanks for the awesome follow-up! The ring buffer + read --after loop, --app filtering, Windows-safe rotation, --human output, and the reset_on_drop redesign all look super clean—and it's great to see both macOS and Windows CI passing.

Keeping it all in this single PR is totally fine by us, and yes, opening a separate issue with the trace for that 6.5 s AX timeout on main would be very helpful!

Before we merge, we caught one practical edge case with --app:

  • Stale cached app list in Session::app_bundles:
    • When an app is rebuilt/reinstalled (e.g., from Xcode) while the daemon is still running, iOS assigns a new container UUID under /var/containers/Bundle/Application/<UUID>/.... Because list_apps(false) still finds the bundle ID in the cached list, app_bundles never refreshes—so iph syslog start --app <bundle id> succeeds, but matches against the old path and silently drops all logs (kept: 0).
    • Similarly, if a newly installed app is passed by display name, resolve_bundle checks the cached list via list_apps(false) and returns app_not_found before reaching the refresh fallback in app_bundles.
    • Fix: when spec.apps is non-empty, refreshing the app list once up front (list_apps(true)) and resolving both display names and bundle paths from that fresh snapshot should cover both reinstalls and newly installed apps cleanly.

Once that's in, this is ready to merge!

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/<UUID>/`. 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 <[email protected]>
@Kofktu

Kofktu commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, good catch. Fixed in a new commit on top.

A start with --app now refreshes the app list once (list_apps(true)) and resolves every name and every bundle path from that one snapshot, so a reinstall's new container path and a newly installed app's display name are both picked up. A start without --app doesn't fetch the list at all. To share the name lookup, I moved it out of resolve_bundle into bundle_id_in, which takes the list. launch still resolves names from the cached list as before. A unit test checks that a name and a bundle id resolve to one bundle at the reinstalled path, and that an unknown app is still app_not_found.

I'll open the issue for the 6.5 s AX timeout separately.

@HyunSeob HyunSeob left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean fix — thanks again for the thoughtful iteration, thorough tests, and real-device verification! Looking forward to the 6.5 s AX timeout issue as well. Merging now!

@HyunSeob
HyunSeob merged commit 09bb5cc into HyunSeob:main Nov 19, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants