Compare commits

..
Author SHA1 Message Date
Bailey DixonandClaude Opus 4.8 99b9cf1704 fix(android): currentSession() must not re-throw network errors (crash)
An on-device crash (FATAL EXCEPTION: main, SocketTimeoutException,
Caused by SocketException "Software caused connection abort") over a
Tailscale connection. Full trace recovered from a background logcat
capture pinned it to DashboardApiClient.currentSession().

Root cause: currentSession() returns Result<DashboardAuthSession> but did
a raw okHttpClient.newCall(req).execute() with NO try/catch — the lone
outlier among the client's methods (executeJson/executeJsonElement/
audioRoutesPresent all catch). The execute() ran on Dispatchers.IO
(correct), but a transient stale-pooled-connection abort re-threw out of
withContext(IO). The caller chain — ConnectionViewModel.probeStandardVoice()
-> viewModelScope.launch (Dispatchers.Main.immediate, the Suppressed frame
in the trace) — used try/finally with no catch, so the exception was
uncaught on the main thread and killed the app. (execute() being off-main
is why StrictMode never fired; the uncaught propagation was the bug.)

Fix:
- currentSession() wraps its request in try/catch -> Result.failure on any
  exception, honoring the Result contract callers rely on (mirrors
  executeJson()).
- Defense-in-depth: probeStandardVoice() gains a catch (rethrowing
  CancellationException) that degrades availability state instead of
  letting any probe sub-call crash the Main coroutine.

