Repository navigation
[0.6.0] - 2026-12-02
Added
GET /battery— battery percentage and charge state straight fromBatteryManager(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 atminSdk 26neither needs a version gate. Fixed response shape —batteryPercentageandcharging, 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, thesincecursor, streaming-flag semantics, concurrent add/read),BatteryMonitor(an unreadable, out-of-range or throwing battery service must read asnull— 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) andScreenNode/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()callsremoveLast()on an empty deque whenmaxCapacity <= 0, so the first event after such an assignment throwsNoSuchElementExceptionout ofonAccessibilityEventinstead of being dropped. Not reachable today (nothing in the app writesmaxCapacity), but the knob is public.ScreenRecorder.record()never releases theMediaRecorderwhen its configuration orprepare()throws:recorder = mris assigned only after theapply {}block returns, socleanupRecording()in the catch sees a null field and the native recorder (encoder + projection client) leaks. Reachable wheneverprepare()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_diffuses to decide nothing changed. Fixing it changes every hash; see Fixed below for the one-time upgrade impact.
ScreenRecordergained aninternal maxDurationMstestability seam (default unchanged at 30 s), same pattern asCommandDispatcher.batteryContext: the cap is otherwise only observable by waiting out a full capped recording.
Changed
ActionExecutorandCommandDispatcherare 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.ActionExecutoris now a 135-line facade whose every public action delegates, with the implementations in focusedinternal 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(includingdescribeNode's PII-1 boundary) andTtsExecutor.CommandDispatcherkeeps what made it the single source of truth — the error contract, thebatteryContext/smsSendertest seams, the RES-1 clamps and the complete 40-entry(method, path)routing table — with only/pingand the 404 arm still carrying behaviour inline; the other 39 arms delegate toScreenCommands,InputCommands,AppIntentCommands,DeviceCommands,NotificationCommandsandMediaCommands.
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:smsSendReportTimeoutMsandsmsSentReportActionkeep delegating members onActionExecutorwhile 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 beingroute()itself) and all 40 route-arm bodies hash identically once five enumerated, purely mechanical rewrites are applied — a sibling-object qualifier, a moved member losingprivate, a handler's trailing expression gainingreturn, and the two seam accessors.- The relay URL scheme you type is the scheme the app dials — and
android_setupnow prints one.RelayUrlmapshttps:///wss://→wss://and everything else, including a barerelay.example.comor203.0.113.7:8766, →ws://: the behaviour every stored URL already relies on. An intermediate rule on this branch defaulted a bare public host towss://, and it is reverted here because the relay only terminates TLS whenANDROID_RELAY_CERT/ANDROID_RELAY_KEYare set whileandroid_setuptold the user to type a barepublic_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, soandroid_setupnow printswss://ip:portwhen the relay has one andws://ip:portwhen it does not, andget_relay_url()reportshttps://for a TLS relay instead of hardcodinghttp://(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 untilandroid_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 andGET /eventsserved them while reportingstreaming: 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), andandroid_broadcastno longer suggests a protected system broadcast; the intent description now states the boundary and points atandroid_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,waitForElementpolls by light search, locations reportageMs/stale, contacts run onePhone.CONTENT_URIquery, 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 theeventpath segment (#17); the file-levelunusedsuppression is removed (#56); the Python toolset has a logging@_toolwrapper, strict unknown-kwarg dispatch, macro guardrails (step cap, no nested macro/setup, configurable delay/timeout), a ping cache, batched atomic.envwrites, and recursive substring PII redaction (#11, #26, #27, #36-40, #50, #59, #60);start_relayupdates-or-restarts instead of silently keeping stale credentials (#4);android_setupwarns on localhost-bound relays and no longer echoes the code (#5, #39); the plugin copies are generated bytools/build_plugin.py --checkfromtools/as canonical (#3, #51);ruff checkgates the Python CI job (#37);requirements.txtand the orphanedstitch-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: forcedwss://+ 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 hardenedcomputeHashwith 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:testDebugUnitTest568/0 +assembleDebug/assembleRelease;pytest1953 passed;ruff checkclean;build_plugin.py --checkin sync.
Fixed
android_pinchno 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 reach50 * scalepx either side of the centre — sopinch(x = 50)at the default scale 1.5 put the left finger's end at50 - 75 = -25and threw out ofActionExecutor.pinchbeforedispatchGesturewas 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.topis checked by the same constructor, so a negativeyreached 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 = 50at the default scale,x = 0where both left-hand coordinates clamp,y = -10for the top edge, andx = 20withscale = 4to pin that the clamp tracks50 * scalerather than a hardcoded margin. Red-green verified: all four fail beforehand with exactly that message.RelayClient.revivalReconnectJobis read-only outside the object. F32 widened it fromprivatetointernalsorevivalReconnectMayDialcould 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 jobreconnectDelayed()had never scheduled. Three of the predicate tests did exactly that: they assigned a bareJob()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 nowinternal var … private set: still readable for the tests, assignable only byreconnectDelayed(),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 therevivalScope'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 andshouldReconnectstill armed, which is precisely the combination F32 exists for; the superseded case firesreconnectDelayed()twice and asserts the two handles differ; the cleared case assertsdisconnect()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-addingRelayClient.revivalReconnectJob = Job()to the test now fails with "Cannot assign to 'revivalReconnectJob': the setter is private".android_setupreadsANDROID_RELAY_PUBLIC_HOSTonce. F34 skipped the IP-echo calls by reading the variable inandroid_setupitself, 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 setANDROID_RELAY_PUBLIC_HOSTto 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_envspy counts exactly one read ofANDROID_RELAY_PUBLIC_HOSTacross a wholeandroid_setup; a configured bare IP under TLS gets the note; a configured hostname does not. 10 fail before the change.- The
queued_unconfirmedmessage no longer contradicts the tally beside it.describe'snullbranch said "no send report arrived within 10000ms", butnullfromawait()only ever meant the bound ran out with no failure recorded — segments could have confirmed, anddata.deliveredin 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 ondelivered: 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 atawaitTally, the read that carries the counts.
The tool docstring (both copies) now says plainly thatqueued_unconfirmedcovers 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.mdgains both variants and points at thedeliveredcount. Tests:SmsSendReportTest(32 → 34) — the message agrees with the tally for zero and non-zerodelivered, quotes "2 of 3", still forbids the resend, and a single-segment send keeps the original wording; plusTestSendSmsOutcomeDocumentation(5, both copies) pinning that the docstring and the schema description name all four statuses, sayqueued_unconfirmedcovers segments that never reported, and say onlyfailedis 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-widewarnings.filterslist 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 singlewarnings.filterwarnings("ignore", category=InsecureRequestWarning, message=...)whose message regex is pinned to exactly the hosts_bridge_tls_verify()relaxes for:localhost,127.0.0.1,::1and[::1]. Narrower than either predecessor — an unverified request to any other host still warns, includinglocalhost.example.comand127.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").hostreturns'[::1]', brackets included, and that is the string urllib3 interpolates into the message. Installation is idempotent by inspectingwarnings.filtersrather than by a module flag, because a flag goes stale the first time anything else legitimately replaces the filter list —catch_warningsdoes 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 makesverifyand the filter impossible to forget at a new call site. The context manager and thecontextlibimport are gone. Both copies.
Tests:TestBridgeTlsVerification(26 → 32), replacing F33's two context-manager cases. Every host form is re-derived throughparse_urland 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 blanketInsecureRequestWarningignore anywhere in the filter list; a verified call installs nothing; and_loopback_tls_warnings_suppressedis 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.
sendSmscalledreport.await(timeoutMs)and then readreport.confirmedPartsandreport.reportedPartsas two separate calls — and the receiver is still registered when the bound runs out, because unregistering happens in thefinallyafterwards. ARESULT_OKlanding between the two reads producedconfirmed = 0, reported = parts, which is exactly the shapedescribemaps tostatus: "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.reportedPartswas itself a sum of twoAtomicIntegers taken at different instants, so it could describe a moment that never existed.
The three counters now sit behind one lock,SmsSendReport.Tallyis an immutable snapshot of all of them plus the latch's completeness, andawaitTally(timeoutMs)returns it at the instant the wait ends.describe(tally, parts, timeoutMs)is the race-free entry point;await()is nowawaitTally(...).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. RevertingActionExecutorto 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:unregisterReceiverdoes not synchronise with anonReceivealready running on another thread, so it narrows the window instead of closing it, and it would need a flag to stop thefinallyfrom unregistering twice. Tests:SmsSendReportTest(28 → 32) — a snapshot taken before a late report is not moved by it while a fresh one is, anddescribeon that snapshot answersqueued_unconfirmedwhere the split read answersfailed(both asserted, so the contrast is the regression test);awaitTallyagrees withawaitand reports completeness; a bound that ran out reports itself incomplete; and 500 reports written from a second thread are snapshotted in a tight loop withconfirmedPartsnever exceedingreportedPartsand never exceeding the segment count. RelayClientno longer writes exception messages from the message-handling path into logcat. F26 fixed the 500 response to useCommandDispatcher.errorBody(), and left the log line right beside it emitting"Error handling message: ${e.message}". That catch wraps the JSON parse, therequest_idcheck and the/mic_filestream, and aJsonSyntaxExceptionfrom a malformed command can quote the command — which for/send_smscontains the recipient, and for/mic_filea 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 nameerrorBodyhands the caller, so the two cannot drift, and attaches no throwable —Log.e(tag, msg, tr)appendsLog.getStackTraceString(tr), whose first line isclass: 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"interpolatedtoString(), i.e. the message, and now logs the class name. The threeLog.*(msg, throwable)calls left alone are audited in a comment —startForeground'sSecurityExceptionand the two TermuxstartServicefailures carry framework text about our own fixed intent, never device content.onFailure's"WebSocket failure: $errorDetail"keepst.messagedeliberately: 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.mdrecords the logcat rule next to the response one. Tests:RelayClientLogRedactionTest(5, new) reads the line back through Robolectric'sShadowLog— a recipient and a body in the message appear in neithermsgnor an attached throwable, aFileNotFoundExceptionpath does not leak, a message-less exception still logs a usable name with no literalnull, the anonymous-classifBlankfallback does not echo the message, and the logged name equalserrorBody's; plus an end-to-end assertion inRelayClientRelayTest(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_setupno longer calls out to third-party IP-echo services when the operator has already named the host._get_public_ip()triesapi.ipify.org,ifconfig.meandicanhazip.comat 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 momentANDROID_RELAY_PUBLIC_HOSTwas 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.envcannot producews://:8766). Both copies. Tests:TestAndroidSetup(+4) — no detection call with the host configured underws://orwss://, 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()calledurllib3.disable_warnings(InsecureRequestWarning), which rewrites the process-widewarnings.filterslist and never restores it. This module runs inside a long-lived gateway, so oneandroid_ping()against anhttps://localhostbridge silencedInsecureRequestWarningfor 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 becamewarnings.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 theverifydecision (F19) and the suppression, so a new call site cannot forget either. That scoping was itself replaced one review later —catch_warningsswaps 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.filtersis unchanged after an https-loopback ping and after a plaintext one, noignorefilter forInsecureRequestWarningsurvives, 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, anddisconnect()/connect()are both@Synchronized: a user who disconnects and then reconnects while it was queued leavesshouldReconnecttrue, because their ownconnect()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 handlereconnectDelayed()last published, and the flag is armed. The coroutine takes its ownJobfromcoroutineContextand passes it in, still inside the monitor the dial runs under, so F25's one-step property is unchanged.revivalReconnectJobbecomes 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_wscompared the presented token againststate.pairing_codeand then, a few lines later, readstate.pairing_codeagain 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-preparere-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 andprepare; this closes the one inside the check itself.expected_codeis now read once and used for both the constant-time comparison andauthenticated_with. Both copies. Tests:TestRotationDuringHandshake(3 → 4) — a hook on_tokens_equalrotates 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 withPOLICY_VIOLATION, never published, never recorded, and never serve a command; before the fix it is published recording the new code. android_send_smsonly calls a send retryable when every segment accounted for itself.describemapped any failure code with nothing confirmed tostatus: "failed"— documented to the agent, in the schema, the docstring,skill.mdanddocs/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 hitRESULT_ERROR_RADIO_OFFand 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".
describenow takesreportedParts— the tally F29 made complete — andfailedrequiresreportedParts >= parts. A failure with segments unheard from falls back toqueued_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 producefailed, so a caller that forgets to pass it degrades to do-not-resend rather than to a duplicate.ActionExecutor.sendSmspassesreport.reportedPartsalongsidereport.confirmedParts. The four statuses and the tightened meaning offailedare restated in the schema description, the docstring (both copies),skill.md/SKILL.mdanddocs/troubleshooting.md. Tests:SmsSendReportTest(25 → 28) andActionExecutorSendSmsTest(16 → 17) — a failure with unreported segments isqueued_unconfirmedand not retryable,failedappears only atreportedParts == parts(asserted across all four values for a 3-segment send), the same through a realSmsSendReportwhose 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
smsSendReportTimeoutMsfor a count that could never be released. Ten seconds of a caller's 30 s budget on the common failure path, on aDispatchers.IOthread F13 had just moved it onto.
Every report now counts down, success or failure, and the failure codes are recorded separately:failurekeeps the first code (the one reported), a newrejectedcounter tallies them, andreportedPartsisconfirmedParts + 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.reportedPartsis 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,reportedPartscounts 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_fileswas still only ever added to:_register_media_temp()put a path in, and nothing took one out untilatexitcleared 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 badstatcannot abort the pass. Files that still exist stay registered — including the one the current call is about to hand back asMEDIA:<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 whenos.listdirraises. android_send_smsno longer spends ten seconds waiting for a report nothing was listening for. Registering thesentIntentreceiver can fail — aSecurityExceptionon a hardened ROM, anIllegalArgumentExceptionfrom a context that cannot take one — andsendSmscorrectly refused to claim success without a report. It then waited out the wholesmsSendReportTimeoutMsbound 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 throughSmsSendReport.describeUnobservable(parts, reason), with wording that says the report cannot be observed on this device and names the reason. The status staysqueued_unconfirmedand 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.mddocuments the variant next to the timeout one. Tests:SmsSendReportTest(21 → 22) andActionExecutorSendSmsTest(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 nounregisterReceiveris 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 thatdispatchnever sees:RelayClient.handleMessage's catch, which wraps the JSON parse, therequest_idcheck and the/mic_filestream. That one answered{"error": e.message}, so a command with norequest_idcame 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 fromCommandDispatcher.errorBody(). TheLog.etext 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.mdnames 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 assertionCommandDispatcherErrorContractTestmakes of the dispatcher), and it is asserted equal toerrorBody()'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
shouldReconnectand clear its own job handle insidesynchronized, then call the connector after releasing the monitor.disconnect()andconnect()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 callconnect()— and so cancel this very job — without deadlocking, so F9's "the reconnect must not be cancelled by its ownconnect()" still holds; nothing in the dial blocks on the monitor from another thread (notifyStatusposts to the main looper,newWebSocketenqueues). 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_setupcan now print awss://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_HOSTnames 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 bindsANDROID_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 aserver_address_notesaying the handshake will fail unless the certificate covers it and naming the variable to set; the same sentence is appended touser_instructions, because that is the text a human reads. A plaintext relay gets no note: an IP is a perfectly goodws://host.docs/configuration.mddocuments the variable in the table, in the.envscope 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, andANDROID_RELAY_HOSTstill decides the bind address.android_send_smsno longer tells the caller a partly delivered multipart SMS is safe to retry.SmsSendReportanswered on the first segment report that was notRESULT_OK, anddescribemapped any such code tostatus: "failed"— documented to the agent, in the schema, the docstring,skill.mdanddocs/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 hitRESULT_ERROR_NO_SERVICEthat 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.
SmsSendReportnow counts the segments that reportedRESULT_OK(confirmedParts) anddescribetakes the tally, adding a fourth outcome:partially_sent,success: true,deliveredofparts, the radio's reason, and an explicit do-not-resend.failedis reserved for a definite error with nothing confirmed, which is the only case where a retry is safe. Every outcome now carriesdeliveredalongsidestatusandpartsso 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 producesfailed, i.e. "retry". A single-segment send still answers immediately, since nothing else can arrive. The wait runs onDispatchers.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 newdocs/troubleshooting.mdentry. Tests:SmsSendReportTest(16 → 21) — a partial multipart send ispartially_sent,success: true, do-not-resend, naming the reason and both counts; a failure with nothing confirmed staysfailedand 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
AudioRecordrelease: it happens in the loop'sfinally, and a coroutine whose body never starts runs nofinally.onDestroyonly calledsafelyStop, which stops capture without releasing, and its unconditional release is guarded byrecordingJob == 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_startcould fail to initialise the microphone.onDestroy's completion handler now releases whateverAudioRecordis still held once the job is done, which is a no-op for a loop that ran (itsfinallyalready released and nulled the field) and cannot pull the microphone out from under a loop that is still writing, because it waits for completion.recorderbecomes internal so the leak can be asserted: the case that causes it is a job cancelled before dispatch, which no realAudioRecordreproduces 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 toFINALIZING), 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_wsvalidated the Bearer token, thenawait ws.prepare(request), and only afterwards publishedstate.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 instate.phone_ws_code;_handle_wsre-checks it underphone_ws_lockafterprepareand closes the socket withPOLICY_VIOLATIONinstead of publishing when it has gone stale._cleanup_phoneclears the recorded code with the socket, so a later rotation never judges a session it knows nothing about. And_drop_phone_after_rotationis 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 restructuredTestPairingRotationDrop(6). The handshake cases drive a fake whoseprepare()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()'sstale_ws is Nonebranch 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 —RelayClientre-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 answeredConnectionError("Phone disconnected (pairing code rotated)"), so rotating the code broke a healthy session it had no business touching; theandroid_ping()an agent runs straight afterandroid_setupis 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_setupno longer writes a bridge URL the TLS relay cannot answer. WithANDROID_RELAY_CERT/ANDROID_RELAY_KEYset, aiohttp serves the relay's whole site over that onessl_context— the/wsroute the phone dials and the HTTP routes the tools call are the sameTCPSite— but setup still saved and exportedANDROID_BRIDGE_URL=http://localhost:<port>. The listener stopped speaking HTTP, so every tool call failed, including theandroid_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 fixedget_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)forANDROID_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 againstandroid_relay.is_tls_configured()so the two predicates cannot drift).
Anhttps://localhostURL still cannot verify: the certificate is issued for the relay's public name, never forlocalhost._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 otherhttps://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'/pingprobe andandroid_mic_fetch's streaming download.docs/configuration.mdand 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 stayshttp://, 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_sweptlatch 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.atexitonly 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 asMEDIA:<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 withrun_coroutine_threadsafe, and the coroutine called_cleanup_phone()with noexpected_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_lockinset_pairing_code()and passed through asexpected_ws, which_cleanup_phone()already knew how to honour. ANonecapture means nothing was connected at rotation time, so there is no old-code session to drop: it is not forwarded asexpected_ws(aNonethere 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_codeis 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_startcan no longer stay blocked at 409 by an abandonedfinalizingphase. The #98/F10 fix leftFINALIZINGout ofisAwaitingRecorderon the reasoning that the finalisation block has no suspension points and owns both terminal states, so it always reachesmarkReady/markErrorby itself. That premise needs the block to run:requestStop()publishesFINALIZINGfrom the main thread while the record loop may still be queued onDispatchers.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.FINALIZINGcounts asisActive,tryReserveStart()keeps returning false, and every/mic_startanswers 409 until the app restarts: #98 again, one phase later.onDestroynow attachesinvokeOnCompletionto the recording job and settles aFINALIZINGphase that nothing will finish, via a newMicrophoneRecordingState.settleAbandonedFinalizing(activeFile, message). The completion handler is what keeps F10 closed: it runs after the job, so a finaliser that reachedmarkReadyleaves the phase atREADYand 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@Afterreset so a failing case cannot leave the state machine active and fail the next one for an unrelated reason.android_send_smssend 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 itssentIntentPendingIntents with requestCodes0..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.PendingIntentidentity isrequestCodeplusIntent.filterEquals, andfilterEqualsignores extras, so call B's segment-0 intent was call A's; withFLAG_IMMUTABLEthe extras cannot be updated, so B was simply handed A's intent. The action now carries a per-call UUID (smsSentReportAction(callId)), which scopes theIntentFilterto 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 afinallyon 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 sendqueued_unconfirmedinstead 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_smsno longer invites the retry that duplicates the message. When no send report arrived inside the 10 s window the tool answeredsuccess: false— but the message had already been handed to the radio (sendTextMessagereturned without throwing), and a missing report is what a device on one bar of signal, a sleeping modem or an OEM that does not firesentIntentproduces routinely.falsereads 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 nowsuccess: truewithdata.status: "queued_unconfirmed"and a message that says delivery is unconfirmed and do not resend, because a retry would duplicate it.success: falseis 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-readabledata.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, noSEND_SMS, no telephony, platform rejection) are unchanged and stillsuccess: false, since nothing reached the radio. The tool schema, its docstring,docs/troubleshooting.mdand the SMS section ofskill.md/SKILL.mdall 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_smsno longer blocks the transport's thread while it waits for the radio.ActionExecutor.sendSmsparks a thread on aCountDownLatchfor up tosmsSendReportTimeoutMs(10 s) so it can report what the modem actually did rather than whatsendTextMessagequeued, andCommandDispatcher.dispatchcalled it inline.dispatchis 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,/screenand the event stream for ten seconds; over the relay it is aDispatchers.IOworker the message-handler coroutine gave up. The call now runs insidewithContext(Dispatchers.IO), the same shape/contactsand/screen_recordalready used, through a newCommandDispatcher.smsSenderseam modelled onbatteryContext. Not converted tosuspendCancellableCoroutine+withTimeout: that would makesendSmssuspend 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 aDefaultDispatcher-workerthread 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.
maybeFireTermuxRevivalreadslastFailureHttpCodeto decideauthFailure— 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 perconnect()cycle), so a code recorded earlier was still sitting there when exhaustion was reached throughonClosed, which writes nothing at all; andonFailurecheckedmyGeneration != generationand 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()andbeginReconnectAttempt()— the only two callers ofconnector, so the only two places an attempt starts — now clear it, and the write goes through a guarded@SynchronizedrecordFailureHttpCode(attemptGeneration, httpCode). Tests:RelayClientFailureClassificationTest(4), mutation-checked by dropping the guard and the resets. RelayUrlnow treats100.64.0.0/10as private. RFC 6598 shared address space is what carrier-grade NAT uses and what Tailscale assigns to every tailnet node, so a relay reached at100.111.22.33was classified public and dialling it overws://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.isPrivateHostis 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 andclassName = "C"hashed identically totext = "X",contentDescription = "Y",className = "null|C". An injectivity hole in the value/screen_difftrusts 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_diffcompares against thepreviousHashthe caller supplies — so the only effect is that a hash obtained before the upgrade never matches one computed after it, and the first/screen_diffacross 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 theMediaRecorderor itsprepare()threw:recorder = mrran only after theapply {}block returned, socleanupRecording()in the catch saw a null field and the native recorder (encoder + projection client) leaked. Reachable on a real device wheneverprepare()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; theVirtualDisplayneeded no change, already being assigned the moment it is created.EventStore.add()no longer throwsNoSuchElementExceptionout ofonAccessibilityEventwhenmaxCapacityis 0 or negative. The eviction guard readsize >= maxCapacityas "at capacity" and calledremoveLast()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. LoweringmaxCapacityalso 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 newEventStoreTestcoverage; not reachable in the shipped app, which never writesmaxCapacity.- Dismissed notifications no longer evict live ones from the shared buffer.
markRemovedretains entries in the sameArrayDequethataddevicts from atmaxCapacity(raised to 300 byBridgeNotificationListener), and eviction wasremoveLast()— the oldest entry, which on a busy day is the long-livedisOngoingone: a music player, navigation, the bridge's own mic notification. Since the default read filters dismissed entries out, they consumed capacity only the opt-ininclude_removedpath could see, so 300 arrivals-and-dismissals pushed out a notification the user could still see in the shade andandroid_notifications()reported it missing.addnow 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 transientphase: errorfor a recording that is complete and downloadable.onDestroyreset any active phase, andisActiveincludesFINALIZING— but the finalisation block has no suspension points and owns both of its terminal states, so it always reachedmarkReadyand 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, andCommandDispatcherserveslatestfrom 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 calledandroid_mic_fetch().docs/manual-tests.mdstep 12 ("wait forandroid_mic_status()to report ready") would hang on that run. Both reset sites now use a newisAwaitingRecorder(STARTING/RECORDINGonly):onDestroy, andrequestStop()'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 inSTARTINGand is still reset.- Both transports now answer a route failure the same way.
CommandDispatcheris 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.handleMessagewrappeddispatchand answered{"error": …}at500;BridgeRouterhad notry/catchandBridgeServerinstalled onlyContentNegotiation, 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.dispatchnow owns the contract — a JSON object with anerrorkey at500— andBridgeRouterguards 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-pagesis not a dependency, so the guard is in the router rather than aStatusPagesblock. Tested at both layers, including a real Netty engine on an ephemeral port answeringPOST /open_appwith a JSON 500. android_send_smsno longer reports success for messages that were never sent.sendTextMessage(to, null, body, null, null)passed null for bothsentIntentanddeliveryIntent, so no send status was ever observed andsendSmsreturnedActionResult(true, "SMS sent")unconditionally —sendTextMessagereturns 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 withdivideMessage, sends viasendMultipartTextMessagewhen there is more than one segment, supplies onesentIntentper segment, and waits (bounded, 10s) for the radio's report:success: falsewith the named reason on a radio failure, and an unconfirmed outcome when no report arrives (see thequeued_unconfirmedentry below for how that is reported).POST /send_smsanswers400on a blankto/body— previously it defaulted both to"", AOSP threwIllegalArgumentExceptionwhose 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-connectionscope, and when that coroutine fired 30 s later it calledconnect()— whose first statement isdisconnect(), which doesscope?.cancel(); scope = null, cancelling the very scope the caller was running on. It only worked because nothing betweendisconnect()and the end ofdoConnect()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, anawaiton DNS — would make it throwCancellationException, 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-levelrevivalScopewith its ownSupervisorJob. 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, andshouldReconnect = falsewas ignored. The job is now tracked inrevivalReconnectJob, cancelled bydisconnect()and at the top ofconnect()(before the pairing-code check, so a connect that bails out still cancels the stale dial), and re-checked againstshouldReconnectwhen 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 theconnect()it makes.reconnectDelayed()re-armsshouldReconnectwhen 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 outlivesdisconnect(), and the realconnect()from inside the coroutine still reachesdoConnect. - The Termux revival watchdog no longer ships one contributor's private deployment path.
RelayClienthardcoded/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 fireRUN_COMMANDat 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 nowRelayClient.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.mdand a newdocs/troubleshooting.mdsection cover the toggle, the Allow external apps requirement, the default path and the fire budget. The intent construction moves intotermuxRevivalIntent()so it is testable:TermuxRevivalIntentTestpins the action, target component, all four extras and the path shape, closing the gap wheremaybeFireTermuxRevival/fireTermuxRestarthad no coverage at all. - The Termux revival watchdog is now bounded. Its only limits were
WATCHDOG_FAILURES_TO_TRIGGER = 3and a 10-minute cooldown, andFirereset 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.RevivalPolicygains a fire budget (maxFires, default 3 — roughly 30 minutes of automatic recovery) and returns a newExhausteddecision 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:portor the request URL. 39 of the 40 network tools answered a transport failure withjson.dumps({"error": str(e)}), andrequestsputsHTTPConnectionPool(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_eventsparams). 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 redactionandroid_mic_fetchhas 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-requestsexception (a localOSError, a handler'sTypeError). android_pingno longer reportsstatus: "ok"for a 200 whose body is not JSON._extract_responseturns an undecodable body into{"error": "<raw text>"}and hands it back as if it were data, so a reverse proxy answering/pingwith an HTML 502 page produced{"status": "ok", "bridge": {"error": "<html>502 Bad Gateway</html>"}}. Agents readstatus == "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_macrono longer raises on a malformed step. The loop readstep.get("tool")outside thetrythat turns handler failures into{"error": "Step N …"}, so a model that sent["android_tap"]or[null]instead of[{"tool": "android_tap", "args": {}}]got anAttributeErrorout 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,toolis a string,argsis an object), and astepsargument that is not a list at all is reported too instead of raisingTypeErrorfromenumerate(None)— or, worse, iterating a bare string one character at a time.stop_relay()no longer raisesRuntimeError("Event loop is closed")after a failedstart_relay().start_relay()registered_relay_instancebefore the readiness handshake and left it registered when that handshake timed out (port taken, loop died), while_run_loop()closes its loop in afinally— so the very nextstop_relay(), the teardown every caller wraps around a start, calledcall_soon_threadsafe()on a closed loop and blew up instead of shutting down. A failed start now rolls_relay_instanceback, andstop_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 theHTTPErrorit 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, andandroid_setupno longer clobbers a port the user configured.docs/configuration.mdpresented all of them under one "Config lives in~/.hermes/.env" table, but onlyANDROID_BRIDGE_URLandANDROID_BRIDGE_TOKENwent through_env();ANDROID_RELAY_PORT,ANDROID_BRIDGE_TIMEOUT,ANDROID_RELAY_HOST,ANDROID_RELAY_CERTandANDROID_RELAY_KEYwere plainos.getenv. That is exactly the processandroid_setupstarts the relay in — a gateway that loads.envfor its own config without exporting it — soANDROID_RELAY_PORT=9000in the file was ignored, the relay bound 8766, and setup then wrote 8766 over the user's 9000.ANDROID_BRIDGE_TIMEOUT=120was ignored the same way, timing longandroid_wait/screen_recordcalls out at 30s.android_relay.pygets its own_env()rather than importing the tool's, so it still runs standalone on a relay host; both copies stay byte-identical.android_setupalso resolves the file it writes with_hermes_home(), the same way the reader does — it usedPath.home(), so it wrote where nothing looked, and the test suite silently created a real~/.hermes/.envon every run. android_send_intentno longer advertises calls the bridge refuses. Its docstring and schema description recommendedandroid_send_intent("android.settings.WIFI_SETTINGS")and promised "setting toggles" — butActionExecutor.sendIntentblocks that action twice over (explicitblockedIntentsentry plus theandroid.settings.prefix rule), and thedata_urihinttel:+1234567890used 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 anhttps://ACTION_VIEWdeep 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 bothandroid_tool.pycopies.tests/test_send_intent_docs.pyderives 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_skillin the plugin is now reported instead of silently swallowed.register()wrapped it inexcept (AttributeError, TypeError): pass, justified as "hermes-agent older than the register_skill API" — butAttributeErroris also what a missingskill.mdproduces andTypeErroris also what a renamedpath=kwarg produces. The plugin folder is copied by hand (install.sh, thecp -rsteps in README.md), so a copy withoutskill.mdshowed✓ hermes-android v0.5.0 (42 tools)in/pluginswhile 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:hasattrfor a genuinely old API (info), anis_file()check for a broken install (warning naming the path), andlogger.exceptionfor anything else, so the tools always survive but the reason always reaches the log. - Wake-key test coverage restored (
android_press_key("wake"), #101).6fe8444added three behavioural assertions toWakeLockManagerWakeTest;aa17e70deleted all three and kept onlyassertTrue(wake()). That is no coverage at all:wake()returnstrueunconditionally once aPowerManageris present, so the suite passed for anyacquireWakeLock()that did not throw — including one that acquires nothing, one that dropsACQUIRE_CAUSES_WAKEUP(press_key("wake")reports{"success":true}while the screen stays black), and one that callsacquire()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()plusShadow.extractfor the tag, hold count andisHeld, sinceShadows.shadowOf()has noPowerManageroverload — and the flags and timeout, which no shadow exposes, go through a newWakeLockManager.powerManagertest seam modelled onCommandDispatcher.batteryContext. Verified by mutation: droppingACQUIRE_CAUSES_WAKEUPand the timeout fails 3 tests, and makingacquireWakeLock()a no-op fails 7. - One source of truth for the Python package version.
setup.pyrepeatedversion,install_requiresandpython_requiresfrompyproject.toml, and the commit titledrelease: v0.5.0bumped pyproject,plugin.yamlandbuild.gradle.ktsbut leftsetup.pyat0.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 --versionreported setup.py's value while a PEP 517 build read[project].setup.pynow carries only the packaging hints[project]does not express (packages,package_data) and inherits the rest;tests/test_version_consistency.pypins the installed dist metadata,plugin.yamland the APK'sversionNametopyproject.toml, and fails if aversion=/install_requires=returns tosetup.py.docs/RELEASING.mdsteps 2–3 updated — they did not mentionbuild.gradle.ktsat all. python.ymlnow also triggers onpull_requestfor changes to.github/workflows/python.ymlitself. The path was inon.push.pathsbut missing fromon.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 onmainto be discovered by the next unrelated PR touchingtools/.tests/test_python_workflow.pypins 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.mdis now pinned to the allowlist in both directions, and the twoandroid_relay.pycopies are pinned byte-identical. An endpoint added toCommandDispatcherwithout 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.pyredirected it by settingHOMEandHERMES_HOMEto a throwaway directory, butPath.home()andos.path.expanduser("~")fall back topwd.getpwuid(os.getuid()).pw_dir— the real home — wheneverHOMEis absent from the environment, which putsandroid_setup()'s credentials write and_env_file_vars()' pairing-token read onedelenv(or one runner withoutHOME) away from the developer's own files. The autouse fixture now patches the~lookups themselves, replacing only thepwdfallback so an explicitly setHOMEstill 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).
PairingManageris the single source of truth on the device: the duplicaterelay_pairing_codestore 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_setuppushes the code to an already-running relay (start_relayis 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.isPasswordwas 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_nodeand/events, and from there into the transcript and the model provider. One choke point (security/SensitiveText) now emits"[redacted]"for those nodes, drops theircontentDescription/hintText, keeps the node itself addressable (id, class, bounds, editable) and flags itpassword: true; text searches match the redacted value, so/find_nodescannot 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_setupvalidates the pairing code (PY-1). The value was interpolated raw into~/.hermes/.env, which is parsed askey=valuelines 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_fileindependently refuses CR/LF values and non-NAMEkeys, and the write is atomic at0600from creation instead of write-then-chmod (which left the token world-readable in between). The fallback path also honoursHERMES_HOME, matching where the token is read from.sendIntentdenylist gaps closed (CTRL-2).sms:andmms:join the blocked schemes; thecontent://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=Falseand 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. /waitand/screen_recorddurations are clamped (RES-1). An unclampedtimeoutMslet 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./waitis now capped at 120 s — above every timeout a legitimate caller can observe — and/screen_recordgained the minimum clamp it was missing, so a negative duration is rejected at the boundary instead of throwing insideThread.sleep.- A non-ASCII
Authorizationheader is a counted rejection, not a 500 (AUTH-5).hmac.compare_digestraises on non-ASCIIstrand 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 (
:8765binds0.0.0.0at app start with no toggle) and is corrected. dataUriis now redacted in the relay's DEBUG request-body log.android_send_intentsends the URI underdataUri— a key_SENSITIVE_BODY_KEYSdid not contain — so aSENDTOdeep link loggedsmsto:<full phone number>verbatim and anhttpsone could leak an embedded reset token, against the AGENTS.md rule to strip phone numbers and recipients from responses and logs.docs/troubleshooting.mdtells 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.actionandpackageOverridestay readable: they name a verb and an app, not a person. A new test derives the payload keys fromandroid_send_intentitself, 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, andpytestwas overwriting the developer's real~/.hermes/.envon every run.