Skip to content

v0.6.0

Latest

Choose a tag to compare

@raulvidis raulvidis released this 02 Dec 13:17

[0.6.0] - 2026-12-02

Added

  • GET /battery — battery percentage and charge state straight from BatteryManager (getIntProperty(BATTERY_PROPERTY_CAPACITY), API 21; isCharging(), API 23) instead of scraping the status-bar accessibility node, which mis-reads across OEM skins and device languages. Neither value depends on the accessibility service running, and at minSdk 26 neither needs a version gate. Fixed response shape — batteryPercentage and charging, both always present — because the HTTP and relay transports serialise nulls differently (#103).
  • JVM unit coverage for previously untested bridge classes: EventStore (ring-buffer eviction and orientation, newest-first ordering, the since cursor, streaming-flag semantics, concurrent add/read), BatteryMonitor (an unreadable, out-of-range or throwing battery service must read as null — never a guessed number), ScreenRecorder (precondition ordering, single-use projection-token handling, the 30 s duration cap, temp-file cleanup, serialised handler-thread state machine), BridgeNotificationListener (instance publication on connect/disconnect, the 300-entry cap, parse-or-drop on post, mark-not-delete on remove) and ScreenNode/NodeBounds.computeHash. 117 tests.
  • Three latent defects surfaced by that coverage, each fixed below — the @Ignore("BUG: ...") is lifted on every demonstration test, so the test that first reproduced a defect is now its regression test:
    • EventStore.add() calls removeLast() on an empty deque when maxCapacity <= 0, so the first event after such an assignment throws NoSuchElementException out of onAccessibilityEvent instead of being dropped. Not reachable today (nothing in the app writes maxCapacity), but the knob is public.
    • ScreenRecorder.record() never releases the MediaRecorder when its configuration or prepare() throws: recorder = mr is assigned only after the apply {} block returns, so cleanupRecording() in the catch sees a null field and the native recorder (encoder + projection client) leaks. Reachable whenever prepare() fails — codec unavailable, storage full, invalid surface.
    • computeHash() joins fields with | without escaping the separator, so field content containing | shifts the layout and two genuinely different nodes hash identically — a hole in the value /screen_diff uses to decide nothing changed. Fixing it changes every hash; see Fixed below for the one-time upgrade impact.
  • ScreenRecorder gained an internal maxDurationMs testability seam (default unchanged at 30 s), same pattern as CommandDispatcher.batteryContext: the cap is otherwise only observable by waiting out a full capped recording.

Changed

  • ActionExecutor and CommandDispatcher are split into domain units — no behaviour change. The two files every bridge action and every endpoint passed through had grown to 1131 and 621 lines, which made them the hardest things in the repo to review and the easiest place for a fix to land somewhere unintended. ActionExecutor is now a 135-line facade whose every public action delegates, with the implementations in focused internal objects in the same package: GestureExecutor (tap/tapText/swipe/scroll/longPress/drag/pinch), NodeLookup (the stable-node-ID lookup and its recycling contract), TextEntryExecutor, SystemKeyExecutor, ScreenshotExecutor, AppIntentExecutor (which keeps both safety denylists in one file for security review), DeviceServicesExecutor (including the whole SMS send-report plumbing), ScreenQueryExecutor (including describeNode's PII-1 boundary) and TtsExecutor. CommandDispatcher keeps what made it the single source of truth — the error contract, the batteryContext/smsSender test seams, the RES-1 clamps and the complete 40-entry (method, path) routing table — with only /ping and the 404 arm still carrying behaviour inline; the other 39 arms delegate to ScreenCommands, InputCommands, AppIntentCommands, DeviceCommands, NotificationCommands and MediaCommands.
    Public signatures are unchanged including their default values, and no route, JSON field, status code, error message, permission gate, PII rule or notification-gating decision moved. The seams stay reachable at the names their tests already use: smsSendReportTimeoutMs and smsSentReportAction keep delegating members on ActionExecutor while their storage sits beside the send they bound. 68 characterization tests were added first and pass unchanged across every step (464 → 532), and each of the sixteen extraction commits was verified as a pure move by a normalised member-body diff against the pre-split tree: all 60 executor members, 29 of 30 dispatcher members (the 30th being route() itself) and all 40 route-arm bodies hash identically once five enumerated, purely mechanical rewrites are applied — a sibling-object qualifier, a moved member losing private, a handler's trailing expression gaining return, and the two seam accessors.
  • The relay URL scheme you type is the scheme the app dials — and android_setup now prints one. RelayUrl maps https:///wss:// → wss:// and everything else, including a bare relay.example.com or 203.0.113.7:8766, → ws://: the behaviour every stored URL already relies on. An intermediate rule on this branch defaulted a bare public host to wss://, and it is reverted here because the relay only terminates TLS when ANDROID_RELAY_CERT/ANDROID_RELAY_KEY are set while android_setup told the user to type a bare public_ip:port — so the documented setup, and every bare URL already in prefs, failed the TLS handshake against a plaintext listener. The phone cannot know whether the operator configured a certificate; the operator can, so android_setup now prints wss://ip:port when the relay has one and ws://ip:port when it does not, and get_relay_url() reports https:// for a TLS relay instead of hardcoding http:// (RELAY-2). What TRANS-1 actually needed is kept: ws:// to a non-private host still draws a toast and a persistent red line on the relay status saying that plaintext can be injected into, not just read. Tests: RelayUrlTest, RelayClientBuildWsUrlTest, TestRelayUrlScheme, TestAndroidSetup.
  • android_events() returns an empty list until android_event_stream(True) is called. The streaming switch used to be a report, not a control: the phone buffered the last 200 accessibility events regardless and GET /events served them while reporting streaming: false. Collection is now gated at the source, which is what the tool descriptions always claimed (DROID-4).
  • android_send_intent's schema no longer advertises values the device rejects (tel:+1234567890, android.settings.WIFI_SETTINGS), and android_broadcast no longer suggests a protected system broadcast; the intent description now states the boundary and points at android_call/android_send_sms (CTRL-2).
  • Audit remediation port (60 findings). The LAN dev server (:8765) no longer starts unconditionally — it runs only behind the in-app USB/LAN toggle, off by default, and the UI advertises the address only while listening (#1); pairing codes are 12 characters on new installs with legacy 6-char codes still validating (#16); the toolchain moves to AGP 8.7.3 / Kotlin 2.0.21 / Ktor 2.3.12 / SDK 35 with okhttp in the version catalog (#44); the Kotlin boundary validates blank/enum/range inputs with 400s (#18); screenshots take with a timeout, waitForElement polls by light search, locations report ageMs/stale, contacts run one Phone.CONTENT_URI query, and the auth throttle uses a monotonic clock (#19-21, #24, #48); broadcasts are restricted to non-system namespaces and dead intent-deny entries are gone (#12, #22); node IDs/counts share one construction site and event sources carry the event path segment (#17); the file-level unused suppression is removed (#56); the Python toolset has a logging @_tool wrapper, strict unknown-kwarg dispatch, macro guardrails (step cap, no nested macro/setup, configurable delay/timeout), a ping cache, batched atomic .env writes, and recursive substring PII redaction (#11, #26, #27, #36-40, #50, #59, #60); start_relay updates-or-restarts instead of silently keeping stale credentials (#4); android_setup warns on localhost-bound relays and no longer echoes the code (#5, #39); the plugin copies are generated by tools/build_plugin.py --check from tools/ as canonical (#3, #51); ruff check gates the Python CI job (#37); requirements.txt and the orphaned stitch-screens/ assets are deleted (#33, #53); the relay daemon ships as a user unit with packaged-first import and the install/systemd/manual-test docs match the gates (#57, #58). Deliberately not ported: forced wss:// + cleartext-off (#2 — origin dials the typed scheme with a red plaintext warning, TRANS-1), a strict intent allowlist (#12 remainder — custom deep links are a pinned contract), the unified tool envelope (#15 — macro failure detection was hardened upstream instead and exact {"error"} shapes are pinned by PII-wording tests), semantic node hashes (#47 remainder — origin hardened computeHash with separator-injective fields instead), store-capacity consts (#54 — the mutable caps are pinned test seams), and a signed release build (#45 — out of scope: no keystore/secrets creation). Gates: testDebugUnitTest 568/0 + assembleDebug/assembleRelease; pytest 1953 passed; ruff check clean; build_plugin.py --check in sync.

Fixed

  • android_pinch no longer throws when the pinch centre is near a screen edge. GestureDescription.StrokeDescription's constructor rejects a path whose computed bounds are negative (IllegalArgumentException: "Path bounds must not be negative"), and the two strokes reach 50 * scale px either side of the centre — so pinch(x = 50) at the default scale 1.5 put the left finger's end at 50 - 75 = -25 and threw out of ActionExecutor.pinch before dispatchGesture was reached. The caller got a 500 whose body names only the exception class, and nothing happened on screen: a coordinate that is perfectly valid on the device reported as a failed pinch. bounds.top is checked by the same constructor, so a negative y reached it directly even though the horizontal offsets cannot. All four path coordinates are now clamped at 0 on both axes; near an edge the gesture is asymmetric — the finger that would have started off-screen starts at the edge instead — which is a slightly weaker pinch where the alternative was a crash the caller cannot catch. The result message still quotes the caller's own coordinates, not the clamped ones. Tests: ActionExecutorGestureTest (18 → 22) — x = 50 at the default scale, x = 0 where both left-hand coordinates clamp, y = -10 for the top edge, and x = 20 with scale = 4 to pin that the clamp tracks 50 * scale rather than a hardcoded margin. Red-green verified: all four fail beforehand with exactly that message.
  • RelayClient.revivalReconnectJob is read-only outside the object. F32 widened it from private to internal so revivalReconnectMayDial could be pinned against the states the handle passes through, and widened the setter with it — so any code in the module, tests included, could publish a job reconnectDelayed() had never scheduled. Three of the predicate tests did exactly that: they assigned a bare Job() and asserted on it, which is a state production cannot reach. The handle is the thing that decides whether a woken reconnect dials, so letting anything but the scheduler write it is how the F11/F25/F32 guarantees get quietly undone later. It is now internal var … private set: still readable for the tests, assignable only by reconnectDelayed(), cancelRevivalReconnect() and the coroutine that clears its own handle before dialling (F9).
    The three tests were rewritten to reach the same states through the real API, which also makes them stronger: the cancelled case now cancels the revivalScope's job rather than a synthetic one, so it proves the predicate refuses a scheduled reconnect that died while waiting — with the handle still published and shouldReconnect still armed, which is precisely the combination F32 exists for; the superseded case fires reconnectDelayed() twice and asserts the two handles differ; the cleared case asserts disconnect() nulls the handle before the predicate refuses it. Tests: RelayClientRevivalReconnectTest (12, all passing before and after the visibility change). Red-green for a visibility change is the compiler: re-adding RelayClient.revivalReconnectJob = Job() to the test now fails with "Cannot assign to 'revivalReconnectJob': the setter is private".
  • android_setup reads ANDROID_RELAY_PUBLIC_HOST once. F34 skipped the IP-echo calls by reading the variable in android_setup itself, on top of the read already inside _relay_public_host() — and _relay_address_note() read it a third time. Three reads of one variable in one function is three places that can disagree, and the reason the caller read it at all was that _relay_public_host() took the fallback by value: to avoid paying for _get_public_ip() the caller had to decide first, which meant duplicating the decision. The helper now takes a callable and calls it only when the variable comes back empty, so the decision exists in exactly one place. _relay_address_note(tls, host) no longer reads the environment either — it is keyed on the address being an IP literal (ipaddress), which is what the warning is actually about. That also fixes a case the old check got wrong: an operator who set ANDROID_RELAY_PUBLIC_HOST to a bare IP was silently given no warning, because the check read "a host was configured" rather than "the address is a name a certificate can cover". Both copies. Tests: TestAndroidSetup (+4, and the fallback table updated to the callable signature) — the helper calls the fallback only when the variable is unset or empty; a _env spy counts exactly one read of ANDROID_RELAY_PUBLIC_HOST across a whole android_setup; a configured bare IP under TLS gets the note; a configured hostname does not. 10 fail before the change.
  • The queued_unconfirmed message no longer contradicts the tally beside it. describe's null branch said "no send report arrived within 10000ms", but null from await() only ever meant the bound ran out with no failure recorded — segments could have confirmed, and data.delivered in the very same response said how many. A multipart send with two of three segments confirmed therefore answered "no send report arrived" next to "delivered": 2, and an agent reading the prose concluded nothing had happened, which is the belief that produces a duplicate. await()'s own KDoc said the same wrong thing ("null when no report arrived at all") and still pointed at [reportedParts], which F36 made private — a dangling KDoc link. The branch now splits on delivered: with segments confirmed it reports "N of M segments were confirmed within Xms and the rest never reported", with none it keeps the original wording, and a single-segment send never grows multipart phrasing. Both KDocs are corrected and now point at awaitTally, the read that carries the counts.
    The tool docstring (both copies) now says plainly that queued_unconfirmed covers every case where something is unknown, not only "the radio stayed quiet": no report in time, only some segments confirmed before the window closed, or a segment that failed while others never reported. docs/troubleshooting.md gains both variants and points at the delivered count. Tests: SmsSendReportTest (32 → 34) — the message agrees with the tally for zero and non-zero delivered, quotes "2 of 3", still forbids the resend, and a single-segment send keeps the original wording; plus TestSendSmsOutcomeDocumentation (5, both copies) pinning that the docstring and the schema description name all four statuses, say queued_unconfirmed covers segments that never reported, and say only failed is retryable — a rule an agent cannot read is a rule that does not exist. Red-green verified on both sides.
  • The loopback TLS warning filter is one narrow, message-pinned entry instead of a per-call context. F33's warnings.catch_warnings() was correctly scoped but is documented as not thread-safe: it swaps the process-wide warnings.filters list for the duration of the block, and every swap bumps the filter version, invalidating every module's __warningregistry__ cache. In a gateway that can serve tool calls on several threads, one call's context could suppress — or un-suppress — another call's warning, and every unverified loopback request paid two list swaps and a version bump.
    It is replaced by a single warnings.filterwarnings("ignore", category=InsecureRequestWarning, message=...) whose message regex is pinned to exactly the hosts _bridge_tls_verify() relaxes for: localhost, 127.0.0.1, ::1 and [::1]. Narrower than either predecessor — an unverified request to any other host still warns, including localhost.example.com and 127.0.0.1.evil.test, which a host-prefix pin would have swallowed — and installed once rather than per call. The bracketed IPv6 alternative is not optional: urllib3.util.parse_url("https://[::1]:8766").host returns '[::1]', brackets included, and that is the string urllib3 interpolates into the message. Installation is idempotent by inspecting warnings.filters rather than by a module flag, because a flag goes stale the first time anything else legitimately replaces the filter list — catch_warnings does exactly that — leaving the filter missing while the flag says it is installed; filterwarnings, and so the version bump, then runs only when the entry really is absent. _bridge_request() stays: it is what makes verify and the filter impossible to forget at a new call site. The context manager and the contextlib import are gone. Both copies.
    Tests: TestBridgeTlsVerification (26 → 32), replacing F33's two context-manager cases. Every host form is re-derived through parse_url and asserted to be swallowed, so a urllib3 that rewords the warning fails a test instead of silently starting to shout; six non-loopback hosts still warn; three consecutive installs leave exactly one matching entry and no blanket InsecureRequestWarning ignore anywhere in the filter list; a verified call installs nothing; and _loopback_tls_warnings_suppressed is asserted absent so the per-call context cannot come back. 8 of these fail before the change.
  • The SMS send tally is read once, atomically. sendSms called report.await(timeoutMs) and then read report.confirmedParts and report.reportedParts as two separate calls — and the receiver is still registered when the bound runs out, because unregistering happens in the finally afterwards. A RESULT_OK landing between the two reads produced confirmed = 0, reported = parts, which is exactly the shape describe maps to status: "failed": "nothing went out, a retry is safe", for a message that was partly delivered. That is the duplicate F30 existed to prevent, reintroduced through a read ordering. reportedParts was itself a sum of two AtomicIntegers taken at different instants, so it could describe a moment that never existed.
    The three counters now sit behind one lock, SmsSendReport.Tally is an immutable snapshot of all of them plus the latch's completeness, and awaitTally(timeoutMs) returns it at the instant the wait ends. describe(tally, parts, timeoutMs) is the race-free entry point; await() is now awaitTally(...).outcomeCode, so its contract and every existing test are unchanged. The two counters are private: exposing them separately is what allowed the split read, and making it not compile is worth more than a comment telling the next call site not to. Reverting ActionExecutor to the old two-read form is now a compile error, which is the red-green check for this one — the race itself is timing-dependent and no unit test can replay it honestly.
    Not fixed by unregistering the receiver first, which was the other option: unregisterReceiver does not synchronise with an onReceive already running on another thread, so it narrows the window instead of closing it, and it would need a flag to stop the finally from unregistering twice. Tests: SmsSendReportTest (28 → 32) — a snapshot taken before a late report is not moved by it while a fresh one is, and describe on that snapshot answers queued_unconfirmed where the split read answers failed (both asserted, so the contrast is the regression test); awaitTally agrees with await and reports completeness; a bound that ran out reports itself incomplete; and 500 reports written from a second thread are snapshotted in a tight loop with confirmedParts never exceeding reportedParts and never exceeding the segment count.
  • RelayClient no longer writes exception messages from the message-handling path into logcat. F26 fixed the 500 response to use CommandDispatcher.errorBody(), and left the log line right beside it emitting "Error handling message: ${e.message}". That catch wraps the JSON parse, the request_id check and the /mic_file stream, and a JsonSyntaxException from a malformed command can quote the command — which for /send_sms contains the recipient, and for /mic_file a file path. AGENTS.md keeps phone numbers, recipients and location out of logs as well as out of responses, and logcat is not private: a bug report captures it, and READ_LOGS is readable by any app on an older device.
    logMessageFailure(cause) logs the same class name errorBody hands the caller, so the two cannot drift, and attaches no throwable — Log.e(tag, msg, tr) appends Log.getStackTraceString(tr), whose first line is class: message, so passing the throwable would put the message back however the text is worded. The cost is the stack trace; the class name is enough to locate the throw and a recipient in logcat is not worth line numbers. The rest of the grep: "Delayed reconnect not scheduled: $e" interpolated toString(), i.e. the message, and now logs the class name. The three Log.*(msg, throwable) calls left alone are audited in a comment — startForeground's SecurityException and the two Termux startService failures carry framework text about our own fixed intent, never device content. onFailure's "WebSocket failure: $errorDetail" keeps t.message deliberately: it is a transport error whose message can name the relay host, which the connect path already logs on purpose, and the same string is what the user reads on the relay status line, where "unable to resolve host" is the difference between a diagnosable failure and an opaque one. docs/architecture.md records the logcat rule next to the response one. Tests: RelayClientLogRedactionTest (5, new) reads the line back through Robolectric's ShadowLog — a recipient and a body in the message appear in neither msg nor an attached throwable, a FileNotFoundException path does not leak, a message-less exception still logs a usable name with no literal null, the anonymous-class ifBlank fallback does not echo the message, and the logged name equals errorBody's; plus an end-to-end assertion in RelayClientRelayTest (13) that the real catch produces exactly that line and no throwable. Red-green verified with today's log line extracted unchanged: all 5 fail.
  • android_setup no longer calls out to third-party IP-echo services when the operator has already named the host. _get_public_ip() tries api.ipify.org, ifconfig.me and icanhazip.com at 3 s each and then falls back to a DNS lookup of the machine's own hostname — up to nine seconds of blocking network I/O, and every one of those answers was discarded the moment ANDROID_RELAY_PUBLIC_HOST was set, because _relay_public_host() prefers it. Setting that variable is what F24 tells TLS users to do, so the recommended configuration was the one that paid for detection and threw the result away. It also handed this gateway's public address to a third-party service on every setup for no reason. Detection is now skipped when the variable is set (an empty value counts as unset, matching _env() everywhere else, so a blank line in .env cannot produce ws://:8766). Both copies. Tests: TestAndroidSetup (+4) — no detection call with the host configured under ws:// or wss://, and detection still runs when the variable is unset or empty, so skipping cannot silently become "never detect".
  • The loopback TLS warning suppression no longer silences warnings for the whole gateway. _bridge_tls_verify() called urllib3.disable_warnings(InsecureRequestWarning), which rewrites the process-wide warnings.filters list and never restores it. This module runs inside a long-lived gateway, so one android_ping() against an https://localhost bridge silenced InsecureRequestWarning for every other library in the process that makes an unverified HTTPS call — including one that never made the loopback decision this code made and would have wanted to hear about it. A module that relaxed verification for its own one URL should not also be the reason nobody else hears about theirs.
    The suppression became warnings.catch_warnings() scoped to the single request, and all four bridge call sites moved onto a new _bridge_request(verb, url, **kwargs) that applies both the verify decision (F19) and the suppression, so a new call site cannot forget either. That scoping was itself replaced one review later — catch_warnings swaps the process-wide filter list and is not thread-safe; see the F37 entry below. _bridge_request() is what survived. It attaches the bridge auth headers and is documented as bridge-only: _get_public_ip()'s calls to third-party IP-echo services deliberately do not use it, since routing them through it would send the pairing token to api.ipify.org. Tests: TestBridgeTlsVerification (20 → 26) — warnings.filters is unchanged after an https-loopback ping and after a plaintext one, no ignore filter for InsecureRequestWarning survives, and the context manager suppresses a warning raised inside it while one raised immediately after is still recorded. Red-green verified with the context manager inert: 4 fail.
  • The post-revival reconnect now checks itself, not just the flag. F11 gave the woken coroutine one guard — shouldReconnect — and F25 moved that guard and the dial into a single critical section. But the coroutine wakes from its 30 s delay and then has to wait for the monitor, and disconnect()/connect() are both @Synchronized: a user who disconnects and then reconnects while it was queued leaves shouldReconnect true, because their own connect() set it. The flag-only guard then read "go ahead" for a job that had been cancelled and a URL the user had already replaced, and dialled the old relay over the top of the connection they had just made. That is F11 again, one lock acquisition later.
    revivalReconnectMayDial(self) is now the guard, and it answers false unless the job is uncancelled, is still the handle reconnectDelayed() last published, and the flag is armed. The coroutine takes its own Job from coroutineContext and passes it in, still inside the monitor the dial runs under, so F25's one-step property is unchanged. revivalReconnectJob becomes internal so the states it passes through can be pinned. Tests: RelayClientRevivalReconnectTest (7 → 12) — a user reconnect leaves the flag armed but the stale job may not dial; a job cancelled while it waited may not; a job superseded by a newer watchdog fire may not, while the newer one may; a cleared handle may not; a null job may not. The five pre-existing F9/F11/F25 cases still pass, including the two that exercise the wired path end to end. Red-green verified with the predicate reduced to the flag alone: 4 fail.
  • The relay's WebSocket handshake reads the expected pairing code once. _handle_ws compared the presented token against state.pairing_code and then, a few lines later, read state.pairing_code again to record which code the session had proved. set_pairing_code() runs on the caller's thread and needs only _relay_lock, which the handler never holds, so a rotation could land between the two reads — and the session that had proved the OLD code was recorded as having proved the NEW one. F21's post-prepare re-check then compared NEW against NEW, passed, and published the session; the scheduled rotation drop compared the recorded code against the current one, found them equal, and left it alone. The result was the thing rotation exists to prevent: a session holding full device control on a code that no longer exists, indistinguishable from a legitimate one, with nothing in the log to show it. F21 closed the window between the check and prepare; this closes the one inside the check itself. expected_code is now read once and used for both the constant-time comparison and authenticated_with. Both copies. Tests: TestRotationDuringHandshake (3 → 4) — a hook on _tokens_equal rotates the code immediately after the first comparison, which is the only deterministic way to land inside the gap, and the session must then be closed with POLICY_VIOLATION, never published, never recorded, and never serve a command; before the fix it is published recording the new code.
  • android_send_sms only calls a send retryable when every segment accounted for itself. describe mapped any failure code with nothing confirmed to status: "failed" — documented to the agent, in the schema, the docstring, skill.md and docs/troubleshooting.md, as "nothing went out, a retry is safe". But a failure code arrives as soon as one segment reports: a three-segment send where segment one hit RESULT_ERROR_RADIO_OFF and segments two and three never answered at all produced exactly the same answer, and the two silent segments may well have gone out. The retry the caller was told was safe then duplicated them. F23 drew the line at "did any segment succeed"; the line also has to be "did every segment report".
    describe now takes reportedParts — the tally F29 made complete — and failed requires reportedParts >= parts. A failure with segments unheard from falls back to queued_unconfirmed, success: true, do-not-resend, and wording that still names the radio's reason and how much of the tally is missing ("1 of 3 segments reported and at least one failed (radio off), the rest never reported"), so the agent can tell the user something went wrong without being invited to resend. Both new parameters default to 0, which is the safe direction: an unstated tally can never produce failed, so a caller that forgets to pass it degrades to do-not-resend rather than to a duplicate. ActionExecutor.sendSms passes report.reportedParts alongside report.confirmedParts. The four statuses and the tightened meaning of failed are restated in the schema description, the docstring (both copies), skill.md/SKILL.md and docs/troubleshooting.md. Tests: SmsSendReportTest (25 → 28) and ActionExecutorSendSmsTest (16 → 17) — a failure with unreported segments is queued_unconfirmed and not retryable, failed appears only at reportedParts == parts (asserted across all four values for a 3-segment send), the same through a real SmsSendReport whose bound runs out, and end to end through the executor with a two-segment send that hears from one. Red-green verified with the parameter inert.
  • A multipart SMS whose segments all reported now answers immediately instead of sitting out the whole ten seconds. F23 made a multipart send wait for the remaining segment reports so the confirmed tally would be complete, but a failed report never counted the latch down — it recorded the code and returned. The latch therefore only reached zero when every successful report had arrived, so a three-segment send that got two OKs and one failure, i.e. every report the radio was ever going to send, still waited out smsSendReportTimeoutMs for a count that could never be released. Ten seconds of a caller's 30 s budget on the common failure path, on a Dispatchers.IO thread F13 had just moved it onto.
    Every report now counts down, success or failure, and the failure codes are recorded separately: failure keeps the first code (the one reported), a new rejected counter tallies them, and reportedParts is confirmedParts + rejected. The latch now means what the wait needs it to mean — "every segment has reported" — so it ends when the tally is actually complete and only runs to the bound when a report genuinely never arrives. A single-segment send is unchanged: one report, one count down, immediate. reportedParts is also what the next fix needs to tell a complete tally from an incomplete one. Tests: SmsSendReportTest (22 → 25) — the mixed multipart case and the all-failed one both assert they answer in under a second against a 5 s bound, reportedParts counts successes and failures alike, and a single-segment failure is still immediate.
  • The MEDIA temp-file registry is bounded by what is on disk, not by how long the process has been up. F18 made the stale sweep repeat, but _media_temp_files was still only ever added to: _register_media_temp() put a path in, and nothing took one out until atexit cleared the whole set. A gateway that runs for days therefore accumulated one dead entry per screenshot, screen recording and microphone fetch — small, but monotonic, in the one process that never exits, and atexit then walked a list of paths that had not existed for days. The sweep now prunes it: registered paths whose file is gone are discarded, both for files this pass deleted and for files anything else removed. The prune runs before the directory listing so an unreadable temp dir does not also stop it, and it is wrapped per path so one bad stat cannot abort the pass. Files that still exist stay registered — including the one the current call is about to hand back as MEDIA:<path>, whose mtime keeps it out of the age-based deletion as before. Both copies. Tests: TestMediaTempFileRetention (10 → 14) — a path the sweep deleted is unregistered, a path that no longer exists is unregistered while a live one is kept, five successive registrations leave the registry empty rather than holding five dead paths, and pruning still happens when os.listdir raises.
  • android_send_sms no longer spends ten seconds waiting for a report nothing was listening for. Registering the sentIntent receiver can fail — a SecurityException on a hardened ROM, an IllegalArgumentException from a context that cannot take one — and sendSms correctly refused to claim success without a report. It then waited out the whole smsSendReportTimeoutMs bound for a report that by construction could not arrive, a third of the caller's default 30 s budget spent learning nothing, and answered with the timeout wording ("no send report arrived within 10000ms") — which says the radio was given the chance to confirm and did not, when in fact the bridge never had anywhere to put the answer. The unregistered case now returns immediately through SmsSendReport.describeUnobservable(parts, reason), with wording that says the report cannot be observed on this device and names the reason. The status stays queued_unconfirmed and the do-not-resend rule is unchanged, because the message is with the radio either way; the send itself still happens, since an unobservable report is not a reason to withhold it. docs/troubleshooting.md documents the variant next to the timeout one. Tests: SmsSendReportTest (21 → 22) and ActionExecutorSendSmsTest (13 → 16) — the unregistered send answers in under a second of a 5 s bound, the wording is the unobservable one and not the timeout one, the message still reaches the radio, and no unregisterReceiver is attempted for a receiver that was never registered. Red-green verified: 2 fail before the wiring.
  • The relay's own 500s now carry the same body as HTTP's. L1 made CommandDispatcher.errorBody() the single contract for a route failure, and both transports used it — but there is a third 500 site that dispatch never sees: RelayClient.handleMessage's catch, which wraps the JSON parse, the request_id check and the /mic_file stream. That one answered {"error": e.message}, so a command with no request_id came back over the relay as {"error": "Command is missing request_id"} while the identical failure over direct HTTP answered {"error": "IllegalArgumentException"}. Same divergence L1 existed to remove, and the leaky side: an exception message can quote an SMS recipient, a file path or a host:port, which is what the PII convention keeps out of responses. The catch now builds its envelope from CommandDispatcher.errorBody(). The Log.e text is unchanged — logcat already prints the throwable's own message and stack trace, and a device-local log is not a tool response. docs/architecture.md names all three 500 sites. Tests: RelayClientRelayTest (11 → 13) — the envelope is a bare class name matching [A-Za-z0-9_$.]+ with no spaces (the same assertion CommandDispatcherErrorContractTest makes of the dispatcher), and it is asserted equal to errorBody()'s output for the same cause rather than to a string, so the two cannot drift again silently. All three fail before the change.
  • The post-revival reconnect's guard and its dial are now one step. F11 had the coroutine check shouldReconnect and clear its own job handle inside synchronized, then call the connector after releasing the monitor. disconnect() and connect() are both @Synchronized, so a user disconnect landing in that gap found no job left to cancel and a flag nothing would re-read — and the reconnect went ahead anyway, which is F11 again one instruction narrower. The window was small (no suspension point between the two) but it was on the exact path the guard exists to protect: the 30 s timer expiring while the user is looking at the relay screen. The connector is now called inside the same critical section. The monitor is reentrant, which is what lets the dial call connect() — and so cancel this very job — without deadlocking, so F9's "the reconnect must not be cancelled by its own connect()" still holds; nothing in the dial blocks on the monitor from another thread (notifyStatus posts to the main looper, newWebSocket enqueues). Tests: RelayClientRevivalReconnectTest (6 → 7) — Thread.holdsLock(RelayClient) observed from inside the connector, which is the invariant itself rather than a race replay; it fails before the change. The six F11/F9 cases pass unchanged.
  • android_setup can now print a wss:// address the phone can actually complete a handshake with. It printed the detected public IP, and the phone validates the relay's certificate with the platform trust store — which means hostname verification against whatever it dialed. Certificates are issued for DNS names (Let's Encrypt will not issue one for a bare IP), so the TLS setup the previous change documented failed at the handshake for anyone who followed it, with a certificate error on the phone and nothing on the gateway to explain it.
    ANDROID_RELAY_PUBLIC_HOST names the host the certificate covers; _relay_public_host() falls back to the detected IP when it is unset. It changes only what is printed — the relay still binds ANDROID_RELAY_HOST — so the two cannot be confused. When TLS is on and the variable is unset the address stays an IP and the response gains a server_address_note saying the handshake will fail unless the certificate covers it and naming the variable to set; the same sentence is appended to user_instructions, because that is the text a human reads. A plaintext relay gets no note: an IP is a perfectly good ws:// host. docs/configuration.md documents the variable in the table, in the .env scope list, and in the Relay + TLS section. Both copies. Tests: TestAndroidSetup (+8) — the configured host reaches the printed address and the instructions, an IP-only TLS address carries the note in both places, a plaintext address carries none whether or not the variable is set, the helper's unset/empty/set fallbacks, and ANDROID_RELAY_HOST still decides the bind address.
  • android_send_sms no longer tells the caller a partly delivered multipart SMS is safe to retry. SmsSendReport answered on the first segment report that was not RESULT_OK, and describe mapped any such code to status: "failed" — documented to the agent, in the schema, the docstring, skill.md and docs/troubleshooting.md, as "the send definitively did not happen, a retry is safe". For a 3-segment message whose first two segments were confirmed and whose third hit RESULT_ERROR_NO_SERVICE that is false: the recipient has the opening of the message, and a retry hands them the same two segments again. F14 had just made the unconfirmed case non-retryable for exactly this reason and left the partial case on the other side of the line.
    SmsSendReport now counts the segments that reported RESULT_OK (confirmedParts) and describe takes the tally, adding a fourth outcome: partially_sent, success: true, delivered of parts, the radio's reason, and an explicit do-not-resend. failed is reserved for a definite error with nothing confirmed, which is the only case where a retry is safe. Every outcome now carries delivered alongside status and parts so a caller can reason about the tally without parsing prose.
    Counting is only useful if the count is complete, so a failure no longer ends the wait early for a multipart send: the remaining segment reports are awaited up to the same 10 s bound. Answering on the first failure could not distinguish "no segment went out" from "the first two did", and undercounting lands on the dangerous side — it produces failed, i.e. "retry". A single-segment send still answers immediately, since nothing else can arrive. The wait runs on Dispatchers.IO (F13), so it costs latency, not a blocked transport thread.
    The do-not-resend rule is restated wherever an agent reads it: the tool schema description and docstring (both copies), skill.md/SKILL.md, and a new docs/troubleshooting.md entry. Tests: SmsSendReportTest (16 → 21) — a partial multipart send is partially_sent, success: true, do-not-resend, naming the reason and both counts; a failure with nothing confirmed stays failed and retryable; a single-segment failure is never partial; a multipart failure waits out the bound so the tally is final; every segment report is counted; and the PII case still holds for the new outcome. Red-green verified with the counter inert.
  • The microphone is no longer held open by a recording the service abandoned. F16 settled the phase for a record loop cancelled before its body started, but the same job also owns the AudioRecord release: it happens in the loop's finally, and a coroutine whose body never starts runs no finally. onDestroy only called safelyStop, which stops capture without releasing, and its unconditional release is guarded by recordingJob == null — precisely the case this is not. The native recorder stayed held for the life of the process: the microphone-in-use indicator never cleared, and the next /mic_start could fail to initialise the microphone. onDestroy's completion handler now releases whatever AudioRecord is still held once the job is done, which is a no-op for a loop that ran (its finally already released and nulled the field) and cannot pull the microphone out from under a loop that is still writing, because it waits for completion. recorder becomes internal so the leak can be asserted: the case that causes it is a job cancelled before dispatch, which no real AudioRecord reproduces on demand. Tests: MicrophoneRecorderServiceStuckStateTest (10 → 14) — an abandoned job's recorder is released on destroy, the release happens whatever phase was left behind (the leak was never specific to FINALIZING), a still-running finaliser keeps ownership until it completes and is then released exactly once, and a destroy with nothing held releases nothing. Red-green verified by removing the release call: 3 fail.
  • A pairing-code rotation can no longer be outrun by a handshake in flight. _handle_ws validated the Bearer token, then await ws.prepare(request), and only afterwards published state.phone_ws. set_pairing_code() runs on the caller's thread and needs only _relay_lock, which the handler never holds, so the code could rotate inside that await — and the session then published itself with a code that no longer existed. F17's drop could not catch it: it targeted the socket that was current when the code changed, and this one was not current yet. The result was full device control (screen, input, microphone, SMS, calls, contacts, location, clipboard) surviving the rotation that exists to revoke it, with nothing in the log to show it.
    Each session now records the code it proved in state.phone_ws_code; _handle_ws re-checks it under phone_ws_lock after prepare and closes the socket with POLICY_VIOLATION instead of publishing when it has gone stale. _cleanup_phone clears the recorded code with the socket, so a later rotation never judges a session it knows nothing about. And _drop_phone_after_rotation is now decided by that recorded code rather than by a captured socket identity: it closes whatever proved a code that is no longer current, needs nothing captured, and is a no-op when the live session is already on the current code — which is what makes it cover both F17 (a session that re-dialed with the NEW code survives) and F20 (a rotation with nothing to drop does not fail a healthy session's in-flight requests). A session whose code was never recorded is dropped: failing closed is the safe answer when the alternative is leaving a possibly-stale session with full device control. Both copies. Tests: TestRotationDuringHandshake (3) and a restructured TestPairingRotationDrop (6). The handshake cases drive a fake whose prepare() rotates the code, which is the only deterministic way to land inside the await: the rotated handshake is closed and never published, an unrotated one still publishes and records its code, and a rejected handshake never reaches the re-check (it is not a second authentication). The drop cases pin close-on-stale, survive-on-current with its pending request intact, close-on-unknown-provenance, no-op-when-nothing-is-connected, scheduling, and the unchanged-code early return. 14 of these fail before the fix.
  • A pairing-code rotation with no session to drop no longer breaks the session that replaced it. _drop_phone_after_rotation()'s stale_ws is None branch called _fail_inflight() unconditionally, on the reasoning that a caller must not hang on a future whose phone is gone. But nothing being connected at rotation time means every request pending when the coroutine runs belongs to a session that authenticated with the new code — RelayClient re-dials the moment its code rotates, and its first tool call can easily be in flight before the scheduled drop gets to run. Those callers were answered ConnectionError("Phone disconnected (pairing code rotated)"), so rotating the code broke a healthy session it had no business touching; the android_ping() an agent runs straight after android_setup is exactly the call that lands in the window. The branch is now a no-op. A future whose phone really is gone is still failed, by _cleanup_phone() on the disconnect path where that belongs. Both copies. Tests: TestPairingRotationDrop (5 → 6) — a NEW-code session keeps its socket, stays registered, and keeps its in-flight request pending across a rotation that had nothing to drop.
  • android_setup no longer writes a bridge URL the TLS relay cannot answer. With ANDROID_RELAY_CERT/ANDROID_RELAY_KEY set, aiohttp serves the relay's whole site over that one ssl_context — the /ws route the phone dials and the HTTP routes the tools call are the same TCPSite — but setup still saved and exported ANDROID_BRIDGE_URL=http://localhost:<port>. The listener stopped speaking HTTP, so every tool call failed, including the android_ping() an agent runs immediately after setup to check the pairing worked; setup itself reported "Relay is running" and a phone address that connected fine, so nothing pointed at the actual breakage. The previous RELAY-2 change fixed get_relay_url(), which has no production callers — the URL that matters is the one setup writes. Both are now derived from the same both-paths TLS rule: _relay_bridge_url(port, tls) for ANDROID_BRIDGE_URL, _relay_server_address(host, port, tls) for the phone, and _relay_tls_enabled() reads the two variables directly because setup decides the scheme before it imports the relay module (pinned against android_relay.is_tls_configured() so the two predicates cannot drift).
    An https://localhost URL still cannot verify: the certificate is issued for the relay's public name, never for localhost. _bridge_tls_verify() therefore switches verification off for a loopback bridge URL only — that hop never leaves the machine, and an attacker who could intercept it already has local code execution and can read ~/.hermes/.env, the file holding the Bearer token, directly, so this gives up nothing that was not already theirs and is strictly better than the plaintext loopback hop it replaces. Any other https:// bridge URL (a remote relay, a reverse proxy, a direct phone connection) keeps full verification, and the urllib3 insecure-request warning is suppressed for the single call that needs it (see the F33 entry below — the first version of this silenced it process-wide). All four HTTP call sites go through one _bridge_request() helper so a new one cannot forget the setting: _get, _post, _check_requirements' /ping probe and android_mic_fetch's streaming download. docs/configuration.md and SECURITY.md document the relaxation and how to avoid it. Tests: TestAndroidSetup (+9), TestBridgeTlsVerification (10) — the scheme follows the certificate in both the exported env and the written .env, half a configuration stays http://, the two TLS predicates agree across all four combinations, the verify decision is a table over eight URLs, and every call site is observed passing it.
  • The stale-MEDIA temp sweep now runs for the life of the process, not once in it. PY-2 added an age-based, prefix-scoped sweep of android_screenshot_* / android_record_* / android_mic_* files older than an hour, behind a _media_temp_swept latch so it ran on the first _register_media_temp() and never again. That is the wrong shape for the process that actually runs it: a gateway stays up for days, so it cleaned the temp dir on the first screenshot and then kept every later screenshot, screen recording and microphone WAV — rendered content from arbitrary apps, banking balances and message threads, and the pairing code whenever the Bridge app was on screen — on disk until it happened to exit. atexit only ever fires for a process that exits. The latch is now a timestamp: _MEDIA_TEMP_SWEEP_INTERVAL_SECONDS = 60, so a registration sweeps at most once a minute (the walk lists the whole temp dir, so it cannot run per file) and otherwise behaves exactly as before — our prefixes only, mtime older than an hour only, best-effort, and never a file this call just registered. Applied to both copies. Tests: TestMediaTempFileRetention (8 → 10) — the once-per-process case is replaced by one asserting the interval is respected and that a pass runs again after it elapses, a case driving the same thing through _register_media_temp() (the path the finding is about), and a case pinning that a second pass never deletes the fresh file the caller is about to hand back as MEDIA:<path>. Red-green verified by restoring the latch: 2 fail.
  • Rotating the pairing code no longer drops the session that reconnected with the new one. set_pairing_code() schedules _drop_phone_after_rotation() onto the relay's event loop with run_coroutine_threadsafe, and the coroutine called _cleanup_phone() with no expected_ws — so it closed whatever socket was current when it ran, not the one that had authenticated with the old code. RelayClient.onPairingCodeRotated() re-dials immediately, which is the behaviour AUTH-1 exists to produce, so the reconnect routinely landed inside that window: the phone presented the NEW code, was accepted, and was then closed by a drop meant for its predecessor. Rotation looked like it broke the connection and the phone had to retry. The socket is now captured under _relay_lock in set_pairing_code() and passed through as expected_ws, which _cleanup_phone() already knew how to honour. A None capture means nothing was connected at rotation time, so there is no old-code session to drop: it is not forwarded as expected_ws (a None there skips the identity guard and would close whichever phone arrived afterwards), and in-flight requests are still failed so no caller hangs on a future whose phone is gone. Applied to both copies. Tests: TestPairingRotationDrop (5) — the old-code session is still closed when it is the current one, a session that reauthenticated with the new code survives and stays registered, a phone that arrives after a rotation with no session is left alone, set_pairing_code is pinned to capturing the socket it saw, and an unchanged code still drops nothing. Red-green verified against the previous one-argument _drop_phone_after_rotation.
  • android_mic_start can no longer stay blocked at 409 by an abandoned finalizing phase. The #98/F10 fix left FINALIZING out of isAwaitingRecorder on the reasoning that the finalisation block has no suspension points and owns both terminal states, so it always reaches markReady/markError by itself. That premise needs the block to run: requestStop() publishes FINALIZING from the main thread while the record loop may still be queued on Dispatchers.IO, and a service destroy inside that window cancels the coroutine before its body starts — so the block, its catch and its finally all never execute. FINALIZING counts as isActive, tryReserveStart() keeps returning false, and every /mic_start answers 409 until the app restarts: #98 again, one phase later. onDestroy now attaches invokeOnCompletion to the recording job and settles a FINALIZING phase that nothing will finish, via a new MicrophoneRecordingState.settleAbandonedFinalizing(activeFile, message). The completion handler is what keeps F10 closed: it runs after the job, so a finaliser that reached markReady leaves the phase at READY and the settle is a no-op — no transient error for a good recording. A null job means the instance never started a recording, so a phase belonging to somebody else is left alone, and the settle is scoped to the file this instance owns so a late handler cannot rewrite a newer recording. Tests: MicrophoneRecordingStateTest (2 → 6), MicrophoneRecorderServiceStuckStateTest (7 → 10), including the F10 cases unchanged; red-green verified, and the service test class gained an @After reset so a failing case cannot leave the state machine active and fail the next one for an unrelated reason.
  • android_send_sms send reports can no longer be counted toward the wrong call. Every send registered a receiver for the same broadcast action (com.hermesandroid.bridge.action.SMS_SENT_REPORT) and built its sentIntent PendingIntents with requestCodes 0..n-1. A context-registered receiver gets every broadcast matching its filter, so two overlapping sends each tallied the other's segment reports — one part of a multipart send could be confirmed, or failed, by an unrelated message — and a late report from a send that had already timed out landed the same way against whichever send was in flight. PendingIntent identity is requestCode plus Intent.filterEquals, and filterEquals ignores extras, so call B's segment-0 intent was call A's; with FLAG_IMMUTABLE the extras cannot be updated, so B was simply handed A's intent. The action now carries a per-call UUID (smsSentReportAction(callId)), which scopes the IntentFilter to one call and makes two calls' segment intents unequal, and the receiver re-checks the action before counting a report as defence in depth. RequestCodes stay per segment and restart at 0 per call, which is safe now that the action carries the call's identity. The receiver was already unregistered in a finally on completion and on timeout; that half now has a test. Tests: ActionExecutorSendSmsTest (9 → 13) — two overlapping sends listen on different, UUID-suffixed actions; a foreign report leaves the send queued_unconfirmed instead of turning it into a definite failure; a report on the call's own action is still counted (so the filter cannot deafen the receiver); and the receiver is unregistered exactly once.
  • android_send_sms no longer invites the retry that duplicates the message. When no send report arrived inside the 10 s window the tool answered success: false — but the message had already been handed to the radio (sendTextMessage returned without throwing), and a missing report is what a device on one bar of signal, a sleeping modem or an OEM that does not fire sentIntent produces routinely. false reads to an agent as "it failed, try again", so the recipient got the same SMS twice, and three times when the retry also timed out. The outcome is now success: true with data.status: "queued_unconfirmed" and a message that says delivery is unconfirmed and do not resend, because a retry would duplicate it. success: false is reserved for a report that definitively says the send failed (RESULT_ERROR_*, and an unknown non-OK code, which is still a definite report), where a retry is safe. Every outcome now carries a machine-readable data.status — sent, queued_unconfirmed, failed — plus the segment count, so a caller does not have to parse prose to tell the two apart; the pre-send refusals (no accessibility service, no SEND_SMS, no telephony, platform rejection) are unchanged and still success: false, since nothing reached the radio. The tool schema, its docstring, docs/troubleshooting.md and the SMS section of skill.md/SKILL.md all state the do-not-resend rule where an agent will read it. Tests: SmsSendReportTest (16), ActionExecutorSendSmsTest (9); red-green verified, and the PII cases still pin that no outcome echoes the recipient or the body.
  • POST /send_sms no longer blocks the transport's thread while it waits for the radio. ActionExecutor.sendSms parks a thread on a CountDownLatch for up to smsSendReportTimeoutMs (10 s) so it can report what the modem actually did rather than what sendTextMessage queued, and CommandDispatcher.dispatch called it inline. dispatch is a suspend function, so "inline" means on whatever thread the caller is on: over direct HTTP that is a Netty event-loop thread shared with every other connection on that loop, so one SMS sent with no signal stalled /ping, /screen and the event stream for ten seconds; over the relay it is a Dispatchers.IO worker the message-handler coroutine gave up. The call now runs inside withContext(Dispatchers.IO), the same shape /contacts and /screen_record already used, through a new CommandDispatcher.smsSender seam modelled on batteryContext. Not converted to suspendCancellableCoroutine + withTimeout: that would make sendSms suspend and rewrite the executor's whole non-suspend contract plus its eleven synchronous test call sites, to save a thread from a pool whose entire purpose is blocking calls. Tests: CommandDispatcherSendSmsTest (11) — the send is observed running on a DefaultDispatcher-worker thread and never on the caller's, and the recipient and body still arrive unchanged.
  • The Termux revival watchdog's auth-failure classification now describes one attempt. maybeFireTermuxRevival reads lastFailureHttpCode to decide authFailure — a 401/403 means "a credential problem, restarting Termux cannot fix it", so the watchdog declines to spend its fire budget. Two ways the field held a value from somewhere other than the attempt being judged: nothing reset it per attempt (nor per connect() cycle), so a code recorded earlier was still sitting there when exhaustion was reached through onClosed, which writes nothing at all; and onFailure checked myGeneration != generation and then assigned, outside the monitor, so a superseded socket's callback could pass the check on an OkHttp thread, be descheduled, and write after the attempt that replaced it had connected and reset the field. A stale 401 does not just mislabel a log line, it switches the recovery path off for the whole cycle. connect() and beginReconnectAttempt() — the only two callers of connector, so the only two places an attempt starts — now clear it, and the write goes through a guarded @Synchronized recordFailureHttpCode(attemptGeneration, httpCode). Tests: RelayClientFailureClassificationTest (4), mutation-checked by dropping the guard and the resets.
  • RelayUrl now treats 100.64.0.0/10 as private. RFC 6598 shared address space is what carrier-grade NAT uses and what Tailscale assigns to every tailnet node, so a relay reached at 100.111.22.33 was classified public and dialling it over ws:// drew the red "anyone on the network path can read AND inject commands" warning for a private overlay network the user owns — on a path where no CA will issue a certificate for the address anyway. Since the scheme default is now explicit-only, this changes the warning, not the connection. isPrivateHost is the warning's only consumer. Tests: RelayUrlTest (14).
  • ScreenNode.computeHash() length-prefixes each field instead of joining raw values with an unescaped |, so field content can no longer shift the layout: text = "X|Y", no description and className = "C" hashed identically to text = "X", contentDescription = "Y", className = "null|C". An injectivity hole in the value /screen_diff trusts to report "no changes" — and a silent one, since the forged pair reports an unchanged screen. Unlikely to be hit by accident (the neighbouring fields have to be shaped just so), but the separator is attacker-influenced: it comes straight from app-supplied text and content descriptions. Every hash changes once on upgrade. Hashes are not stored on-device — /screen_diff compares against the previousHash the caller supplies — so the only effect is that a hash obtained before the upgrade never matches one computed after it, and the first /screen_diff across the upgrade reports "Screen changed" for an unchanged screen. The shape is unchanged (16 lowercase hex chars, first 8 bytes of SHA-256), so no caller or log format needs updating.
  • ScreenRecorder.record() released nothing when configuring the MediaRecorder or its prepare() threw: recorder = mr ran only after the apply {} block returned, so cleanupRecording() in the catch saw a null field and the native recorder (encoder + projection client) leaked. Reachable on a real device whenever prepare() fails — codec unavailable, storage full, invalid surface — and the next capture then failed with the recorder still held. The recorder is now published to the field before it is configured, so every failure path releases it; the VirtualDisplay needed no change, already being assigned the moment it is created.
  • EventStore.add() no longer throws NoSuchElementException out of onAccessibilityEvent when maxCapacity is 0 or negative. The eviction guard read size >= maxCapacity as "at capacity" and called removeLast() on an empty deque; a non-positive cap now means "retain nothing" and the event is dropped. Chosen over clamping the cap to 1 because it is the smaller change and honours the knob as written — a floor of 1 would silently retain an event the caller asked not to keep. The volatile knob is read once per add, so a concurrent write cannot desynchronise the guard from the eviction loop. Lowering maxCapacity also trims an oversized backlog down to the new cap on the next add instead of serving the old entries until they happen to drain. Surfaced by the new EventStoreTest coverage; not reachable in the shipped app, which never writes maxCapacity.
  • Dismissed notifications no longer evict live ones from the shared buffer. markRemoved retains entries in the same ArrayDeque that add evicts from at maxCapacity (raised to 300 by BridgeNotificationListener), and eviction was removeLast() — the oldest entry, which on a busy day is the long-lived isOngoing one: a music player, navigation, the bridge's own mic notification. Since the default read filters dismissed entries out, they consumed capacity only the opt-in include_removed path could see, so 300 arrivals-and-dismissals pushed out a notification the user could still see in the shade and android_notifications() reported it missing. add now prefers the oldest dismissed entry for eviction and falls back to oldest-first only when nothing is dismissed, so the buffer stays bounded either way. Before dismissal retention was added the buffer held live notifications only, so this restores that property rather than changing it.
  • android_mic_status() no longer reports a transient phase: error for a recording that is complete and downloadable. onDestroy reset any active phase, and isActive includes FINALIZING — but the finalisation block has no suspension points and owns both of its terminal states, so it always reached markReady and overwrote the ERROR. The final state was correct; the window was not. android_mic_stop() stops the service, so the stop path races the finaliser routinely, and CommandDispatcher serves latest from disk regardless of phase — an agent polling in that window saw {"phase":"error","error":"Recorder service was destroyed before completion"}, reported a failed recording, and never called android_mic_fetch(). docs/manual-tests.md step 12 ("wait for android_mic_status() to report ready") would hang on that run. Both reset sites now use a new isAwaitingRecorder (STARTING/RECORDING only): onDestroy, and requestStop()'s #98 branch, which had the same defect for a second STOP arriving while the first was finalising. #98 stays fixed — a service destroyed before the loop starts is in STARTING and is still reset.
  • Both transports now answer a route failure the same way. CommandDispatcher is documented as the single source of truth shared by the relay and the HTTP server, and both did call it — but only the relay caught. RelayClient.handleMessage wrapped dispatch and answered {"error": …} at 500; BridgeRouter had no try/catch and BridgeServer installed only ContentNegotiation, so an exception escaped to Ktor's default handler as a non-JSON 500. A tool that parsed the body therefore worked over the relay and broke over direct USB/LAN for the identical request. dispatch now owns the contract — a JSON object with an error key at 500 — and BridgeRouter guards the routes that run outside it (/mic_file). The value is the exception's class name, never its message, which can carry an SMS recipient, a file path or a host:port. ktor-server-status-pages is not a dependency, so the guard is in the router rather than a StatusPages block. Tested at both layers, including a real Netty engine on an ephemeral port answering POST /open_app with a JSON 500.
  • android_send_sms no longer reports success for messages that were never sent. sendTextMessage(to, null, body, null, null) passed null for both sentIntent and deliveryIntent, so no send status was ever observed and sendSms returned ActionResult(true, "SMS sent") unconditionally — sendTextMessage returns as soon as the message is queued, not when it is sent. Bodies over the single-segment limit were never divided either, so they failed at the radio layer with nobody listening. An agent sending a 300-character SMS was told it was delivered, told the user so, and — because the recipient and body are stripped from the response by design — had nothing in the tool output to contradict the claim. It now divides with divideMessage, sends via sendMultipartTextMessage when there is more than one segment, supplies one sentIntent per segment, and waits (bounded, 10s) for the radio's report: success: false with the named reason on a radio failure, and an unconfirmed outcome when no report arrives (see the queued_unconfirmed entry below for how that is reported). POST /send_sms answers 400 on a blank to/body — previously it defaulted both to "", AOSP threw IllegalArgumentException whose message quotes the destination address, and the exception escaped the dispatcher as a 500. The PII convention holds: no outcome echoes the recipient or the body, and the new segment count is the only send detail surfaced.
  • The post-revival delayed reconnect now runs on a scope that survives disconnect(). fireTermuxRestart() launched it on the per-connection scope, and when that coroutine fired 30 s later it called connect() — whose first statement is disconnect(), which does scope?.cancel(); scope = null, cancelling the very scope the caller was running on. It only worked because nothing between disconnect() and the end of doConnect() suspends, so cancelling the enclosing job could not interrupt synchronous code. The first suspension point added to either function — withContext(Dispatchers.Main) to update the UI, an await on DNS — would make it throw CancellationException, abort the reconnect silently, and leave the watchdog firing the script but never reconnecting: the exact bug the call site's comment claimed was fixed. It now launches on an object-level revivalScope with its own SupervisorJob. That scope outliving the session is the point, but it is not the whole fix: a scope nobody cancels meant a pending reconnect nobody could stop, so a user who tapped Disconnect — or Connect against a different relay — while the watchdog's 30 s timer was running was silently overridden by a dial they had already cancelled, and shouldReconnect = false was ignored. The job is now tracked in revivalReconnectJob, cancelled by disconnect() and at the top of connect() (before the pairing-code check, so a connect that bails out still cancels the stale dial), and re-checked against shouldReconnect when the timer expires. The coroutine clears its own handle under the same monitor before calling the connector, which is what preserves the original intent: the reconnect is never cancelled by the connect() it makes. reconnectDelayed() re-arms shouldReconnect when it schedules, because its only caller is the exhausted-budget path that has just cleared it. RelayClientRevivalReconnectTest (6) drives virtual time through the seam to pin all of it: the reconnect fires after exhaustion, a user disconnect cancels it, a newer manual connect supersedes it, the scope still outlives disconnect(), and the real connect() from inside the coroutine still reaches doConnect.
  • The Termux revival watchdog no longer ships one contributor's private deployment path. RelayClient hardcoded /data/data/com.termux/files/home/.termux/boot/start-zee.sh — a personal stack launcher, in a public repo and a public APK, not configurable and not documented. Any other user who enabled the Termux Auto-Revival switch because their relay kept dropping had the bridge fire RUN_COMMAND at a script that did not exist on their device: Termux logged an error, the app showed "Stack unreachable — firing Termux revival…", nothing recovered, and the user believed auto-recovery was on. The script is now RelayClient.DEFAULT_REVIVAL_SCRIPT, the same location with a project-named script (start-hermes.sh); the location is unchanged so the file still doubles as a Termux boot script. No new UI — the path stays a constant, and the docs now say plainly to leave the switch off unless that exact file exists. docs/configuration.md, README.md, docs/architecture.md and a new docs/troubleshooting.md section cover the toggle, the Allow external apps requirement, the default path and the fire budget. The intent construction moves into termuxRevivalIntent() so it is testable: TermuxRevivalIntentTest pins the action, target component, all four extras and the path shape, closing the gap where maybeFireTermuxRevival/fireTermuxRestart had no coverage at all.
  • The Termux revival watchdog is now bounded. Its only limits were WATCHDOG_FAILURES_TO_TRIGGER = 3 and a 10-minute cooldown, and Fire reset the counter to 0 — so a relay that was merely unreachable (wrong server URL, rotated pairing code, server down for the weekend) made an opt-in device execute a shell script every 10 minutes indefinitely, each cycle also spawning a delayed reconnect. RevivalPolicy gains a fire budget (maxFires, default 3 — roughly 30 minutes of automatic recovery) and returns a new Exhausted decision once it is spent; a successful connection re-arms it, so a later unrelated outage is not ignored for the rest of the process lifetime. An HTTP 401/403 no longer counts as a watchdog failure at all: restarting Termux cannot fix a credential problem, and spending the budget on one would mask the outage a restart could have fixed. The status line now carries the attempt count (firing Termux revival (2/3)) and reports once when the watchdog gives up, instead of the user believing auto-recovery is still running.
  • Tool error responses no longer leak the bridge host:port or the request URL. 39 of the 40 network tools answered a transport failure with json.dumps({"error": str(e)}), and requests puts HTTPConnectionPool(host='…', port=8766): Max retries exceeded with url: /contacts?query=Jane+Doe… in that text — so a failed call returned the server IP plus, for the GET tools whose arguments travel in the query string, the caller's own PII (android_search_contacts' contact name, android_notifications/android_events params). A single shared _safe_error() helper now renders the exception class plus a generic reason (connection refused / timed out / HTTP status) and is used at every error-return site, extending to all tools the redaction android_mic_fetch has had since #99. The two message kinds that carry nothing to hide survive verbatim: the bridge's own error body on an HTTP error ("SEND_SMS permission not granted" stays actionable) and any non-requests exception (a local OSError, a handler's TypeError).
  • android_ping no longer reports status: "ok" for a 200 whose body is not JSON. _extract_response turns an undecodable body into {"error": "<raw text>"} and hands it back as if it were data, so a reverse proxy answering /ping with an HTML 502 page produced {"status": "ok", "bridge": {"error": "<html>502 Bad Gateway</html>"}}. Agents read status == "ok" as "the bridge is healthy" and stop looking — the wrong signal precisely when the relay is returning somebody else's error page. The same now applies to a 200 carrying a JSON {"error": ...} body.
  • android_macro no longer raises on a malformed step. The loop read step.get("tool") outside the try that turns handler failures into {"error": "Step N …"}, so a model that sent ["android_tap"] or [null] instead of [{"tool": "android_tap", "args": {}}] got an AttributeError out of the tool call — an unhandled exception aborting the agent turn rather than a readable step failure. Steps are now validated inside the per-step error handling (step is an object, tool is a string, args is an object), and a steps argument that is not a list at all is reported too instead of raising TypeError from enumerate(None) — or, worse, iterating a bare string one character at a time.
  • stop_relay() no longer raises RuntimeError("Event loop is closed") after a failed start_relay(). start_relay() registered _relay_instance before the readiness handshake and left it registered when that handshake timed out (port taken, loop died), while _run_loop() closes its loop in a finally — so the very next stop_relay(), the teardown every caller wraps around a start, called call_soon_threadsafe() on a closed loop and blew up instead of shutting down. A failed start now rolls _relay_instance back, and stop_relay() tolerates a loop that is already closed (including one that closes between the check and the signal) rather than letting the exception escape the caller's cleanup.
  • HTTP error bodies are no longer double-encoded in tool responses. _extract_response() serialises the bridge's error body into the HTTPError it raises so that the text survives, and every caller then filed it under an "error" key of its own — producing {"error": "{\"error\": \"not paired\"}"}, a JSON document inside a JSON string, for the failure agents most need to read (an unpaired relay, a denied permission). _safe_error() now takes the one wrapper back off, so that case returns {"error": "not paired"}. Only a body consisting of exactly that single key is unwrapped: a bridge sending {"error": ..., "code": ...} keeps both fields rather than having one dropped for tidiness.
  • Every documented ANDROID_* variable now falls back to ~/.hermes/.env, and android_setup no longer clobbers a port the user configured. docs/configuration.md presented all of them under one "Config lives in ~/.hermes/.env" table, but only ANDROID_BRIDGE_URL and ANDROID_BRIDGE_TOKEN went through _env(); ANDROID_RELAY_PORT, ANDROID_BRIDGE_TIMEOUT, ANDROID_RELAY_HOST, ANDROID_RELAY_CERT and ANDROID_RELAY_KEY were plain os.getenv. That is exactly the process android_setup starts the relay in — a gateway that loads .env for its own config without exporting it — so ANDROID_RELAY_PORT=9000 in the file was ignored, the relay bound 8766, and setup then wrote 8766 over the user's 9000. ANDROID_BRIDGE_TIMEOUT=120 was ignored the same way, timing long android_wait/screen_record calls out at 30s. android_relay.py gets its own _env() rather than importing the tool's, so it still runs standalone on a relay host; both copies stay byte-identical. android_setup also resolves the file it writes with _hermes_home(), the same way the reader does — it used Path.home(), so it wrote where nothing looked, and the test suite silently created a real ~/.hermes/.env on every run.
  • android_send_intent no longer advertises calls the bridge refuses. Its docstring and schema description recommended android_send_intent("android.settings.WIFI_SETTINGS") and promised "setting toggles" — but ActionExecutor.sendIntent blocks that action twice over (explicit blockedIntents entry plus the android.settings. prefix rule), and the data_uri hint tel:+1234567890 used a denied URI scheme. An agent following its own tool description was refused on the first thing it tried, then told the user it could not control the device. The examples are now an https:// ACTION_VIEW deep link, the blocklist is stated in the description, and the working path for settings (android_open_app("com.android.settings") then tap) is named. Applied to both android_tool.py copies. tests/test_send_intent_docs.py derives the advertised examples from the schema and docstring and fails if any is a blocked action or a denied URI scheme, and pins the two copies together.
  • A failed register_skill in the plugin is now reported instead of silently swallowed. register() wrapped it in except (AttributeError, TypeError): pass, justified as "hermes-agent older than the register_skill API" — but AttributeError is also what a missing skill.md produces and TypeError is also what a renamed path= kwarg produces. The plugin folder is copied by hand (install.sh, the cp -r steps in README.md), so a copy without skill.md showed ✓ hermes-android v0.5.0 (42 tools) in /plugins while the accessibility-tree-first guidance never loaded — the agent silently regressed to screenshot + vision, the exact behaviour the feature exists to prevent, with nothing in the log to explain it. Each failure mode is now checked separately: hasattr for a genuinely old API (info), an is_file() check for a broken install (warning naming the path), and logger.exception for anything else, so the tools always survive but the reason always reaches the log.
  • Wake-key test coverage restored (android_press_key("wake"), #101). 6fe8444 added three behavioural assertions to WakeLockManagerWakeTest; aa17e70 deleted all three and kept only assertTrue(wake()). That is no coverage at all: wake() returns true unconditionally once a PowerManager is present, so the suite passed for any acquireWakeLock() that did not throw — including one that acquires nothing, one that drops ACQUIRE_CAUSES_WAKEUP (press_key("wake") reports {"success":true} while the screen stays black), and one that calls acquire() with no timeout (the lock is held forever on a device meant to be always-on). The assertions are ported to the Robolectric 4.11 API — ShadowPowerManager.getLatestWakeLock() plus Shadow.extract for the tag, hold count and isHeld, since Shadows.shadowOf() has no PowerManager overload — and the flags and timeout, which no shadow exposes, go through a new WakeLockManager.powerManager test seam modelled on CommandDispatcher.batteryContext. Verified by mutation: dropping ACQUIRE_CAUSES_WAKEUP and the timeout fails 3 tests, and making acquireWakeLock() a no-op fails 7.
  • One source of truth for the Python package version. setup.py repeated version, install_requires and python_requires from pyproject.toml, and the commit titled release: v0.5.0 bumped pyproject, plugin.yaml and build.gradle.kts but left setup.py at 0.4.1 — fixed one commit later, with nothing in CI checking either. A release cut from a tree where they disagree publishes metadata whose version depends on the build path: python setup.py --version reported setup.py's value while a PEP 517 build read [project]. setup.py now carries only the packaging hints [project] does not express (packages, package_data) and inherits the rest; tests/test_version_consistency.py pins the installed dist metadata, plugin.yaml and the APK's versionName to pyproject.toml, and fails if a version=/install_requires= returns to setup.py. docs/RELEASING.md steps 2–3 updated — they did not mention build.gradle.kts at all.
  • python.yml now also triggers on pull_request for changes to .github/workflows/python.yml itself. The path was in on.push.paths but missing from on.pull_request.paths, so a PR that only edited the workflow — adding a Python to the matrix, changing the pytest invocation — ran no check at all and the breakage landed on main to be discovered by the next unrelated PR touching tools/. tests/test_python_workflow.py pins the two trigger lists together so they cannot drift again.
  • Relay route allowlist lifted out of _serve() to module level (_ROUTES) so tests can assert on it. docs/architecture.md is now pinned to the allowlist in both directions, and the two android_relay.py copies are pinned byte-identical. An endpoint added to CommandDispatcher without the matching allowlist entry used to fail silently: reachable over direct USB/LAN, refused over the relay — which is the default transport (#103).
  • The Python test suite can no longer reach the real ~/.hermes/.env. tests/conftest.py redirected it by setting HOME and HERMES_HOME to a throwaway directory, but Path.home() and os.path.expanduser("~") fall back to pwd.getpwuid(os.getuid()).pw_dir — the real home — whenever HOME is absent from the environment, which puts android_setup()'s credentials write and _env_file_vars()' pairing-token read one delenv (or one runner without HOME) away from the developer's own files. The autouse fixture now patches the ~ lookups themselves, replacing only the pwd fallback so an explicitly set HOME still wins, and a regression test asserts the redirect holds with both variables deleted.

Security

Remediation of the 2026-09-29 security audit. Every High finding, the .env injection, the sendIntent denylist gaps and the small/local Mediums are fixed, each with a regression test.

  • Pairing-code rotation now takes effect (AUTH-1, High). PairingManager is the single source of truth on the device: the duplicate relay_pairing_code store is gone (and cleared from prefs on upgrade), so Regenerate drops the live relay session and re-dials presenting the new code, and the UI says which of those happened instead of implying success. On the server, android_setup pushes the code to an already-running relay (start_relay is a no-op once the thread is alive) and closes any session authenticated with the old one. Before this, an attacker holding a leaked code kept full device control indefinitely after the user "rotated" it.
  • Password fields are redacted instead of serialised (PII-1, High). AccessibilityNodeInfo.isPassword was not consulted anywhere, so a login screen driven by the agent put the user's password — or the OTP the IME had just auto-filled — into /screen, /find_nodes, /describe_node and /events, and from there into the transcript and the model provider. One choke point (security/SensitiveText) now emits "[redacted]" for those nodes, drops their contentDescription/hintText, keeps the node itself addressable (id, class, bounds, editable) and flags it password: true; text searches match the redacted value, so /find_nodes cannot be used as an oracle. Screenshots and screen recordings are pixels and remain unredacted — documented in SECURITY.md.
  • Plaintext transport is no longer the silent default (TRANS-1, High) — see Changed. SECURITY.md's threat model now says what plaintext actually costs: a ws:// WebSocket has no integrity protection, so an on-path attacker can append frames to the established stream and have the phone dispatch them as authenticated commands, without holding the pairing code at all.
  • android_setup validates the pairing code (PY-1). The value was interpolated raw into ~/.hermes/.env, which is parsed as key=value lines and read back by _bridge_url() — so one crafted argument could re-point every later tool call at an attacker host with the real Bearer token attached. Codes must now match the alphabet and length the phone generates ([A-HJ-NP-Z2-9]{6,32}), the rejection message never echoes the credential, _update_env_file independently refuses CR/LF values and non-NAME keys, and the write is atomic at 0600 from creation instead of write-then-chmod (which left the token world-readable in between). The fallback path also honours HERMES_HOME, matching where the token is read from.
  • sendIntent denylist gaps closed (CTRL-2). sms: and mms: join the blocked schemes; the content:// prefix list grows from two entries to fourteen (SMS, MMS, MMS-SMS, call log, telephony, contacts, ICC and the AOSP authorities); and the URI is trimmed and lower-cased before the check, so " tel:+19005550100" and " content://sms/inbox" are no longer bypasses.
  • MEDIA temp files are deleted (PY-2). Screenshots, screen recordings and microphone WAVs were written with delete=False and never cleaned up, leaving rendered content from arbitrary apps in the temp dir for the lifetime of the filesystem. They are now registered on creation, deleted at process exit, and stale leftovers from crashed runs are swept once per process — without ever touching a file another session may still be relaying.
  • /wait and /screen_record durations are clamped (RES-1). An unclamped timeoutMs let a malicious relay (or anyone who can inject into a plaintext session) park a coroutine walking the accessibility tree every 500 ms for ~24.8 days, long after the caller's own 30 s timeout. /wait is now capped at 120 s — above every timeout a legitimate caller can observe — and /screen_record gained the minimum clamp it was missing, so a negative duration is rejected at the boundary instead of throwing inside Thread.sleep.
  • A non-ASCII Authorization header is a counted rejection, not a 500 (AUTH-5). hmac.compare_digest raises on non-ASCII str and neither relay call site was wrapped, so garbage traffic produced an unauthenticated 500 and skipped the rate-limit accounting. Both now compare UTF-8 bytes through a helper that cannot raise.
  • SECURITY.md and README describe the shipped product (DOC-1). The capability list was five items; the real surface includes microphone recording, screen video, SMS, calls, contacts, GPS, clipboard read/write, notifications including dismissed ones, event history, arbitrary intents and broadcasts, and Termux script execution — now a capability → endpoint → permission table. "The phone is never directly exposed" was false (:8765 binds 0.0.0.0 at app start with no toggle) and is corrected.
  • dataUri is now redacted in the relay's DEBUG request-body log. android_send_intent sends the URI under dataUri — a key _SENSITIVE_BODY_KEYS did not contain — so a SENDTO deep link logged smsto:<full phone number> verbatim and an https one could leak an embedded reset token, against the AGENTS.md rule to strip phone numbers and recipients from responses and logs. docs/troubleshooting.md tells users to raise the log level to DEBUG to inspect commands, so this was the default path to a phone number in a log file. action and packageOverride stay readable: they name a verb and an app, not a person. A new test derives the payload keys from android_send_intent itself, so a field added later fails until it is classified rather than leaking by default.
  • Test-suite hygiene found while fixing the above: the Kotlin suite was red on a clean checkout because runTest's 10 s real-time dispatch timeout tripped on cold mockk proxy generation, and pytest was overwriting the developer's real ~/.hermes/.env on every run.