Test: DashboardApiClientTest.currentSession_onConnectionAbort_returnsFailure_doesNotThrow
(MockWebServer DISCONNECT_AT_START) asserts a connection abort yields
Result.failure, not a throw. :app:testSideloadDebugUnitTest green (25/25).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 16:51:51 -04:00
Bailey Dixon ee0591457b Merge pull request #126 from Codename-11/dev
release(android): android-v1.2.3
2026-06-23 22:04:36 -04:00
Bailey DixonandClaude Opus 4.8 26811f0eb8 release(android): android-v1.2.3
Connection-stability hotfix. Promotes the TLS/Tailscale connect-crash fix
(#118, #124; likely #70) from [Unreleased] to [1.2.3]. appVersionName
1.2.3 / appVersionCode 17. Desktop CLI entries stay under [Unreleased] for
their own cli-v* cut.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:35:16 -04:00
Bailey Dixon eafdb4efe2 Merge pull request #125 from Codename-11/fix/evictall-network-on-main-thread
fix(android): close TLS sockets off the main thread on client shutdown
2026-06-23 21:31:04 -04:00
Bailey DixonandClaude Opus 4.8 802385c65c fix(android): close TLS sockets off the main thread on client shutdown
Connecting over an encrypted link (Tailscale Serve / public HTTPS) could
hard-close the app with NetworkOnMainThreadException. HermesApiClient,
DashboardApiClient and ConnectionManager all call ConnectionPool.evictAll()
inline in shutdown(); evictAll() closes pooled sockets synchronously, and a
live https/wss keep-alive close drains a TLS close-notify through
SSLOutputStream -- a real network write StrictMode forbids on the main
thread. Several call sites reach shutdown() from a viewModelScope
(Dispatchers.Main.immediate) coroutine -- probeStandardVoice()'s finally
block on every connect, and onCleared()'s connectionManager.shutdown() --
so the process was killed on connect over TLS. (Plaintext closes write
nothing, which is why every report is on Tailscale/public TLS.)

Push the guard into the leaf: a shared shutdownOffMainThread() runs the
executor-shutdown + evictAll() on a short-lived daemon thread when called
from the main thread, and inline otherwise (preserving the blocking
awaitTermination semantics for callers already on IO). Every shutdown()
call site is now safe regardless of dispatcher; the redundant
withContext(IO)/Thread wrappers in onCleared() are removed.

Adds a Robolectric NetworkShutdownTest asserting the teardown never runs on
the main thread when invoked from the main looper, and runs inline off it.

Fixes #118, #124. Likely resolves the v1.1.0/Tailscale crash in #70.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:58:17 -04:00
Bailey DixonandClaude Opus 4.8 ec05643b6b docs(devlog): record android-v1.2.2 release
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 22:58:55 -04:00
15 changed files with 228 additions and 77 deletions
+10
View File
@@ -20,6 +20,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
- **Desktop CLI: smoother pairing.** The multi-endpoint probe shows per-endpoint progress and latency; a near-expiry session warns before it fails and prints the exact re-pair command; and a bare `ws://host` (no port) defaults to `:8767`.
- **Desktop CLI: voice + consent transparency.** `voice` now surfaces enhanced-voice capabilities (Gemini tone tags / persona, xAI speech tags); the desktop-tool consent prompt is clear that it persists per relay and points at `hermes-relay audit`; and computer-use's observe → grant → act flow is documented in `--help`.
### Fixed
- **Crash when a dashboard connection drops mid-check.** A transient network blip on the dashboard session check (e.g. a pooled connection aborting over Tailscale) could close the app: the check returned a result type but re-threw the network error instead of reporting it, and it surfaced on the main thread. The check now reports the failure cleanly, and the connection probe degrades gracefully instead of ever crashing.
## [1.2.3] - 2026-06-23
### Fixed
- **Crash on connect over TLS / Tailscale.** Connecting to a server over an encrypted link (Tailscale Serve or public HTTPS) could hard-close the app with `NetworkOnMainThreadException`. Tearing down an HTTP client closed live SSL sockets on the main thread, and a TLS socket close performs a network write — which Android forbids on the main thread. Client shutdown now always closes sockets off the main thread, so connecting over a secured link no longer crashes. (#118, #124; likely the v1.1.0 / Tailscale crash in #70)
## [1.2.2] - 2026-06-22
### Added
+24
View File
@@ -1,5 +1,29 @@
# Hermes-Relay — Dev Log
## 2026-06-24 — Fix SocketTimeoutException crash from DashboardApiClient.currentSession()
**Why.** An in-app crash report (`FATAL EXCEPTION: main`, `SocketTimeoutException`, `Caused by: java.net.SocketException: Software caused connection abort`) captured on-device over a Tailscale connection. The visible dialog truncated the trace; the full stack was recovered from a background `adb logcat` capture that happened to be running when it fired.
**Root cause.** `DashboardApiClient.currentSession()` declared `Result<DashboardAuthSession>` but performed a **raw `okHttpClient.newCall(req).execute()` with no try/catch** — the lone outlier among the client's methods (`executeJson`/`executeJsonElement`/`audioRoutesPresent` all catch). Its `.execute()` correctly ran on `Dispatchers.IO`, but a transient network failure (a stale pooled connection aborting over Tailscale) **re-threw** out of `withContext(IO)`. The caller chain — `ConnectionViewModel.probeStandardVoice()` → `viewModelScope.launch` (`Dispatchers.Main.immediate`, the `Suppressed` frame in the trace) — used `try/finally` with **no `catch`**, so the exception was uncaught on the main thread and killed the app. The `.execute()` being off-main is why StrictMode never fired; the uncaught *propagation* to the Main coroutine was the bug.
**Fix.** (1) `currentSession()` now wraps its request in `try/catch`, returning `Result.failure` on any exception — honoring the `Result` contract every caller relies on (mirrors `executeJson`). (2) Defense-in-depth: `probeStandardVoice()` gained a `catch` (rethrowing `CancellationException`) that degrades the voice/gateway availability state instead of letting any probe sub-call crash the Main coroutine.
**Verification.** New `DashboardApiClientTest.currentSession_onConnectionAbort_returnsFailure_doesNotThrow` (MockWebServer `DISCONNECT_AT_START`) asserts a connection abort yields `Result.failure`, not a throw. `:app:testSideloadDebugUnitTest` + `:app:lintSideloadDebug` green. On-device confirmation pending a build.
## 2026-06-23 — Fix NetworkOnMainThreadException crash on TLS connect
**Why.** Two external bug reports (#118, #124) and the later comment on #70 reported the app hard-closing on connect over an encrypted link (Tailscale Serve / public HTTPS). The auto-captured traces were identical: `android.os.NetworkOnMainThreadException` from `okhttp3.ConnectionPool.evictAll()`, with a suppressed `Dispatchers.Main.immediate [Cancelling]` frame — i.e. a `viewModelScope` coroutine.
**Root cause.** `HermesApiClient.shutdown()`, `DashboardApiClient.shutdown()`, and `ConnectionManager.shutdown()` each call `connectionPool.evictAll()` inline. `evictAll()` closes pooled sockets synchronously; for a live `https`/`wss` keep-alive connection a TLS close drains a close-notify through `SSLOutputStream` — a real network write StrictMode forbids on the main thread. Several call sites reach `shutdown()` from a `viewModelScope` (`Dispatchers.Main.immediate`) coroutine: `probeStandardVoice()`'s `finally { client.shutdown() }` fires on every connect/voice probe, and `onCleared()` called `connectionManager.shutdown()` directly on the main thread. The off-main handling existed only as scattered per-call-site `withContext(Dispatchers.IO)` / background-`Thread` wrappers, so the unwrapped paths still crashed. TLS-only because a plaintext socket close writes nothing — matching every report being on Tailscale/public TLS.
**Fix.** Pushed the guard into the leaf. New `network/NetworkShutdown.kt#shutdownOffMainThread(name, block)` runs the executor-shutdown + `evictAll()` on a short-lived daemon thread when called from the main thread, and inline otherwise (preserving the blocking `awaitTermination` semantics for callers already on IO). Wrapped all three `shutdown()` bodies with it, so every call site is safe regardless of dispatcher. Simplified `ConnectionViewModel.onCleared()` — its now-redundant manual `Thread` wrappers were removed and `connectionManager.shutdown()` is no longer an unguarded main-thread `evictAll()`.
**Verification.** New Robolectric `NetworkShutdownTest` (2 cases) asserts the teardown runs off the main thread when invoked from the main looper, and inline when invoked off it. `./gradlew :app:testSideloadDebugUnitTest --tests NetworkShutdownTest` green (compiles the full module + both cases pass). On-device confirmation over a real Tailscale/TLS connection pending a Studio build.
## 2026-06-22 — Released android-v1.2.2
Cut Android **1.2.2** (appVersionName 1.2.2 / appVersionCode 16) — "Multi-profile polish". The version bump + release docs were already on `dev`; the cut first integrated `origin/dev`, which had advanced to **compileSdk 37** (`206d182`) and typed `stream.event` passthrough (PR #120) — dropping the temporary 1.2.2-prep `markdown-renderer 0.41.0` / `lifecycle 2.10.0` pins (a compileSdk-36 workaround) for compileSdk 37 + the `0.42.0` / `2.11.0` deps. `dev` CI (Android build + tests on compileSdk 37) green; release PR #122 (`dev` → `main`, `--no-ff`, merge `984d9a2`) merged on green Required-checks + claude-review; `android-v1.2.2` tagged from the `main` tip triggered `release-android.yml` → signed APK/AAB (googlePlay + sideload) + `SHA256SUMS.txt` → GitHub Release **Hermes-Relay-Android v1.2.2** (published, not draft). Headline 1.2.2: session-delete persists on non-default profiles, cold-start profile isolation for the session drawer, full-screen Diagnostics status timeline, "Hermes"/"Relay" connection wording, and the clean-chat layout + scrollable history; also ships the typed `stream.event` relay passthrough (first slice) integrated from `dev`. Post-cut: `main` back-merged into `dev` (fast-forward) so they stay aligned. Follow-up: CLAUDE.md still says "Compile SDK 36" — update to 37 to match the build.
## 2026-06-22 — Outstanding-TODO batch (orchestration): four User-Added fixes
**Why.** Four open User-Added TODO items, resolved in one 4-worker orchestration pass with disjoint file ownership and coordinator-serialized commits (workers edited only; the coordinator committed each task's files by pathspec to avoid the shared-index race). A read-only Explore pass mapped each task to its files first, surfacing the two collision hubs (`ChatScreen.kt`, `RelayApp.kt`) so ownership could be partitioned to keep all four file sets disjoint. All changes are client-side Kotlin. **Unbuilt at time of writing — pending Studio build + `./gradlew lint`.**
+14 -21
View File
@@ -1,22 +1,22 @@
# Hermes-Relay-Android v1.2.2
# Hermes-Relay-Android v1.2.3
**Release Date:** June 22, 2026
**Since v1.2.1:** A multi-profile reliability pass. Switching agent profiles now keeps your chats straight — **deleting a session on a non-default profile sticks**, and a **cold start opens the session list on the right profile** instead of flashing the default one — plus a **full-screen Diagnostics** view that leads with subsystem health checks, simpler connection wording, and a roomier distraction-free chat mode.
**Release Date:** June 23, 2026
**Since v1.2.2:** A connection-stability hotfix. Connecting to a server over an **encrypted link** (Tailscale Serve or public HTTPS) could hard-close the app the moment the connection came up; that crash is fixed, so securing your connection no longer force-closes Hermes-Relay.
v1.2.2 is a focused follow-up to 1.2.1, sharpened by real multi-profile use. The two profile fixes remove the most confusing rough edges when you run more than one agent profile, Diagnostics becomes a place you can actually read at a glance, and a couple of small touches make the default path clearer.
v1.2.3 is a focused fix for anyone connecting over Tailscale or public TLS. Plain-LAN connections were never affected.
---
## Download
v1.2.2 ships in two Android build flavors. APK and AAB filenames are version-tagged:
v1.2.3 ships in two Android build flavors. APK and AAB filenames are version-tagged:
| Flavor | File | Who it's for |
|---|---|---|
| Google Play | `hermes-relay-1.2.2-googlePlay-release.aab` | Upload this Android App Bundle to Play Console. It has no AccessibilityService, screen reading, screenshots, gestures, SMS/calls, contacts/location, overlays, or unattended phone control. |
| sideload | `hermes-relay-1.2.2-sideload-release.apk` | Direct-install APK for full Device Control. Installs as `com.axiomlabs.hermesrelay.sideload`. |
| googlePlay APK | `hermes-relay-1.2.2-googlePlay-release.apk` | Parity/testing artifact. |
| sideload AAB | `hermes-relay-1.2.2-sideload-release.aab` | Parity/testing artifact. |
| Google Play | `hermes-relay-1.2.3-googlePlay-release.aab` | Upload this Android App Bundle to Play Console. It has no AccessibilityService, screen reading, screenshots, gestures, SMS/calls, contacts/location, overlays, or unattended phone control. |
| sideload | `hermes-relay-1.2.3-sideload-release.apk` | Direct-install APK for full Device Control. Installs as `com.axiomlabs.hermesrelay.sideload`. |
| googlePlay APK | `hermes-relay-1.2.3-googlePlay-release.apk` | Parity/testing artifact. |
| sideload AAB | `hermes-relay-1.2.3-sideload-release.aab` | Parity/testing artifact. |
Verify integrity with `SHA256SUMS.txt` from the same release. See the [Sideload guide](https://codename-11.github.io/hermes-relay/guide/getting-started.html#sideload-apk) for APK install steps.
@@ -24,19 +24,12 @@ Verify integrity with `SHA256SUMS.txt` from the same release. See the [Sideload
## Highlights
### Profiles that behave
- **Deleting a session on a non-default profile now sticks.** A non-default profile keeps its sessions in its own store; the delete now scopes to the active profile, so a removed chat no longer reappears after the list refreshes.
- **Cold start opens on the right profile.** Launching with a non-default profile selected used to briefly show the default profile's chats before snapping to the correct ones. The session list (and the restored session context) now wait for the profile to resolve and load the right list directly.
### Clearer diagnostics
- **Diagnostics status timeline.** Diagnostics is now a full screen that leads with a top-to-bottom list of subsystem health checks — network, API server, chat transport, pairing, relay, and voice — each with a pass / warning / fail state and the reason when something's wrong. Tap a failing check for full detail; the recent-activity log stays below.
### Small touches
- **Simpler connection wording.** The default connection is now just **"Hermes"** (previously "Vanilla" / "Standard Hermes"), and the optional power features are labelled **"Relay"** / "Relay plugin", across setup, the switcher, voice, and permissions.
- **Roomier clean chat.** Distraction-free chat mode gives its text a taller, scrollable area instead of capping it near a third of the screen.
### Fixed
- **No more crash on connect over TLS / Tailscale.** Connecting over an encrypted link (Tailscale Serve or public HTTPS) could force-close the app with a `NetworkOnMainThreadException` as the connection came up — a live SSL socket was being closed on the main thread during client teardown, and a TLS close performs a network write. Socket teardown now always runs off the main thread, so connecting over a secured link is stable. Plain-LAN connections were never affected.
---
## Upgrade notes
- All changes are client-side and available on **both** flavors (no Device Control needed).
- `appVersionCode` is **16**.
- This is an app-side fix on **both** flavors — no Device Control or server changes needed.
- If you were crashing on connect over Tailscale or HTTPS, update and reconnect.
- `appVersionCode` is **17**.
@@ -1,7 +1,3 @@
v1.2.2 — Multi-profile polish.
v1.2.3 — Connection crash fix.
• Deleting a session on a non-default profile now sticks — no more reappearing.
• Cold start opens the session list on the right profile instead of flashing the default one.
• Diagnostics is now a full-screen health-check list with clear status and the reason when something's wrong.
• The default connection is simply "Hermes" (power features are "Relay").
• Distraction-free chat mode gives its text more room and scrolls.
• Fixed a crash that could close the app right after connecting over an encrypted link (Tailscale or HTTPS). Connecting over a secured connection is now stable. Plain local-network connections were never affected.
+13
View File
@@ -1,5 +1,18 @@
{
"versions": [
{
"version": "1.2.3",
"title": "Connection crash fix",
"date": "2026-06-23",
"sections": [
{
"header": "Stability",
"bullets": [
"Fixed a crash that could close the app right after connecting over an encrypted link (Tailscale or HTTPS) — a live secure connection was being torn down on the main thread as it came up. Securing your connection no longer force-closes the app; plain-LAN connections were never affected."
]
}
]
},
{
"version": "1.2.2",
"title": "Multi-profile polish",
+5 -16
View File
@@ -1,17 +1,6 @@
v1.2.2 - Multi-profile polish
v1.2.3 - Connection crash fix
Profiles that behave
* Deleting a session on a non-default agent profile now sticks — it no longer
reappears after the list refreshes.
* On a cold start with a non-default profile selected, the session list opens
on that profile's chats directly instead of flashing the default profile's.
Clearer diagnostics
* Diagnostics is now a full screen that leads with a top-to-bottom list of
health checks — network, server, chat, pairing, relay, and voice — each with
a clear status and the reason when something's wrong. Tap a failing check for
detail; the recent-activity log stays below.
Small touches
* The default connection is simply "Hermes" now (power features are "Relay").
* Distraction-free chat mode gives its text a taller, scrollable area.
Stability
* Fixed a crash that could close the app right after connecting over an
encrypted link (Tailscale or HTTPS). Securing your connection no longer
force-closes the app. Plain-LAN connections were never affected.
@@ -0,0 +1,29 @@
package com.hermesandroid.relay.network
import android.os.Looper
/**
* Run an OkHttp teardown [block] without ever performing a network write on
* the main thread.
*
* [okhttp3.ConnectionPool.evictAll] closes pooled sockets synchronously. For
* a live `https`/`wss` keep-alive connection that close drains the SSL output
* queue — a real network write (`SSLOutputStream.writeInternal`) — which trips
* StrictMode's [android.os.NetworkOnMainThreadException]. Reported as a hard
* crash on connect over TLS/Tailscale (issues #70 / #118 / #124): a
* `viewModelScope` (i.e. `Dispatchers.Main.immediate`) coroutine resumes on the
* main thread and shuts a dashboard/API client down in a `finally` block.
*
* Client shutdown is fire-and-forget cleanup, so when the caller is on the main
* thread we hand [block] to a short-lived daemon thread. Off the main thread
* (already on `Dispatchers.IO` or a background thread) we run it inline so
* callers that deliberately moved off main keep their ordering and any blocking
* `awaitTermination` waits stay where the caller put them.
*/
internal fun shutdownOffMainThread(threadName: String, block: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Thread({ runCatching(block) }, threadName).apply { isDaemon = true }.start()
} else {
block()
}
}
@@ -14,6 +14,7 @@ import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import com.hermesandroid.relay.network.relay.models.Envelope
import com.hermesandroid.relay.network.shared.EndpointResolver
import com.hermesandroid.relay.network.shutdownOffMainThread
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -705,8 +706,12 @@ class ConnectionManager(
disconnect()
unregisterNetworkCallback()
supervisorJob.cancel()
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
// evictAll() closes live wss sockets synchronously; on a TLS keep-alive
// that close is a network write, so keep it off the main thread.
shutdownOffMainThread("ConnectionManager-shutdown") {
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
}
}
fun send(envelope: Envelope) {
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.network.upstream
import android.content.Context
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.shutdownOffMainThread
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.MessageListResponse
import com.hermesandroid.relay.network.upstream.models.SessionItem
@@ -513,15 +514,26 @@ class DashboardApiClient(
.get()
.build()
okHttpClient.newCall(request).execute().use { response ->
if (response.code == 401 || response.code == 403) {
return@withContext Result.success(DashboardAuthSession(authenticated = false))
// try/catch is NOT optional here: currentSession() returns a Result and
// callers (probeStandardVoice on a viewModelScope/Main coroutine) rely
// on it NEVER throwing. A raw execute() re-threw transient network
// failures — e.g. a stale pooled connection over Tailscale aborting
// ("Software caused connection abort") — straight past withContext(IO)
// and crashed the app on the main thread. Mirror executeJson()'s
// contract: every failure becomes Result.failure.
try {
okHttpClient.newCall(request).execute().use { response ->
when {
response.code == 401 || response.code == 403 ->
Result.success(DashboardAuthSession(authenticated = false))
!response.isSuccessful ->
Result.failure(apiFailure(response, "Dashboard session"))
else ->
Result.success(parseAuthSession(response.readJsonObject(json)))
}
}
if (!response.isSuccessful) {
return@withContext Result.failure(apiFailure(response, "Dashboard session"))
}
val root = response.readJsonObject(json)
Result.success(parseAuthSession(root))
} catch (e: Exception) {
Result.failure(e)
}
}
@@ -574,7 +586,7 @@ class DashboardApiClient(
fun gatewayWebSocketUrl(ticket: String, path: String = "/api/ws"): String? =
gatewayWebSocketUrl(baseUrl = baseUrl, ticket = ticket, path = path)
fun shutdown() {
fun shutdown() = shutdownOffMainThread("DashboardApiClient-shutdown") {
okHttpClient.dispatcher.executorService.shutdown()
okHttpClient.connectionPool.evictAll()
}
@@ -5,6 +5,7 @@ import android.os.Looper
import android.util.Log
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.AppAnalytics
import com.hermesandroid.relay.network.shutdownOffMainThread
import com.hermesandroid.relay.network.upstream.models.CreateSessionRequest
import com.hermesandroid.relay.network.upstream.models.HermesSseEvent
import com.hermesandroid.relay.network.upstream.models.MessageItem
@@ -1343,7 +1344,7 @@ class HermesApiClient(
// --- Lifecycle ---
fun shutdown() {
fun shutdown() = shutdownOffMainThread("HermesApiClient-shutdown") {
client.dispatcher.executorService.shutdown()
try {
if (!client.dispatcher.executorService.awaitTermination(2, TimeUnit.SECONDS)) {
@@ -3446,6 +3446,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
url = dashboardUrl,
)
}
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
// Defense-in-depth: this runs in a viewModelScope (Main) coroutine,
// so an unexpected throw from any probe sub-call would crash the
// app (see the currentSession() stale-connection crash). A probe
// failure must only degrade the UI, never be fatal.
android.util.Log.w("ConnectionVM", "probeStandardVoice failed: ${e.message}")
_standardVoiceAvailability.value = StandardVoiceAvailability.Unreachable
_standardAudioApiReachable.value = false
_serverChatDisplaySettings.value = null
updateGatewayAvailability(GatewayAvailability.Unreachable)
} finally {
client.shutdown()
}
@@ -5366,21 +5378,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
override fun onCleared() {
super.onCleared()
connectionManager.shutdown()
// ViewModel.onCleared runs on the main thread and viewModelScope
// is already being cancelled — fire-and-forget the client
// shutdown on a plain background Thread so
// ConnectionPool.evictAll doesn't trip
// onCleared runs on the main thread, but every client's shutdown()
// routes ConnectionPool.evictAll() (a synchronous TLS socket close /
// network write) off the main thread internally via
// shutdownOffMainThread, so these direct calls can't trip
// NetworkOnMainThreadException on live SSL sockets.
_apiClient.value?.let { client ->
Thread({ runCatching { client.shutdown() } }, "HermesApiClient-shutdown").start()
}
profileChatApiClient?.let { client ->
Thread(
{ runCatching { client.shutdown() } },
"HermesProfileApiClient-shutdown",
).start()
}
connectionManager.shutdown()
_apiClient.value?.shutdown()
profileChatApiClient?.shutdown()
tailscaleDetector.shutdown()
// Release the cached VirtualDisplay + ImageReader + HandlerThread
// built by ScreenCapture on the first /screenshot call. Without
@@ -0,0 +1,63 @@
package com.hermesandroid.relay.network
import android.os.Looper
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* Guards the fix for the `NetworkOnMainThreadException` crash (issues #70 /
* #118 / #124): client `shutdown()` reaches `ConnectionPool.evictAll()`, which
* closes live TLS sockets with a synchronous network write. The teardown block
* must never execute on the main thread.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class NetworkShutdownTest {
@Test
fun whenCalledOnMainThread_runsTeardownOffTheMainThread() {
// Robolectric drives the test body on the main looper — the same place
// a viewModelScope (Dispatchers.Main.immediate) coroutine resumes and
// shuts a dashboard/API client down in a `finally` block.
assertSame(Looper.myLooper(), Looper.getMainLooper())
val mainThread = Looper.getMainLooper().thread
val ranOn = AtomicReference<Thread>()
val latch = CountDownLatch(1)
shutdownOffMainThread("test-shutdown") {
ranOn.set(Thread.currentThread())
latch.countDown()
}
assertTrue("teardown block never ran", latch.await(5, TimeUnit.SECONDS))
assertNotSame(
"evictAll must not run on the main thread",
mainThread,
ranOn.get(),
)
}
@Test
fun whenCalledOffMainThread_runsTeardownInline() {
val ranOn = AtomicReference<Thread>()
val latch = CountDownLatch(1)
val worker = Thread {
shutdownOffMainThread("test-shutdown") { ranOn.set(Thread.currentThread()) }
latch.countDown()
}
worker.start()
assertTrue(latch.await(5, TimeUnit.SECONDS))
// Off the main thread the block runs inline (no extra hop), preserving
// the blocking awaitTermination semantics for callers already off main.
assertSame(worker, ranOn.get())
}
}
@@ -7,6 +7,7 @@ import kotlinx.serialization.json.jsonObject
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -56,6 +57,20 @@ class DashboardApiClientTest {
assertEquals("0.16.0", status.version)
}
@Test
fun currentSession_onConnectionAbort_returnsFailure_doesNotThrow() = runTest {
// Reproduces the crash: a stale pooled connection aborting mid-flight
// ("Software caused connection abort"). currentSession() returns a
// Result, so a network failure MUST surface as Result.failure — never a
// throw that escapes withContext(IO) and crashes the Main coroutine.
server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START))
val client = DashboardApiClient(baseUrl = server.url("/").toString())
val result = client.currentSession()
assertTrue("network abort must be Result.failure, not a throw", result.isFailure)
}
@Test
fun getStatus_acceptsProviderObjects() = runTest {
server.enqueue(
+2 -6
View File
@@ -83,13 +83,9 @@ This app is a community project and is not affiliated with or endorsed by NousRe
Paste into Play Console → **What's new** (≤500 characters):
```
v1.2.1 — Polish & control.
v1.2.3 — Connection crash fix.
• Lock the app to a single agent profile and hide the rest.
• In-app "What's New" with current and past release notes.
• Diagnostics with clean error titles and one-tap reporting.
• A tasteful, dismissable "update available" nudge.
• Voice fixes: Stop halts speech instantly, steadier hold-to-talk, a more readable overlay, and chosen voices apply in Auto mode.
• Fixed a crash that could close the app right after connecting over an encrypted link (Tailscale or HTTPS). Connecting over a secured connection is now stable. Plain local-network connections were never affected.
```
## Category
+2 -2
View File
@@ -1,6 +1,6 @@
[versions]
appVersionName = "1.2.2"
appVersionCode = "16"
appVersionName = "1.2.3"
appVersionCode = "17"
agp = "9.2.1"
kotlin = "2.4.0"
compose-bom = "2026.06.00"