Compare commits

..
Author SHA1 Message Date
Bailey Dixon 5fc85c1699 chore: refresh plugin-only dev tip before merge
# Conflicts:
#	CHANGELOG.md
2026-08-31 19:53:02 -04:00
Bailey Dixon c01c6cf457 Merge pull request #520 from Codename-11/fix/plugin-manifest-installer-compat
fix(plugin): restore native installer compatibility
2026-08-31 19:50:43 -04:00
Bailey Dixon 22780881e1 Merge remote-tracking branch 'origin/dev' into fix/plugin-manifest-installer-compat
# Conflicts:
#	CHANGELOG.md
2026-08-31 19:45:59 -04:00
Bailey Dixon 201e204290 fix(plugin): restore native installer compatibility 2026-08-31 19:45:38 -04:00
Bailey Dixon eb8434e508 chore: refresh chat transport base before passive session activity merge
# Conflicts:
#	CHANGELOG.md
#	docs/spec.md
2026-08-31 19:41:41 -04:00
Bailey Dixon 597b13e2db Merge pull request #515 from Codename-11/fix/android-chat-transport-affinity
fix(android): keep chat transport ownership stable
2026-08-31 19:35:59 -04:00
Bailey Dixon 946b333109 chore: refresh origin/dev before merging passive session activity
# Conflicts:
#	CHANGELOG.md
2026-08-31 19:32:34 -04:00
Bailey Dixon 8b3731b22f chore(android): refresh localization status 2026-08-31 19:20:43 -04:00
Bailey Dixon b76ba7a314 Merge remote-tracking branch 'origin/dev' into fix/android-chat-transport-affinity
# Conflicts:
#	CHANGELOG.md
2026-08-31 18:37:03 -04:00
Bailey Dixon 2c15bd4207 fix(android): clarify gateway connection status 2026-08-31 18:36:25 -04:00
Bailey Dixon 949add15b1 Merge pull request #512 from Codename-11/fix/android-compaction-watchdog
fix(android): preserve gateway turns during context compaction
2026-08-31 17:09:07 -04:00
Bailey Dixon 6a93d13ecb Merge origin/dev into fix/android-compaction-watchdog
# Conflicts:
#	CHANGELOG.md
2026-08-31 16:56:15 -04:00
Bailey Dixon cbc02bb407 Merge pull request #514 from Codename-11/fix/android-emulator-testing
test(android): add on-demand emulator coverage
2026-08-31 16:49:11 -04:00
Bailey Dixon 525f6b5fc0 Merge origin/dev into fix/android-compaction-watchdog 2026-08-31 16:41:54 -04:00
Bailey Dixon de8f5558c2 Merge origin/dev into fix/android-emulator-testing 2026-08-31 16:37:42 -04:00
Bailey Dixon 58e8b1edb6 Merge remote-tracking branch 'origin/dev' into fix/android-chat-transport-affinity 2026-08-31 16:37:31 -04:00
Bailey Dixon adcf4ded79 Merge pull request #517 from Codename-11/fix/android-supervised-parent-secret
fix(android): require app-specific supervised parent access
2026-08-31 16:36:44 -04:00
Bailey Dixon 05d6ee4d7c Merge origin/dev into fix/android-emulator-testing 2026-08-31 16:25:48 -04:00
Bailey Dixon d42fa91698 Merge remote-tracking branch 'origin/dev' into fix/android-chat-transport-affinity 2026-08-31 16:25:42 -04:00
Bailey Dixon 41cbafddba Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 16:24:21 -04:00
Bailey Dixon a2be512c45 chore: refresh origin/dev before passive session activity handoff 2026-08-31 16:23:58 -04:00
Bailey Dixon 6a66710763 Merge origin/dev into fix/android-compaction-watchdog 2026-08-31 16:22:08 -04:00
Bailey Dixon 8632ced503 Merge pull request #516 from Codename-11/fix/android-on-demand-dispatch
fix(ci): route Android presets through registered workflow
2026-08-31 16:21:53 -04:00
Bailey Dixon ae18bbee24 Merge origin/dev into fix/android-emulator-testing
# Conflicts:
#	AGENTS.md
#	app/src/main/kotlin/com/hermesandroid/relay/network/upstream/DashboardApiClient.kt
#	app/src/main/kotlin/com/hermesandroid/relay/runtime/HermesRuntimeBinder.kt
#	app/src/main/kotlin/com/hermesandroid/relay/viewmodel/ChatViewModel.kt
#	app/src/test/kotlin/com/hermesandroid/relay/network/upstream/DashboardApiClientTest.kt
2026-08-31 16:13:34 -04:00
Bailey Dixon 9690071e7d Merge remote-tracking branch 'origin/dev' into fix/android-chat-transport-affinity 2026-08-31 16:07:06 -04:00
Bailey Dixon 698b45cbb3 fix(android): avoid cold-start chat owner crash 2026-08-31 16:05:03 -04:00
Bailey Dixon 55a838cb78 merge: refresh Android dispatcher with dev 2026-08-31 16:04:29 -04:00
Bailey Dixon afa875d89f chore: merge origin/dev into passive session activity fix 2026-08-31 16:02:37 -04:00
Bailey Dixon aff758fb99 fix(android): project passive session activity 2026-08-31 16:00:26 -04:00
Bailey Dixon 8625963846 Merge origin/dev into fix/android-compaction-watchdog 2026-08-31 16:00:20 -04:00
Bailey Dixon d367cd3a24 Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 15:59:55 -04:00
Bailey Dixon 5bd0b2acaf Merge pull request #513 from Codename-11/fix/android-dashboard-history-auth-recovery
fix(android): recover Dashboard history auth failures
2026-08-31 15:59:09 -04:00
Bailey Dixon 6f0948ca01 Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 15:58:43 -04:00
Bailey Dixon 541a7c078d fix(android): require app-specific supervised parent access 2026-08-31 15:51:20 -04:00
Bailey Dixon e0b726de85 Merge origin/dev into fix/android-compaction-watchdog 2026-08-31 15:51:12 -04:00
Bailey Dixon 8865a31013 fix(ci): route Android presets through registered workflow 2026-08-31 15:49:43 -04:00
Bailey Dixon a199c35377 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 15:47:36 -04:00
Bailey Dixon 6a495b6e06 Merge pull request #511 from Codename-11/chore/android-cloud-verification
ci(android): prefer cloud verification lanes
2026-08-31 15:43:32 -04:00
Bailey Dixon 105da550e7 docs: note Android history auth recovery 2026-08-31 15:32:40 -04:00
Bailey Dixon 23c06d60b9 ci(android): prefer cloud verification lanes 2026-08-31 15:29:06 -04:00
Bailey Dixon febc26fe35 Merge origin/dev into fix/android-emulator-testing 2026-08-31 15:12:55 -04:00
Bailey Dixon 28a906215d test(android): add managed emulator coverage 2026-08-31 15:12:44 -04:00
Bailey Dixon 1617f75f1a Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 14:32:44 -04:00
Bailey Dixon dbf71a87f4 Merge remote-tracking branch 'origin/dev' into fix/android-chat-transport-affinity 2026-08-31 14:22:36 -04:00
Bailey Dixon 95ed8e6edb fix(android): bind chat conversations to one transport 2026-08-31 14:22:26 -04:00
Bailey Dixon d26bf6c25b Merge origin/dev into fix/android-compaction-watchdog
# Conflicts:
#	DEVLOG.md
2026-08-31 14:10:59 -04:00
Bailey Dixon 181e10f2ad test(android): cover compaction watchdog leases 2026-08-31 14:09:57 -04:00
Bailey Dixon 78203fd8a1 Merge pull request #510 from Codename-11/fix/android-generated-image-retention
fix(android): retain generated image results
2026-08-31 14:03:44 -04:00
Bailey Dixon c519502551 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 13:38:13 -04:00
Bailey Dixon 814afc56da fix(android): retain generated image results 2026-08-31 13:37:22 -04:00
Bailey Dixon 1f055cb91f Merge pull request #507 from Codename-11/fix/android-supervised-gateway-salvage
fix(android): harden supervised Gateway setup
2026-08-31 13:36:26 -04:00
Bailey Dixon 936b9bed8a Merge pull request #508 from Codename-11/feature/android-release-notes-expansion
feat(android): make What's New a complete release record
2026-08-31 13:31:19 -04:00
Bailey Dixon dafa6f3a18 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 13:23:33 -04:00
Bailey Dixon 245362d58e Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion 2026-08-31 13:21:40 -04:00
Bailey Dixon 857a1551f3 Merge origin/dev into fix/android-compaction-watchdog 2026-08-31 13:17:04 -04:00
Bailey Dixon 95e78e0657 Merge pull request #509 from Codename-11/chore/android-build-lane
chore(android): serialize Windows build lanes
2026-08-31 13:14:56 -04:00
JackandClaude Opus 5 00052d20d9 watchdog: arm longer leash on compacting status instead of killing silent compaction
Server-side context compaction summarizes the transcript with NO deltas
or tool events flowing until it finishes. Near the context ceiling that
silence routinely exceeds TURN_TIMEOUT_MS (180s), so the idle watchdog
fired session.interrupt on a healthy compression, rolled back its work,
and retriggered on the next prompt — an infinite 'Operation interrupted'
loop that makes near-full sessions permanently unresponsive from mobile.

Observed against a live gateway: four turns killed at exactly
prompt+~251s (visible tool work + 180.0s of silent compaction), server
compression telemetry aborted at 180469/180233/180219ms with
failure_class=explicit_interrupt.

Fix: treat a status.update event with kind 'compacting' like the ask
events that already arm longer leashes (same watchdogTimeoutFor seam):
arm COMPACTING_TIMEOUT_MS (600s) instead of the 180s default. Any
regular event rearms TURN_TIMEOUT_MS as before. Pairs with the gateway
fix that emits periodic compacting heartbeats during compression
(NousResearch/hermes-agent#98371); a single compacting event at
compaction start already engages the longer leash on current gateways.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 13:14:35 -04:00
Bailey Dixon 246d9f1010 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 12:49:28 -04:00
Bailey Dixon e9f32673be fix(android): recover dashboard history auth failures 2026-08-31 12:49:13 -04:00
Bailey DixonandUpbeat7898 7b390fa99f fix(android): harden supervised gateway setup
Co-authored-by: Upbeat7898 <upbeat7898@noreply.git.meberthosting.de>
2026-08-31 12:47:41 -04:00
Bailey Dixon cd856da6a0 Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion
# Conflicts:
#	app/src/test/kotlin/com/hermesandroid/relay/screenshots/ChangelogHistoryScreenshotTest.kt
#	app/src/test/kotlin/com/hermesandroid/relay/screenshots/WhatsNewToastScreenshotTest.kt
2026-08-31 12:46:18 -04:00
Bailey Dixon 9a40aedb7d chore(android): serialize Windows build lanes 2026-08-31 12:46:03 -04:00
Bailey Dixon 30eb70daa3 Merge pull request #506 from Codename-11/fix/android-whats-new-tests
test(android): refresh v1.14 What's New assertions
2026-08-31 12:14:32 -04:00
Bailey Dixon 6be6cec201 test(android): refresh v1.14 What's New assertions 2026-08-31 12:03:24 -04:00
Bailey Dixon 4f5f3fac10 Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion
# Conflicts:
#	CHANGELOG.md
2026-08-31 11:43:28 -04:00
Bailey Dixon 7f7112caf2 feat(android): expand in-app release notes 2026-08-31 11:42:53 -04:00
Bailey Dixon 4c00e8edb7 Merge pull request #499 from Codename-11/dependabot/github_actions/dev/actions/setup-java-6
chore(deps): bump actions/setup-java from 5 to 6
2026-08-31 11:08:59 -04:00
Bailey Dixon 44f0acec94 Merge pull request #505 from Codename-11/fix/android-bot-chat-binding-lifecycle-refresh
fix(android): render Bot Chat history after binding
2026-08-31 11:08:15 -04:00
Bailey Dixonandlayerflex c8cd13e5bc fix(android): render bot chat history after binding
Preserve the route-owned ChatHandler as the rendered state source from first composition and cover fast/delayed history plus handler replacement and on-device lifecycle recovery.

Supersedes PR #453 while preserving contributor credit.

Co-authored-by: layerflex <254160994+layerflex@users.noreply.github.com>
2026-08-31 10:08:20 -04:00
Bailey Dixon ad4175bb6d test(android): remove obsolete clean chat instrumentation 2026-08-31 10:08:20 -04:00
dependabot[bot] 6b7cb706e0 chore(deps): bump coil from 3.5.0 to 3.6.0 (#502)
Bumps `coil` from 3.5.0 to 3.6.0.

Updates `io.coil-kt.coil3:coil-compose` from 3.5.0 to 3.6.0
- [Release notes](https://github.com/coil-kt/coil/releases)
- [Changelog](https://github.com/coil-kt/coil/blob/main/CHANGELOG.md)
- [Commits](https://github.com/coil-kt/coil/compare/3.5.0...3.6.0)

Updates `io.coil-kt.coil3:coil-gif` from 3.5.0 to 3.6.0
- [Release notes](https://github.com/coil-kt/coil/releases)
- [Changelog](https://github.com/coil-kt/coil/blob/main/CHANGELOG.md)
- [Commits](https://github.com/coil-kt/coil/compare/3.5.0...3.6.0)

Updates `io.coil-kt.coil3:coil-network-okhttp` from 3.5.0 to 3.6.0
- [Release notes](https://github.com/coil-kt/coil/releases)
- [Changelog](https://github.com/coil-kt/coil/blob/main/CHANGELOG.md)
- [Commits](https://github.com/coil-kt/coil/compare/3.5.0...3.6.0)

---
updated-dependencies:
- dependency-name: io.coil-kt.coil3:coil-compose
  dependency-version: 3.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: io.coil-kt.coil3:coil-gif
  dependency-version: 3.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: io.coil-kt.coil3:coil-network-okhttp
  dependency-version: 3.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 12:00:18 +00:00
dependabot[bot] 6031427ffb chore(deps): bump haze from 1.7.2 to 1.7.3 (#504)
Bumps `haze` from 1.7.2 to 1.7.3.

Updates `dev.chrisbanes.haze:haze` from 1.7.2 to 1.7.3
- [Release notes](https://github.com/chrisbanes/haze/releases)
- [Changelog](https://github.com/chrisbanes/haze/blob/1.7.3/CHANGELOG.md)
- [Commits](https://github.com/chrisbanes/haze/compare/1.7.2...1.7.3)

Updates `dev.chrisbanes.haze:haze-materials` from 1.7.2 to 1.7.3
- [Release notes](https://github.com/chrisbanes/haze/releases)
- [Changelog](https://github.com/chrisbanes/haze/blob/1.7.3/CHANGELOG.md)
- [Commits](https://github.com/chrisbanes/haze/compare/1.7.2...1.7.3)

---
updated-dependencies:
- dependency-name: dev.chrisbanes.haze:haze
  dependency-version: 1.7.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: dev.chrisbanes.haze:haze-materials
  dependency-version: 1.7.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 11:59:10 +00:00
dependabot[bot] 53dd21400a chore(deps): bump org.jetbrains.compose from 1.11.1 to 1.12.0 (#503)
Bumps [org.jetbrains.compose](https://github.com/JetBrains/compose-multiplatform) from 1.11.1 to 1.12.0.
- [Release notes](https://github.com/JetBrains/compose-multiplatform/releases)
- [Changelog](https://github.com/JetBrains/compose-multiplatform/blob/master/CHANGELOG.md)
- [Commits](https://github.com/JetBrains/compose-multiplatform/compare/v1.11.1...v1.12.0)

---
updated-dependencies:
- dependency-name: org.jetbrains.compose
  dependency-version: 1.12.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 11:58:09 +00:00
dependabot[bot] 802a0b0844 chore(deps): bump androidx.navigation:navigation-compose (#501)
Bumps androidx.navigation:navigation-compose from 2.9.8 to 2.10.0.

---
updated-dependencies:
- dependency-name: androidx.navigation:navigation-compose
  dependency-version: 2.10.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 11:57:10 +00:00
dependabot[bot] 7658329ca7 chore(deps): bump markdown-renderer from 0.44.0 to 0.45.0 (#500)
Bumps `markdown-renderer` from 0.44.0 to 0.45.0.

Updates `com.mikepenz:multiplatform-markdown-renderer-m3` from 0.44.0 to 0.45.0
- [Release notes](https://github.com/mikepenz/multiplatform-markdown-renderer/releases)
- [Changelog](https://github.com/mikepenz/multiplatform-markdown-renderer/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/mikepenz/multiplatform-markdown-renderer/compare/v0.44.0...v0.45.0)

Updates `com.mikepenz:multiplatform-markdown-renderer-code` from 0.44.0 to 0.45.0
- [Release notes](https://github.com/mikepenz/multiplatform-markdown-renderer/releases)
- [Changelog](https://github.com/mikepenz/multiplatform-markdown-renderer/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/mikepenz/multiplatform-markdown-renderer/compare/v0.44.0...v0.45.0)

---
updated-dependencies:
- dependency-name: com.mikepenz:multiplatform-markdown-renderer-m3
  dependency-version: 0.45.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: com.mikepenz:multiplatform-markdown-renderer-code
  dependency-version: 0.45.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 11:56:41 +00:00
dependabot[bot] 1622db0b23 chore(deps): bump the testing group with 2 updates (#498)
Bumps the testing group with 2 updates: [io.github.takahirom.roborazzi:roborazzi](https://github.com/takahirom/roborazzi) and [io.github.takahirom.roborazzi:roborazzi-compose](https://github.com/takahirom/roborazzi).


Updates `io.github.takahirom.roborazzi:roborazzi` from 1.72.0 to 1.73.0
- [Release notes](https://github.com/takahirom/roborazzi/releases)
- [Commits](https://github.com/takahirom/roborazzi/compare/1.72.0...1.73.0)

Updates `io.github.takahirom.roborazzi:roborazzi-compose` from 1.72.0 to 1.73.0
- [Release notes](https://github.com/takahirom/roborazzi/releases)
- [Commits](https://github.com/takahirom/roborazzi/compare/1.72.0...1.73.0)

---
updated-dependencies:
- dependency-name: io.github.takahirom.roborazzi:roborazzi
  dependency-version: 1.73.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: testing
- dependency-name: io.github.takahirom.roborazzi:roborazzi-compose
  dependency-version: 1.73.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: testing
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-31 11:56:30 +00:00
dependabot[bot] 41b724e072 chore(deps): bump actions/setup-java from 5 to 6
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5 to 6.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-31 11:56:27 +00:00
Bailey Dixon bca3cd0e48 fix(plugin): harden Git workspace path containment (#492) 2026-08-30 23:30:51 -04:00
Bailey Dixon bb2f1e6c0c fix(plugin): harden Git workspace path containment 2026-08-30 23:28:51 -04:00
Bailey Dixon ff23d54332 Merge pull request #491 from Codename-11/fix/release-desktop-ui-assets
chore(website): refresh desktop UI source fingerprint
2026-08-30 22:28:31 -04:00
Bailey Dixon a4a0575688 chore(website): refresh desktop UI source fingerprint 2026-08-30 22:26:55 -04:00
Bailey Dixon 0509ac8377 Merge pull request #489 from Codename-11/release/android-plugin-cli-2026-08-30
release: prepare Android 1.14.0, Plugin 1.11.0, and CLI+UI beta.6
2026-08-30 22:01:55 -04:00
Bailey Dixon 3fdc2260dd release: prepare Android 1.14.0, Plugin 1.11.0, and CLI+UI beta.6 2026-08-30 21:50:10 -04:00
Bailey Dixon 1800bee7b1 Merge pull request #488 from Codename-11/integration/android-live-fixes
feat: integrate Android live fixes and Dashboard routing
2026-08-30 21:41:19 -04:00
181 changed files with 6762 additions and 1717 deletions
-38
View File
@@ -1,38 +0,0 @@
## Summary
<!-- Brief description of what this PR does -->
## Changes
-
## Verification
<!-- List the checks you ran, or explain why a check is not applicable. -->
-
## Lineage / contributor credit
<!--
If this PR salvages or supersedes earlier work, link every source PR and name
the original contributor(s). Preserve original commit authors where practical;
otherwise use verified Co-authored-by trailers. Write "N/A" for original work.
-->
- Source PR(s): N/A
- Attribution preserved by: N/A
## Checklist
- [ ] Target branch is `dev`, unless this is a `dev` → `main` release PR or a focused production-tag hotfix PR to `main`
- [ ] Android changes: lint and focused unit tests ran, or rationale is listed above
- [ ] Translation changes: locale status/review references are accurate, `python scripts/check-android-locales.py` ran, and device/emulator review is documented, or N/A
- [ ] Server changes: focused `python -m unittest ...` checks ran, or rationale is listed above
- [ ] Desktop changes: `npm run build` or a narrower documented check ran, or rationale is listed above
- [ ] Docs/site changes: docs build or link check ran, or rationale is listed above
- [ ] UI changes were tested on emulator/device or desktop surface when applicable
- [ ] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
- [ ] CHANGELOG.md updated (if user-facing)
- [ ] Public writing hygiene checked: no secrets, private infrastructure, personal names, or AI/process narration
- [ ] Salvaged work links the source PR and preserves contributor authorship, or N/A
+5 -4
View File
@@ -5,9 +5,8 @@ not `AGENTS.md`) picks up the project's agent guidance.
**Read [AGENTS.md](../AGENTS.md) first — it is the single source of truth**
for agent guidance: the entry point, the non-negotiables, and the public-repo
writing hygiene. It links on to `CLAUDE.md` for the deep reference
(architecture, upstream Hermes API, repository layout, per-language code style,
the dev loop, and the Key Files map). Follow those; don't restate them here.
writing hygiene. `CLAUDE.md` imports that same canonical file. Follow
`AGENTS.md` and its linked project records; don't restate them here.
Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
@@ -17,6 +16,8 @@ Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
- **Conventional Commits**, `main`/`dev` branching — feature branches off
`dev`, `--no-ff` merges, tags cut from `main`.
- **Android:** Jetpack Compose (no XML), kotlinx.serialization (no Gson),
OkHttp (no Ktor), `wss://` only; run `./gradlew lint` before pushing Kotlin.
OkHttp (no Ktor), `wss://` only. Narrow local checks use the Android lane;
pushed exact SHAs prefer `Android On-Demand` for heavy verification; full
local pre-push remains an explicit fallback.
- **Public repo:** no personal names, no private infrastructure, no
AI/assistant self-narration in committed prose.
+4 -1
View File
@@ -18,8 +18,11 @@ function classifyCiPaths(paths) {
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
'scripts/check-android-collection-apis.py', 'scripts/check-android-native-compat.py',
'scripts/check-android-release-notes.py',
'scripts/android-lane.ps1', 'scripts/android-prepush.py', 'scripts/dev.bat', 'scripts/dev.sh',
'scripts/tests/android_prepush_test.py',
'scripts/tests/check_android_native_compat_test.py',
'scripts/tests/check_android_release_notes_test.py', '.github/workflows/ci-android.yml',
'scripts/tests/check_android_release_notes_test.py',
'.github/workflows/android-on-demand.yml', '.github/workflows/ci-android.yml',
'.github/workflows/play-preflight-android.yml',
'.github/workflows/approve-release-android.yml',
'.github/workflows/release-android.yml',
@@ -18,6 +18,12 @@ assert.deepEqual(classifyCiPaths(['relay-core/src/main/kotlin/Wire.kt']), { ...n
assert.deepEqual(classifyCiPaths(['scripts/check-android-release-notes.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/check-android-native-compat.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_native_compat_test.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/android-lane.ps1']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/android-prepush.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/dev.bat']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/dev.sh']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/tests/android_prepush_test.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['.github/workflows/android-on-demand.yml']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['plugin/relay/server.py']), { ...none, plugin: true });
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
assert.deepEqual(classifyCiPaths(['user-docs/index.md']), { ...none, docs: true });
+226
View File
@@ -0,0 +1,226 @@
name: Android On-Demand
run-name: Android ${{ inputs.preset }} · ${{ inputs.head_sha }}
on:
workflow_call:
inputs:
head_sha:
required: true
type: string
preset:
required: true
type: string
permissions:
contents: read
concurrency:
group: android-on-demand-${{ inputs.head_sha }}-${{ inputs.preset }}
cancel-in-progress: false
jobs:
validate:
name: Validate exact SHA
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Validate input shape
shell: bash
env:
REQUESTED_SHA: ${{ inputs.head_sha }}
REQUESTED_PRESET: ${{ inputs.preset }}
run: |
if [[ ! "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]; then
echo "head_sha must be a full lowercase 40-character commit SHA" >&2
exit 2
fi
case "$REQUESTED_PRESET" in
focused|lint|assemble-debug|release-smoke|all-final) ;;
*)
echo "unsupported Android preset: $REQUESTED_PRESET" >&2
exit 2
;;
esac
- name: Checkout exact commit
uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
fetch-depth: 1
- name: Confirm checkout identity
shell: bash
env:
REQUESTED_SHA: ${{ inputs.head_sha }}
run: test "$(git rev-parse HEAD)" = "$REQUESTED_SHA"
focused:
name: Focused Android checks
needs: validate
if: ${{ inputs.preset == 'focused' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Run repository checks and focused sideload tests
run: python3 scripts/android-prepush.py --skip-lint
- name: Run the same focused tests for Google Play
shell: bash
run: |
mapfile -t focused_tests < <(python3 -c \
"import runpy; print(*runpy.run_path('scripts/android-prepush.py')['FOCUSED_TESTS'], sep='\n')")
test_args=()
for test_name in "${focused_tests[@]}"; do
test_args+=(--tests "$test_name")
done
./gradlew :app:testGooglePlayDebugUnitTest "${test_args[@]}" --console=plain
- name: Upload failed test reports
uses: actions/upload-artifact@v7
if: failure()
with:
name: focused-test-reports-${{ inputs.head_sha }}
path: app/build/reports/tests/
if-no-files-found: ignore
retention-days: 7
lint:
name: Android lint
needs: validate
if: ${{ inputs.preset == 'lint' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Validate Android repository inputs
run: |
python3 scripts/check-android-locales.py
python3 scripts/check-user-docs-locales.py
python3 scripts/check-android-collection-apis.py
python3 scripts/check-android-release-notes.py
python3 scripts/check-version-tracks.py
if [[ -f scripts/tests/android_prepush_test.py ]]; then
python3 -m unittest scripts.tests.android_prepush_test
fi
python3 -m unittest scripts.tests.check_android_release_notes_test
python3 -m unittest scripts.tests.check_android_native_compat_test
- name: Run Android lint
run: ./gradlew lint --console=plain
- name: Upload lint reports
uses: actions/upload-artifact@v7
if: always()
with:
name: lint-reports-${{ inputs.head_sha }}
path: app/build/reports/lint-results*
if-no-files-found: ignore
retention-days: 7
assemble-debug:
name: Assemble both debug flavors
needs: validate
if: ${{ inputs.preset == 'assemble-debug' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Build debug APKs
run: ./gradlew assembleDebug --console=plain
- name: Verify packaged native compatibility
run: |
python3 scripts/check-android-native-compat.py \
app/build/outputs/apk/googlePlay/debug/*.apk \
app/build/outputs/apk/sideload/debug/*.apk
- name: Upload debug APKs
uses: actions/upload-artifact@v7
with:
name: debug-apks-${{ inputs.head_sha }}
path: app/build/outputs/apk/*/debug/*.apk
if-no-files-found: error
retention-days: 7
release-smoke:
name: Release build smoke
needs: validate
if: ${{ inputs.preset == 'release-smoke' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 35
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Build release bundles and APKs
run: ./gradlew bundleRelease assembleRelease --console=plain
- name: Scan release DEX for unsupported collection APIs
run: |
python3 scripts/check-android-collection-apis.py \
--apk app/build/outputs/apk/googlePlay/release/*.apk \
--apk app/build/outputs/apk/sideload/release/*.apk
- name: Verify packaged native compatibility
run: |
python3 scripts/check-android-native-compat.py \
app/build/outputs/apk/googlePlay/release/*.apk \
app/build/outputs/apk/sideload/release/*.apk
- name: Upload release smoke artifacts
uses: actions/upload-artifact@v7
with:
name: release-smoke-${{ inputs.head_sha }}
path: |
app/build/outputs/apk/*/release/*.apk
app/build/outputs/bundle/**/*.aab
if-no-files-found: error
retention-days: 7
+11 -4
View File
@@ -30,6 +30,11 @@ on:
- "gradle.properties"
- "gradlew"
- "gradlew.bat"
- "scripts/android-lane.ps1"
- "scripts/android-prepush.py"
- "scripts/dev.bat"
- "scripts/dev.sh"
- "scripts/tests/android_prepush_test.py"
- "scripts/check-android-locales.py"
- "scripts/android-locale-harness.py"
- "scripts/check-android-collection-apis.py"
@@ -38,6 +43,7 @@ on:
- "scripts/tests/check_android_native_compat_test.py"
- "scripts/tests/check_android_release_notes_test.py"
- ".github/workflows/ci-android.yml"
- ".github/workflows/android-on-demand.yml"
- ".github/workflows/play-preflight-android.yml"
- ".github/workflows/approve-release-android.yml"
- ".github/workflows/release-android.yml"
@@ -61,7 +67,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -80,6 +86,7 @@ jobs:
- name: Validate Android release notes
run: |
python3 scripts/check-android-release-notes.py
python3 -m unittest scripts.tests.android_prepush_test
python3 -m unittest scripts.tests.check_android_release_notes_test
- name: Test Android native compatibility checker
@@ -101,7 +108,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -151,7 +158,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -215,7 +222,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+1
View File
@@ -101,6 +101,7 @@ jobs:
- name: Run focused Plugin tests
run: |
python -m pytest \
plugin/tests/test_manifest_compatibility.py \
plugin/tests/test_relay_security.py \
plugin/tests/test_voice_routes.py \
plugin/tests/test_session_grants.py \
+30 -9
View File
@@ -20,13 +20,25 @@ on:
description: "Exact candidate commit to check"
required: true
type: string
android_preset:
description: "Optional Android-only compute lane"
required: false
default: auto
type: choice
options:
- auto
- focused
- lint
- assemble-debug
- release-smoke
- all-final
permissions:
contents: read
pull-requests: read
concurrency:
group: ci-required-${{ github.ref }}
group: ci-required-${{ github.event_name == 'workflow_dispatch' && format('{0}-{1}', inputs.head_sha, inputs.android_preset) || github.ref }}
cancel-in-progress: true
jobs:
@@ -113,33 +125,41 @@ jobs:
android:
needs: changes
if: needs.changes.outputs.android == 'true'
if: needs.changes.outputs.android == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-android.yml
android_on_demand:
needs: changes
if: github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto'
uses: ./.github/workflows/android-on-demand.yml
with:
head_sha: ${{ inputs.head_sha }}
preset: ${{ inputs.android_preset }}
desktop:
needs: changes
if: needs.changes.outputs.desktop == 'true'
if: needs.changes.outputs.desktop == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-desktop.yml
plugin:
needs: changes
if: needs.changes.outputs.plugin == 'true'
if: needs.changes.outputs.plugin == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-plugin.yml
dashboard:
needs: changes
if: needs.changes.outputs.dashboard == 'true'
if: needs.changes.outputs.dashboard == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-dashboard.yml
contract:
needs: changes
if: needs.changes.outputs.contract == 'true'
if: needs.changes.outputs.contract == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-contract.yml
docs:
name: Build public docs
needs: changes
if: needs.changes.outputs.docs == 'true'
if: needs.changes.outputs.docs == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
runs-on: ubuntu-latest
defaults:
run:
@@ -161,11 +181,12 @@ jobs:
guard:
name: Required checks
if: always()
needs: [changes, android, desktop, plugin, dashboard, contract, docs]
needs: [changes, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
runs-on: ubuntu-latest
env:
CHANGES_RESULT: ${{ needs.changes.result }}
ANDROID_RESULT: ${{ needs.android.result }}
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
DESKTOP_RESULT: ${{ needs.desktop.result }}
PLUGIN_RESULT: ${{ needs.plugin.result }}
DASHBOARD_RESULT: ${{ needs.dashboard.result }}
@@ -176,7 +197,7 @@ jobs:
shell: bash
run: |
failed=0
for check in CHANGES ANDROID DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
for check in CHANGES ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
result_var="${check}_RESULT"
result="${!result_var}"
echo "$check: $result"
+1 -1
View File
@@ -70,7 +70,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+1 -1
View File
@@ -68,7 +68,7 @@ jobs:
fi
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+2 -2
View File
@@ -137,7 +137,7 @@ jobs:
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -176,7 +176,7 @@ jobs:
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+1
View File
@@ -85,6 +85,7 @@ jobs:
- name: Run focused Plugin tests
run: |
python -m pytest \
plugin/tests/test_manifest_compatibility.py \
plugin/tests/test_relay_security.py \
plugin/tests/test_voice_routes.py \
plugin/tests/test_session_grants.py \
+1 -1
View File
@@ -83,7 +83,7 @@ jobs:
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+22 -12
View File
@@ -7,12 +7,15 @@ coding agent (Claude Code, Codex, Cursor, etc.).
This file is the provider-neutral canonical agent context. Read it before
touching code, then `docs/spec.md` and `docs/decisions.md`. Provider adapters
such as **[CLAUDE.md](CLAUDE.md)** may add tool-specific guidance, but they do
not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
such as **[CLAUDE.md](CLAUDE.md)** import this file instead of duplicating
policy. They do not redefine the branch, release, hotfix, or verification
contract here and in `RELEASE.md`.
- Release process → **[RELEASE.md](RELEASE.md)**
- Contributor setup → **[CONTRIBUTING.md](CONTRIBUTING.md)**
- Gateway/session/reconnect testing → **[docs/gateway-contract-testing.md](docs/gateway-contract-testing.md)**
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
@@ -62,8 +65,10 @@ PR; never resolve those cases by choosing a side automatically.
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
and Vanilla Hermes voice. The API server is an optional automatic fallback and
advanced headless-compatibility surface; Relay adds optional extensions. This
and Vanilla Hermes voice. The API server is an explicit API-only/headless
compatibility surface; Relay adds optional extensions. A Gateway-owned
conversation never changes transport because Gateway auth or reachability
changes. This
path must work against unmodified upstream hermes-agent. Server-side needs go
through upstream PRs or the optional relay plugin, never fork patches.
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
@@ -83,16 +88,21 @@ PR; never resolve those cases by choosing a side automatically.
Version bumps happen only on a release-prep branch targeting `dev`, and
production tags are cut only from `main`.
- **Android:** Jetpack Compose only (no XML), kotlinx.serialization (no Gson),
OkHttp (no Ktor), `wss://` only. Run `./gradlew lint` before pushing Kotlin.
For interactive device-review loops, run focused tests plus the affected
assemble/install task; run the full affected-variant lint once when the
combined candidate is final, or earlier only for lint-sensitive resource,
manifest, dependency, or build-configuration changes. Do not repeat full
variant lint after every small Kotlin iteration.
OkHttp (no Ktor), `wss://` only. While editing, use only the narrow local
compile or focused test needed for feedback, through `scripts/android-lane.ps1`
on Windows. Once an exact commit is already pushed, prefer the `Android
On-Demand` workflow for lint, the focused shards, both-flavor assemblies, and
release smoke; isolated cloud jobs may run concurrently. Do not push solely
to obtain cloud compute without push authorization, and do not duplicate a
preset already running for the same SHA. Full local verification remains
available through `scripts/dev.bat prepush` (or `./scripts/dev.sh prepush`)
when explicitly wanted or when cloud execution is unavailable.
Physical-device checks and APK installation remain separately owned local
evidence.
- **Plugin (Python 3.11+):** aiohttp + asyncio (no threading), type hints
everywhere, structured `logging` (no `print`). **Desktop CLI (Node ≥21):**
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Full
per-language style and the dev loop live in CLAUDE.md → "Code Style".
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Contributor
commands and the development loop live in `CONTRIBUTING.md`.
## Review guidelines
+57 -13
View File
@@ -6,37 +6,81 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
## [Unreleased]
### Changed
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
### Fixed
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
## [Android 1.14.0] - 2026-08-30
### Added
- **Android can preview delegated agent work without leaving the parent chat.** The current-chat activity sheet shows bounded lifecycle, progress, and tool previews for concurrent children, opens vanilla Hermes child history read-only when the Gateway exposes it, and stays explicit when reconnect gaps or older routes leave details unavailable.
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden.
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
- **Android can preview delegated agent work without leaving the parent chat.** The current-chat activity sheet shows bounded lifecycle, progress, and tool previews for concurrent children, opens vanilla Hermes child history read-only when the Gateway exposes it, and stays explicit when reconnect gaps or older routes leave details unavailable. (#447)
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden. An updated optional Hermes-Relay Plugin is required for Git operations.
### Changed
- **Hermes-Relay Dashboard management is organized around operator tasks.** Overview, Devices, Activity, Remote Access, Git, and Settings now have separate native Dashboard surfaces; pairing is QR-first, paired clients use responsive cards, and token-backed media is labeled as a bounded diagnostic instead of a health counter.
- **New Relay pairing uses each Dashboard origin as the network ingress.** Dashboard, CLI, and TUI QR flows advertise the same-origin Relay transport for LAN, Tailscale, and public HTTPS routes. Recommended Tailscale uses dedicated HTTPS `:10443` for local Dashboard `:9119`, avoiding conflicts with an existing Traefik, Caddy, or nginx listener on `:443`; old `:443`/`:9119` routes and direct `:8767` remain explicit migration compatibility while `:8642` stays an optional API fallback.
- **Dashboard pairing now explains and verifies route security before exposing an invite.** Endpoint receipts show Dashboard, Relay, and API URLs with priority and per-surface probe status, distinguish tailnet encryption from application TLS, and block malformed or plaintext public candidates.
- **Connections now explain and recover each Dashboard, Relay, and optional API route independently.** LAN, Tailscale, and public HTTPS can fail over without allowing an unauthenticated or different-origin Relay route to borrow Dashboard credentials. Protected same-origin Relay health challenges are recognized as authentication boundaries instead of outages. An updated optional Hermes-Relay Plugin is required for same-origin Relay ingress. (Related: #399)
- **Android What's New leads with one curated release highlight without interrupting startup.** A timed post-update toast can be swiped or closed, previews additional feature/fix counts when a release has meaningful secondary items, expands into the centered highlight view on request, and keeps the full technical history available. Each release can present one plain-language summary, up to three primary benefits, and up to two quieter improvements, while release checks keep the structured entry, fallback, Play copy, and public release records aligned.
### Fixed
- **Android wake-word detection now loads a compatible native ONNX Runtime.** Packaged sherpa and Java JNI consumers are checked against the shared runtime for every supported ABI before release.
- **Android wake-word detection now loads a compatible native ONNX Runtime.** Packaged sherpa and Java JNI consumers are checked against the shared runtime for every supported ABI before release. (#444)
- **Android Continuous voice waits for barge-in microphone teardown before listening again.** Multi-turn hands-free conversations no longer lose the microphone after a response finishes with barge-in enabled. (#464)
- **Opening Android no longer claims or interrupts a turn already running in Hermes Desktop/TUI.** Passive foreground and session browsing now use read-only Gateway status plus profile-scoped history; live-session resume remains reserved for explicit Android actions and exact Android-owned recovery.
- **Android provisional Threads can be removed without touching server history.** The drawer now offers a local-only removal action, reconciles promoted phone sessions without duplicate rows, and keeps Thread routing isolated to the active saved connection.
- **Android Clarify cards make custom answers explicit and keyboard-friendly.** Choice prompts label their Other answer field, submit trimmed text from the keyboard, and do not restore an authoritatively expired prompt after session navigation.
- **Opening Android no longer claims or interrupts a turn already running in Hermes Desktop/TUI.** Passive foreground and session browsing now use read-only Gateway status plus profile-scoped history; live-session resume remains reserved for explicit Android actions and exact Android-owned recovery. (Related: #365)
- **Android provisional Threads can be removed without touching server history.** The drawer now offers a local-only removal action, reconciles promoted phone sessions without duplicate rows, and keeps Thread routing isolated to the active saved connection. (#461)
- **Android Clarify cards make custom answers explicit and keyboard-friendly.** Choice prompts label their Other answer field, submit trimmed text from the keyboard, and do not restore an authoritatively expired prompt after session navigation. (#446)
- **The visible Android Sphere keeps its smooth procedural motion across startup and chat.** Backgrounded and motion-disabled surfaces remain still without reducing foreground animation to a stepped ambient pulse.
- **Android Voice Focus keeps Stop and immediate spoken steering available across every interaction mode.** Hold-to-talk now interrupts Thinking and Transcribing turns before capturing the replacement direction, remains operable through TalkBack, Switch Access, and keyboard controls, preserves pointer press-and-release behavior across floating controls, and Google Play no longer offers the sideload-only system overlay action.
- **Android Assistant sessions explain when no speech was captured instead of appearing stuck at Ready.** Retry feedback survives the separate system overlay process, recreated session UI requests the current turn state, and locked sessions keep transcript, response, and technical error text private.
- **Android New Chat keeps the current profile and stays fresh across profile switches.** Starting from All Profiles no longer forces the literal default profile, choosing another profile from an empty draft no longer reopens that profile's previous session after route settlement or restart, and leaving a provisional phone Thread cannot route the next turn to its old chat under the new profile.
- **Android self-hosted OIDC keeps sign-in on one trusted Dashboard origin.** Android follows upstream `native_pkce` capability for every interactive provider and falls back to exact-host cookies only when needed. Private and Tailscale routes can discover a provider-declared callback, verify the same installation, and ask before retaining a different authenticated Dashboard/Gateway origin; public origins require HTTPS while reviewed local or overlay HTTP remains compatible. Routes presents that origin separately from optional network paths and no longer exposes internal roles as a VPN. (#399)
- **Android Assistant sessions explain when no speech was captured instead of appearing stuck at Ready.** Retry feedback survives the separate system overlay process, recreated session UI requests the current turn state, and locked sessions keep transcript, response, and technical error text private. (Related: #424)
- **Android New Chat keeps the current profile and stays fresh across profile switches.** Starting from All Profiles no longer forces the literal default profile, choosing another profile from an empty draft no longer reopens that profile's previous session after route settlement or restart, and leaving a provisional phone Thread cannot route the next turn to its old chat under the new profile. (#436)
- **Android Dashboard connections and profile drawers no longer wait on unavailable optional routes.** Dashboard, API fallback, and Relay probes run independently; API/Relay never gate a normal Dashboard connection, Gateway auth/ticket failures are not blindly retried, and authenticated session history remains available without a live Gateway socket. Concurrent route probes are shared and generation-safe, healthy same-priority routes win immediately, superseded session reads cancel their HTTP calls, and optional PR decoration stays outside the session-list critical path.
### Removed
- **Android Chat no longer includes the hidden clean-focus presentation.** The long-press gesture, overlapping instructional pill, reduced composer, and alternate fading transcript were removed so Chat keeps one complete interaction model. Voice Focus remains available.
## [Plugin 1.11.0] - 2026-08-30
### Added
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
- **Relay extensions can use the authenticated Dashboard origin as one network ingress.** Fixed allowlisted HTTP and WebSocket paths proxy to the local Relay while Dashboard admission and Relay session authentication remain separate. (Related: #399)
### Changed
- **Hermes-Relay Dashboard management is organized around operator tasks.** Overview, Devices, Activity, Remote Access, Git, and Settings now have separate native Dashboard surfaces; pairing is QR-first, paired clients use responsive cards, and token-backed media is labeled as a bounded diagnostic instead of a health counter. (#486)
- **Dashboard, CLI, and TUI pairing advertise the same explicit route set.** Recommended Tailscale uses dedicated HTTPS `:10443` for local Dashboard `:9119`, public HTTPS and LAN stay visible fallbacks, and old `:443`/`:9119` plus direct `:8767` remain migration compatibility.
- **Pairing receipts explain transport protection before exposing an invite.** Per-surface probes distinguish application TLS, tailnet encryption, optional API fallback, and authenticated Relay ingress.
### Fixed
- **Public and roaming pairing no longer invent closed direct Relay or Dashboard ports.** Exact Dashboard origins own their same-origin Relay paths, ambiguous or plaintext public candidates fail closed, and inactive optional API routes are omitted.
- **Dense pairing QRs scan reliably.** Dashboard, CLI, and TUI render integer-sized modules with a full quiet zone.
- **Remote-access migration keeps existing listeners safe.** Recommended setup avoids taking over `:443`, explicit legacy cleanup remains available, and default disable actions remove only the listeners they own.
## [0.4.0-beta.6] - 2026-08-30
### Changed
- **Hermes-Relay CLI+UI preserves the complete multi-route pairing topology.** Dashboard, Relay, optional API, priorities, and transport protection remain attached to one saved host across LAN, Tailscale, and public routes. (Related: #399)
### Fixed
- **Desktop rejects Dashboard-ingress Relay dials until it can mint Dashboard WebSocket tickets.** The daemon and host selector choose a compatible direct Relay fallback instead of attempting an unauthenticated same-origin ingress.
- **API-less pairing remains valid.** Dashboard and direct Relay routes can pair without inventing an optional API server, while secure-first ranking keeps plain LAN as the final fallback.
## [Android 1.13.2] - 2026-08-25
### Added
+1 -525
View File
@@ -1,525 +1 @@
# Hermes-Relay — Claude Code Adapter
> Read [AGENTS.md](AGENTS.md) first. It is the provider-neutral canonical agent
> context. Branch, release, staging, and hotfix rules live in `AGENTS.md` and
> [RELEASE.md](RELEASE.md); this file only adds Claude-specific project and tool
> guidance. Then read `docs/spec.md` and `docs/decisions.md`.
## What This Is
A native Android app (Kotlin + Jetpack Compose) paired with an optional Python relay plugin/server (aiohttp) for the Hermes agent platform. Vanilla Hermes chat, Manage, and dashboard voice work against unmodified upstream Hermes. The Relay plugin adds phone control, terminal, remote desktop tooling, extra voice engines, and dashboard Relay management via the official Hermes web dashboard.
**Current state:** Reference latest released version for stable state and current dev branch for working state. The default no-plugin path supports chat, Manage, and voice on vanilla upstream Hermes. Chat auto-prefers the dashboard `/api/ws` gateway transport when Manage auth is ready, then falls back to API-server SSE routes. Vanilla Hermes voice uses dashboard `/api/audio/*` with the Manage session. Relay remains an additive power path for terminal, bridge/device control, notification companion, extra/provider-native voice, remote access, and desktop tooling. Two Android product flavors ship: `googlePlay` (conservative, no unattended Device Control surface) and `sideload` (full-capability).
## Architecture
```
Phone (WS) -> Hermes dashboard (:9119) [vanilla Hermes gateway chat, live thinking]
Phone (HTTP/SSE) -> Hermes API Server (:8642) [vanilla Hermes chat fallback, sessions, runs]
Phone (HTTP) -> Hermes dashboard (:9119) [vanilla Hermes Manage + voice]
Phone (WSS/HTTP) -> Relay plugin/server (:8767) [optional bridge, terminal, relay voice, remote tools]
```
The Vanilla Hermes path must stay upstream-only. API-server bearer auth and dashboard cookie auth are separate. Terminal and bridge require Relay pairing; Vanilla Hermes chat, Manage, and dashboard voice must not.
### Upstream Hermes API Reference
**IMPORTANT:** Always verify endpoints against the actual hermes-agent source (`gateway/platforms/api_server.py`). The upstream repo is the source of truth — not our docs, not our memory, not assumptions from other frontends.
**Vanilla Hermes endpoints (confirmed in hermes-agent source):**
| Endpoint | Purpose | Tool Call Format |
| --------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `POST /v1/chat/completions` | OpenAI-compatible chat (stream=true for SSE) | Inline markdown text (``💻 terminal``) — no separate tool events |
| `POST /v1/runs` | Start an agent run | Returns `run_id` |
| `GET /v1/runs/{run_id}/events` | SSE stream of run lifecycle events | **Structured events**: `tool.started`, `tool.completed`, `message.delta`, `reasoning.available`, `run.completed`, `run.failed` |
| `POST /v1/responses` | OpenAI Responses API format | Structured `function_call` objects (non-streaming only) |
| `GET /v1/capabilities` | Machine-readable feature + endpoint discovery | Use before assuming optional surfaces exist |
| `GET /v1/models` | List available models | — |
| `GET /v1/skills` | Read-only skill list for the API-server agent | `{"object":"list","data":[...]}` |
| `GET /v1/toolsets` | Read-only API-server toolset inventory | `{"object":"list","platform":"api_server","data":[...]}` |
| `GET/POST/PATCH/DELETE /api/sessions/*` | Native session CRUD, messages, fork, sync chat, SSE chat | Upstream merged via NousResearch/hermes-agent PR #33134 |
| `GET /health` | Health check | — |
| `GET/POST/PATCH/DELETE /api/jobs/*` | Cron job management (api_server surface) | — |
**Compatibility endpoints (not all native upstream API-server routes):**
Upstream main now contains the focused session-control API (`#33134`) and read-only skills/toolsets (`#33016`). The original broad PR [#8556](https://github.com/NousResearch/hermes-agent/pull/8556) was closed as superseded. Keep these distinctions straight:
1. **Native upstream** — `/api/sessions`, `/api/sessions/{id}/messages`, `/api/sessions/{id}/chat`, `/api/sessions/{id}/chat/stream`, `/v1/capabilities`, `/v1/skills`, and `/v1/toolsets` exist in current `gateway/platforms/api_server.py`.
2. **Bootstrap compatibility** (`plugin/hermes_relay_bootstrap/`) — monkey-patches aiohttp on startup via `.pth` file, injecting only compatibility-only surfaces (session search, memory, legacy skill detail/toggle, config, available-models, slash middleware). Sessions CRUD/messages/fork and the legacy skills list are **retired** — native upstream owns them (#33134/#33016) and the bootstrap carries no fallback for old builds. Native routes still win per method/path for the remaining set. The repo-root `hermes_relay_bootstrap/` package is a legacy import shim.
3. **Legacy fork branches** — useful as lineage only. Do not cite `feat/session-api` / `#8556` as the current upstream contract.
| Endpoint | Purpose | Provided by |
| -------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
| `GET /api/sessions` (CRUD) | Session list/create/rename/delete/fork | Native upstream (#33134); bootstrap injection retired |
| `GET /api/sessions/{id}/messages` | Conversation history | Native upstream (#33134); bootstrap injection retired |
| `POST /api/sessions/{id}/chat` | Synchronous session chat | Native upstream (#33134) |
| `POST /api/sessions/{id}/chat/stream` | Session-based SSE chat | Native upstream (#33134); bootstrap does NOT inject |
| `GET /v1/skills`, `GET /v1/toolsets` | Read-only skill/toolset discovery | Native upstream (#33016) |
| `GET /api/sessions/search` | Full-text message search | Bootstrap/fork legacy; not in current upstream main |
| `GET /api/config`, `PATCH /api/config` | Personalities + model config | Bootstrap/fork legacy or dashboard web-server surface; not current API-server upstream |
| `GET /api/skills/{name}` | Legacy skill detail | Bootstrap compat; list (`GET /api/skills`) retired — use native `/v1/skills` |
| `PUT /api/skills/toggle` | Enable/disable installed skill | `hermes_cli/web_server.py` dashboard surface; bootstrap stub returns 501 |
| `GET/POST/PATCH/DELETE /api/memory` | Memory CRUD | Bootstrap/fork legacy; not current API-server upstream |
| `GET /api/available-models` | Provider model list | Bootstrap/fork legacy; not current API-server upstream |
The Android client probes per-endpoint capability via `HermesApiClient.probeCapabilities()` (returns `ServerCapabilities`). When `streamingEndpoint = "auto"`, `ConnectionViewModel.resolveStreamingEndpoint()` picks `sessions`, `completions`, or `runs` based on the capability snapshot.
**Dashboard web server (separate surface — standard Manage / Desktop remote gateway):**
hermes-agent ships a second web server at `hermes_cli/web_server.py` that hosts the React admin dashboard at `hermes_cli/web_dist/`. It has its **own** `/api/*` routes that **do not live on `api_server.py`** — notably: `GET/PUT /api/config` (full tree), `GET /api/config/schema`, `GET /api/config/defaults`, `GET/PUT /api/config/raw` (YAML text), `GET/PUT/DELETE /api/env` + `POST /api/env/reveal`, `PUT /api/skills/toggle`, `/api/cron/jobs/*` (different shape from `/api/jobs/*`), `/api/providers/oauth/*`, `/api/dashboard/themes`, `/api/dashboard/plugins`, `/api/model/info` + `/api/model/options` + `POST /api/model/set`, `/api/profiles/*` (CRUD, `POST /api/profiles/active`, per-profile soul/description/model), `/api/mcp/*`, `/api/logs`, `/api/analytics/usage`, and `**POST /api/audio/transcribe` + `POST /api/audio/speak`** (base64 data-url contract, built for hermes-desktop voice). The API server has **no audio routes** — its `/v1/capabilities` advertises `audio_api: false`; PR #8199 (`/v1/audio/*`) is the canonical future surface but is unmerged. Android's **Vanilla Hermes (no-plugin) voice** therefore rides this dashboard surface via `StandardHermesVoiceClient` with the per-connection dashboard cookie session (Manage sign-in unlocks voice); `AutoVoiceAudioClient` prefers Relay when paired and falls back to standard.
Current upstream supports two auth modes on this surface. Loopback dashboards still use the injected `window.__HERMES_SESSION_TOKEN__` path. Remote/non-loopback dashboards use the Desktop-style dashboard auth gate: `/api/status` advertises `auth_required` and providers, `/auth/password-login` handles password providers, `/auth/login?provider=...` handles Nous/OIDC redirects, `/api/auth/me` returns the verified session, and `/api/auth/ws-ticket` mints a short-lived ticket for `/api/ws` / `/api/pty`. This dashboard session is **not** an `API_SERVER_KEY`. Android uses it for Manage, Vanilla Hermes voice, and the gateway chat transport. `/api/ws` is backed by `tui_gateway/server.py` (what hermes-desktop + the Ink TUI speak) and is the only upstream surface with **live** `reasoning.delta`/`thinking.delta` streaming; the api_server SSE paths remain the SSE fallback. Relay-only capabilities remain behind Relay pairing. **Do not proxy dashboard auth or dashboard admin APIs over the relay.**
**Tool call rendering paths:**
1. **Runs API** — Emits `tool.started`/`tool.completed` as real SSE events → `ToolProgressCard` in real-time.
2. **Sessions API** — Native upstream emits structured SSE (`run.started`, `message.started`, `assistant.delta`, `tool.progress`, `tool.started/completed/failed`, `assistant.completed`, `run.completed`, `done`). `run.completed.messages` can reconcile authoritative per-turn transcript.
3. **Annotation parser** — Fallback for servers emitting inline markdown annotations (``💻 terminal``).
## Key Instructions
- **Vanilla Hermes path = upstream-only.** The default (no-plugin) connection path — gateway/API chat, Manage, and Vanilla Hermes voice via the dashboard surface — must work against **unmodified upstream hermes-agent**: no fork patches, no bespoke server config as a dependency. The app ships on Google Play to users whose servers we don't control. Features that need server-side changes go through upstream PRs (with graceful degradation until merged) or live behind the opt-in relay plugin.
- **Always verify upstream before assuming an endpoint exists.** Check `gateway/platforms/api_server.py` in hermes-agent. If an endpoint isn't there, document whether bootstrap injects it or it requires the fork.
- If we use a non-standard endpoint, ensure `probeCapabilities()` covers it and the auto-resolver degrades gracefully.
- **Bootstrap maintenance:** Retire `plugin/hermes_relay_bootstrap/` per surface. Done: sessions CRUD/messages/fork and the legacy skills list are retired from the bootstrap (native upstream #33134/#33016, no old-build fallback kept). Remaining: config, memory, legacy skill detail/toggle, available-models, session search, and slash middleware still need explicit replacement decisions before full removal.
## Repository Layout
```
hermes-android/
├── app/src/main/kotlin/com/hermesandroid/relay/
│ ├── ui/ # Screens, components, theme
│ ├── network/ # ConnectionManager, ChannelMultiplexer, handlers
│ ├── auth/ # AuthManager (pairing + tokens)
│ ├── viewmodel/ # ChatViewModel, ConnectionViewModel
│ ├── data/ # ChatMessage, ToolCall models, FeatureFlags
│ ├── audio/ # VoiceRecorder, VoicePlayer, VoiceSfxPlayer
│ ├── voice/ # VoiceViewModel, VoiceBridgeIntentHandler
│ ├── accessibility/ # HermesAccessibilityService, ScreenReader, ActionExecutor
│ ├── bridge/ # BridgeSafetyManager, BridgeForegroundService, BridgeStatusOverlay
│ └── notifications/ # HermesNotificationCompanion
├── relay-core/ ← [EXPERIMENTAL] Quest/XR shared core lib (com.axiomlabs.hermesrelay.core) — pairing, transport, terminal, voice, wire
├── relay-ui/ ← [EXPERIMENTAL] Quest/XR shared Compose UI lib — sphere, terminal WebView, QR scanner
├── quest/ ← [EXPERIMENTAL] Meta Spatial SDK Quest/XR app (gradle includeBuild; in development, not shipped)
├── ui-preview/ ← Desktop Compose Hot Reload harness for PC UI iteration (NOT shipped; shares MorphingSphereCore)
├── desktop/ ← Node thin-client CLI (`@hermes-relay/cli`)
│ ├── bin/hermes-relay.js # #!/usr/bin/env node shim → dist/cli.js
│ ├── src/
│ │ ├── cli.ts # argv parser + subcommand dispatcher (bare → shell)
│ │ ├── commands/ # chat, shell, pair, status, tools, devices
│ │ ├── banner.ts # contextual connect line (LAN / Tailscale / Plain / Secure)
│ │ ├── renderer.ts # GatewayEvent → plain-line stdout formatter (chat only)
│ │ ├── endpoint.ts # ADR 24 EndpointCandidate + role helpers
│ │ ├── pairingQr.ts # v3 QR decode + priority-raced reachability probe
│ │ ├── pairing.ts # readline 6-char prompt + payload validator
│ │ ├── credentials.ts # token → pair-qr → code → stored → prompt precedence
│ │ ├── certPin.ts # TOFU SPKI sha256 extract / pinKey / compare
│ │ ├── tools/ # desktop.command router + fs/terminal/search handlers + consent
│ │ ├── transport/ # RelayTransport (reconnect state machine + TLS probe TOFU)
│ │ └── lib/ # gracefulExit, rpc, circularBuffer (vendored)
│ └── scripts/ # install.sh + install.ps1 curl/iwr one-liners
├── website/ ← Astro product/marketing site (static Coolify/Nixpacks deployment)
├── plugin/ ← Hermes agent plugin
│ ├── android_tool.py # 18 android_* tool handlers
│ ├── pair.py # QR pairing implementation
│ ├── relay/ # Canonical WSS relay (server.py, auth.py, channels/, media.py, voice.py)
│ ├── tools/ # android_navigate.py, android_notifications.py
│ └── dashboard/ # hermes-agent dashboard plugin — manifest, React UI, FastAPI proxy
├── relay_server/ ← Thin compat shim → plugin.relay (legacy entrypoint)
├── hermes_relay_bootstrap/ ← Legacy import shim for older startup hooks
├── skills/devops/hermes-relay-pair/ ← /hermes-relay-pair slash command
├── scripts/ ← dev.bat, bridge-smoke.sh, bump-version.sh
└── docs/ ← spec, decisions, security, relay-server, mcp-tooling
```
## Project Conventions
### File Structure
- **Root-level:** README.md, CLAUDE.md, AGENTS.md, DEVLOG.md, TODO.md, .gitignore
- **docs/** — spec, decisions, security, and any other long-form documentation
- **DEVLOG.md** — update at end of each work session with what was done + verification (the factual record of *what happened*). It churns; do NOT park forward work here.
- **TODO.md** — the single home for follow-ups / deferred work / known gaps ("what's next"). Record them here — never buried in DEVLOG or scattered through code/doc comments where they get lost.
- **CLAUDE.md hygiene:** Key Files entries must stay one line — implementation detail belongs in the file or `docs/`. Run `/revise-claude-md` after feature-heavy sessions to trim drift.
### Public-repo writing hygiene
This is a **public, distributed repo** — every committed file (CHANGELOG, DEVLOG, README, docs, release notes) is public-facing. Write accordingly:
- **No personal names** in prose — attribute impersonally ("a user reported", "observed"). Author identity lives in git history + the signing cert, not the changelog.
- **No private infrastructure** — real server hostnames/IPs, internal deployment names, `~/SYSTEM.md` contents. (Generic example IPs like `192.168.1.100` in setup docs are fine.)
- **No AI/assistant process self-narration** — no "I should have…", no course-correction confessionals. State the technical conclusion, not the path to it.
- **No internal jargon / fork-branch plumbing** in user-facing notes — keep *what changed*, drop *where we staged it*.
- **CHANGELOG** uses Keep-a-Changelog grouping (Added / Changed / Fixed). Detail may accumulate during iteration, but at **release-prep the version block is condensed to crisp public bullets** (1–2 lines each) — deep "how we debugged it" stays in commits/DEVLOG. See [RELEASE.md](RELEASE.md) §2 "Scrub for public distribution".
- **DEVLOG.md** is a committed, factual engineering log — what changed, why, and verification — depersonalized and third-person, not a diary.
### Code Style — Android (Kotlin)
- **Jetpack Compose** — no XML layouts. Material 3 / Material You.
- **kotlinx.serialization** — not Gson. Type-safe, faster.
- **OkHttp** for WebSocket + SSE — `okhttp` for WSS relay, `okhttp-sse` for API streaming
- **Single-activity** — Compose Navigation for all routing
- **Namespace (Kotlin source tree):** `com.hermesandroid.relay` — stable, drives on-disk layout + class FQCNs
- **applicationId:** `com.axiomlabs.hermesrelay` (googlePlay), `com.axiomlabs.hermesrelay.sideload` (sideload)
- **Min SDK 26, Target SDK 35, Compile SDK 37** / **Kotlin 2.0+**, JVM toolchain 17
### Code Style — Desktop CLI (Node/TypeScript)
- **Node ≥21** — uses built-in global `WebSocket` (no `ws`/`undici` dep). Strict TS, ES modules, `NodeNext` resolution.
- **Zero runtime deps** — `@types/node` + `tsx`/`rimraf`/`typescript` are devDeps only. Ship compiled `dist/`, not tsx.
- **One binary, subcommands** — idiomatic for Node CLIs (codex, continue, vite pattern). Bare invocation is `chat`.
- **Vendor-for-now** — transport/gateway/types are copied verbatim from `hermes-agent-tui-smoke/ui-tui/src/` with a header note. Extract to a shared package when the TUI and CLI stabilize.
- **Dev loop:** `npx tsx src/cli.ts <args>` (no rebuild). `npm run build` + `npm link` before pushing to verify the bin shim. Never ship tsx in the published tarball — pre-build with `tsc` so Windows `npm install -g` can cmd-shim the JS directly.
### Code Style — Server (Python)
- **aiohttp** — async, matches existing Hermes relay patterns
- **Type hints everywhere** — Python 3.11+ syntax
- **asyncio** — no threading; **structured logging** — use `logging`, not print()
### Git
- **Conventional Commits:** `feat`, `fix`, `docs`, `refactor`, `test`, `chore`
- **Branch/release policy:** follow the branch-contract table in `AGENTS.md` and
the executable release and hotfix procedures in `RELEASE.md`. Do not maintain
a Claude-specific parallel policy here.
### Testing
- **Android:** JUnit + Compose testing for UI, MockK for mocks
- **Gateway/session/reconnect work:** follow the on-demand scenario,
current-upstream conformance, Android instrumentation, and physical-proof
routing in `docs/gateway-contract-testing.md`; do not infer device behavior
from fixture or source checks.
- **Python:** `python -m unittest plugin.tests.test_<name>` — avoid bare `pytest` (conftest imports `responses` which may not be installed in the venv)
- **CI and release gates:** follow the repository-wide requirements in
`AGENTS.md` and `RELEASE.md`; Claude-specific guidance does not redefine them.
## Key Files
| File | Why |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `docs/spec.md` | Full specification — protocol, UI layouts, phases, dependencies |
| `docs/decisions.md` | Architecture decisions — framework choice, channel design, auth model |
| `docs/gateway-contract-testing.md` | On-demand reusable Gateway scenarios, upstream conformance, Android instrumentation, and ADB certification |
| `AGENTS.md` | Universal agent entry point — points here + the non-negotiables (standard-path, commits, writing hygiene) |
| `docs/mcp-tooling.md` | MCP server setup — android-tools-mcp + mobile-mcp; `android_*` tool usage patterns |
| **App — Core** | |
| `ui/RelayApp.kt` | Main scaffold (Scaffold + Compose nav); Chat is home — no mode strip, Manage/Bridge reached via Settings; `bottomBar` is a status pill, not a NavigationBar |
| `viewmodel/ChatViewModel.kt` | Chat orchestration — send, stream, cancel, slash commands |
| `viewmodel/ConnectionViewModel.kt` | Dual connection model (API + relay); `resolveStreamingEndpoint()`; derived `relayUiState` flow + `markPaired` hook stamp the active Connection |
| `viewmodel/RelayUiState.kt` | Shared sealed state for the relay row — 5 cases + `asBadgeState()` / `statusText()` extensions; 5s grace window before Stale |
| `network/HermesApiClient.kt` | Direct HTTP/SSE — `sendRunStream()`, `sendChatStream()`, `probeCapabilities()` |
| `network/GatewayChatClient.kt` | Gateway chat transport — JSON-RPC over dashboard `/api/ws` (tui_gateway); live `reasoning.delta`; fresh ws-ticket per connect; per-turn SSE fallback via `onPreflightFailure`; `prewarm()` (connect+resume off the send path); `setKeepAliveInBackground()` suppresses the 120s idle-close |
| `network/GatewayKeepAliveService.kt` | Opt-in `specialUse` foreground service (BOTH flavors; declared in main manifest; Play needs a Console FGS declaration) holding the process up so the gateway socket survives background/Doze; driven by ConnectionViewModel from the `KEY_GATEWAY_KEEP_ALIVE` toggle; stops on task-removal |
| `data/GatewayKeepAlivePrefs.kt` | Shared `KEY_GATEWAY_KEEP_ALIVE` pref key + `Context.setGatewayKeepAlive()` — used by ConnectionViewModel (StateFlow/setter) and the FGS Stop action |
| `network/GatewayEventMapper.kt` | Pure-JVM gateway event→callback mapping for one turn; unknown event types silently ignored; tui_gateway usage-key translation |
| `network/GatewayModels.kt` | `GatewayAvailability`, `ActiveTurnHandle`, `GatewayTurnCallbacks` (all members REQUIRED — forces dispatchOn main-thread wrap), `GatewayAsk`, `GatewaySubagentEvent`, `resolveStreamingEndpointPreference()` |
| `ui/components/ChatInputBar.kt` | Redesigned input bar — pill field, one trailing slot morphing Send/Voice/Stop/Steer/Queue, no slash button (long-press + opens palette) |
| `ui/components/SubagentLane.kt` | Per-taskIndex subagent progress lane — guide rail, compact tool rows, auto-collapse |
| `notifications/TurnCompleteNotifier.kt` | Turn-complete local notification when backgrounded — channel `chat_turn_complete`, cancel on resume, settings-gated |
| `network/ConnectionManager.kt` | WSS to relay with auto-reconnect; rebuilds OkHttpClient with fresh CertPinner on connect |
| `network/ChannelMultiplexer.kt` | Envelope routing by channel; `sendNotification()` for notification outbound |
| `network/handlers/ChatHandler.kt` | Chat message state, streaming events, tool annotation parser |
| `network/models/SessionModels.kt` | Session, message, SSE event data models |
| `data/FeatureFlags.kt` | Feature gating — DEV_MODE + DataStore overrides; `BuildFlavor` (googlePlay/sideload Tier flags) |
| **App — Auth** | |
| `auth/AuthManager.kt` | Wires SessionTokenStore + CertPinStore; parses auth.ok; `applyServerIssuedCodeAndReset()` |
| `auth/SessionTokenStore.kt` | Keystore (StrongBox) + EncryptedSharedPrefs fallback; lossless migration on upgrade |
| `auth/CertPinStore.kt` | TOFU cert pinning — SHA-256 SPKI per host:port in DataStore |
| `auth/PairedSession.kt` | PairedSession state + PairedDeviceInfo wire model |
| `data/Endpoint.kt` | `EndpointCandidate` / `ApiEndpoint` / `RelayEndpoint` — multi-endpoint pairing (ADR 24); `displayLabel()` for LAN/Tailscale/Public/Custom chips |
| `network/RelayHttpClient.kt` | OkHttp for /media, /sessions (list/revoke/extend), /health |
| **App — Bridge** | |
| `network/handlers/BridgeCommandHandler.kt` | Routes `bridge.command` → ActionExecutor; full path inventory + safety-rail integration |
| `viewmodel/BridgeViewModel.kt` | BridgeScreen VM — masterToggle, bridgeStatus, permissionStatus, activityLog |
| `bridge/BridgeSafetyManager.kt` | Connection-scoped capabilities + timed screen expiry + blocklist + destructive confirmation; unknown, denied, and expired commands fail closed |
| `bridge/BridgeCapabilities.kt` / `data/BridgeCapabilityPolicyRepository.kt` | Closed method/path registry + no-backup-bound per-Connection Always/Never/Timed policy; global safety vocabulary and timer duration remain in `BridgeSafetyPreferences.kt` |
| `ui/screens/BridgeScreen.kt` | Bridge cockpit — master → Agent access posture/setup → single Unattended Access control → capability-scoped Android readiness (expandable full matrix) → Advanced safety/full editor → activity log |
| `ui/components/BridgeAccessCards.kt` | Native access cockpit + first-use preset and screen-lease sheets (renewable idle limits or warned Until-off dedicated-device mode); preserves full permission/safety drilldowns while keeping selected policy/readiness above the fold |
| `ui/components/UnattendedAccessRow.kt` | Unattended toggle card (sideload); `enabled=masterEnabled`; inline `KeyguardDetectedAlert` |
| `ui/components/UnattendedGlobalBanner.kt` | 28dp amber strip at scaffold top when master+unattended on (sideload); tap → Bridge tab |
| `bridge/BridgeStatusOverlay.kt` | WindowManager overlay; `ConfirmationOverlayHost`; requires `SavedStateRegistryOwner` init order (CREATED→restore→RESUMED) |
| `accessibility/HermesAccessibilityService.kt` | AccessibilityService subclass; `@Volatile instance` singleton for BridgeCommandHandler |
| `accessibility/ScreenReader.kt` | UI tree → ScreenContent; `findNodeBoundsByText()`, `findFocusedInput()` |
| `accessibility/ActionExecutor.kt` | Gesture/text dispatch via GestureDescription + ACTION_SET_TEXT; pressKey maps vocab only |
| **App — Voice** | |
| `voice/VoiceViewModel.kt` | Voice turn state machine; TTS queue; `ignoreAssistantId`; `errorEvents: SharedFlow` |
| `audio/VoiceRecorder.kt` | MediaRecorder wrapper; perceptual amplitude curve; `.m4a` at 16kHz/64kbps |
| `audio/VoicePlayer.kt` | Media3 ExoPlayer (gapless TTS queue) + Visualizer; amplitude StateFlow; `awaitCompletion()` via coroutine; `audioSessionId` is a thread-safe `@Volatile` cache |
| `network/RelayVoiceClient.kt` | OkHttp for `/voice/transcribe`, `/synthesize`, `/config` |
| `voice/VoiceBridgeIntentHandler.kt` | Interface routing voice utterances to bridge; impls per flavor via factory |
| `voice/VoiceIntentClassifier.kt` | Regex phone-control classifier (sideload only); false-negatives preferred over false-positives |
| `ui/components/VoiceModeOverlay.kt` | Full-screen voice UI — MorphingSphere + VoiceWaveform + mic button |
| `ui/components/MorphingSphere.kt` | Compose renderer for the agent sphere — delegates math to `MorphingSphereCore` |
| `ui/components/MorphingSphereCore.kt` | Platform-agnostic sphere algorithm (`kotlin.math` only) — single source of truth; mirrored byte-for-byte in `preview/web/sphere.js` |
| `preview/web/` | Zero-dep browser harness — live `index.html` preview + `parity-check.mjs`; paired with `MorphingSphereCoreParityTest` (JVM) for struct/full checksum diffing |
| `user-docs/.vitepress/theme/components/SphereMark.vue` | Docs-site sphere embed — imports `preview/web/sphere.js` directly; autonomous fbm drift + pointer-proximity gaze/state blend; `<ClientOnly>` + `IntersectionObserver` + `prefers-reduced-motion` aware |
| **App — Media + Notifications** | |
| `util/MediaCacheWriter.kt` | `cacheDir/hermes-media/` LRU writer; returns FileProvider URIs |
| `util/MediaSaver.kt` | Save/share/open for chat media — MediaStore scoped-storage save (Pictures/Download `Hermes-Relay`, no perms on API 29+; pre-Q → share sheet); FileProvider share staging; remote-byte fetch; magic-byte image-MIME sniff for correct extensions |
| `ui/components/ChatImageViewer.kt` | Full-screen image viewer — pinch-zoom/pan (`detectTransformGestures`), double-tap 1×/2.5×, Share/Save/Close; `ChatImageViewerSource` decouples Coil-model/bitmap display from a suspend `bytesProvider` so Save keeps original bytes |
| `ui/components/InboundAttachmentCard.kt` | Discord-style attachment card for images/video/audio/pdf/text/generic; image tap → ChatImageViewer, file card long-press → Open/Share/Save menu |
| `ui/components/ChatImageContent.kt` | Parses `![alt](src)` out of assistant content; remote http(s) → Coil (tap → ChatImageViewer), server-local/failed → inline "can't render" notice with the path |
| `data/HermesCard.kt` | `CARD:{json}` envelope (ADR 26) — type/accent/fields/actions; kotlinx.serialization |
| `ui/components/HermesCardBubble.kt` | Rich-card renderer — accent stripe + FlowRow actions + dispatch stamp collapse |
| `viewmodel/CardDispatchSyncBuilder.kt` | Twin of VoiceIntentSyncBuilder — synthesizes card dispatches as `hermes_card_action` OpenAI pairs for session memory |
| `notifications/HermesNotificationCompanion.kt` | NotificationListenerService; cold-start buffer (50); forwards via ChannelMultiplexer |
| `util/RelayErrorClassifier.kt` | `classifyError(Throwable, context) → HumanError`; used by Voice/Chat/Connection |
| `util/TurnLatencyTracer.kt` | One `TurnLatency` INFO line per chat turn — `warm/cold` + `connect/session/submit/ttfe/ttft/done@…ms`; gateway + 3 SSE paths use it for desktop-comparable latency diagnosis; durations only |
| **Relay — Server** | |
| `plugin/relay/server.py` | Canonical relay — WSS + HTTP routes; bridge, media, voice, session, pairing handlers. `handle_pairing_mint` mirrors `pair.py:762` — top-level = API server, `relay.{url,code}` nested |
| `plugin/relay/auth.py` | PairingManager, SessionManager, RateLimiter; `math.inf` for never-expire |
| `plugin/relay/channels/bridge.py` | Bridge handler — `handle_command()` mints request_id, awaits response, 30s timeout |
| `plugin/relay/channels/notifications.py` | Bounded deque (100) of notification metadata; in-memory only |
| `plugin/relay/media.py` | MediaRegistry — LRU token store; `strict_sandbox` off by default for `/media/by-path` |
| `plugin/relay/voice.py` | Voice endpoints — transcribe, synthesize, voice_config; lazy tool imports |
| `plugin/relay/qr_sign.py` | HMAC-SHA256 QR signing; secret at `~/.hermes/hermes-relay-qr-secret`; canonical form preserves `endpoints` array order + role strings verbatim (ADR 24) |
| `plugin/relay/tailscale.py` | First-class Tailscale helper (ADR 25) — `status()` / `enable(port)` / `disable(port)` / `canonical_upstream_present()`; safe-absent via shell-out to `tailscale` CLI |
| `plugin/relay/_env_bootstrap.py` | Loads `~/.hermes/.env` before relay imports; called from both entry points |
| **Plugin — Tools + Installer** | |
| `plugin/tools/android_tool.py` | 18 `android_*` tool handlers (14 baseline + send_sms, call, search_contacts, return_to_hermes); `android_screenshot` first consumer of `register_media()` |
| `plugin/tools/android_navigate.py` | Vision-driven navigation loop; up to 20 iterations; `llm_gap` error until vision client wired |
| `plugin/pair.py` | QR payload builder + CLI; `build_payload(sign=True)`; `--register-code` fallback |
| `plugin/doctor.py` | `hermes relay doctor`; checks standard upstream API/dashboard reachability, Relay loopback state, plugin layout, and compat hook state |
| `plugin/compat.py` | `hermes relay compat status/install/remove`; owns the optional `hermes_relay_bootstrap.pth` lifecycle |
| `plugin/hermes_relay_bootstrap/` | Plugin-owned runtime compatibility patch — compat-only surfaces (session search, memory, skill detail/toggle, config, available-models, slash middleware); sessions + skills-list injection retired (#33134/#33016) |
| `install.sh` | Canonical installer — 6 steps; idempotent; drops `hermes-relay-update` shim |
| `uninstall.sh` | Canonical uninstaller; reverses install.sh; never touches `.env` or `state.db` |
| `hermes_relay_bootstrap/` | Legacy import shim for old `.pth` files and editable installs |
| **Plugin — Dashboard** | |
| `plugin/dashboard/manifest.json` | Declares tab, entry bundle, and FastAPI module for hermes-agent discovery |
| `plugin/dashboard/plugin_api.py` | FastAPI router proxying 5 routes to relay over loopback; `/pairing` body = API-server overrides (host/port/tls/api_key), relay URL auto-derived |
| `plugin/dashboard/src/index.jsx` | React root registering `hermes-relay` plugin with 4-tab shell |
| `plugin/dashboard/dist/index.js` | Committed IIFE bundle loaded verbatim by dashboard |
| **Desktop CLI** | |
| `desktop/package.json` | `@hermes-relay/cli` package manifest — Node ≥21, one `hermes-relay` bin, pre-built dist |
| `desktop/bin/hermes-relay.js` | Tiny shim: `import('../dist/cli.js').then(m => m.main())` + error surfacing |
| `desktop/src/chatAttach.ts` | captureClipboardImage / captureScreenshot / readImageFile; ships base64 to server via `image.attach.bytes` RPC before next prompt.submit |
| `desktop/src/cli.ts` | argv parser + subcommand dispatcher — bare → `shell` (PTY), positional-only → `chat`; command-scoped `--help` falls through to each command |
| `desktop/src/lib/theme.ts` | Shared ANSI palette + `colorEnabled()` + `Theme` (semantic helpers, `statusDot`) — single visual language; `--no-color`/`NO_COLOR`/TTY aware |
| `desktop/src/lib/table.ts` | Zero-dep column-aligned table renderer (ANSI-width aware, last column flexes to terminal width) — used by devices/sessions/audit |
| `desktop/src/lib/spinner.ts` | Stderr braille spinner for slow ops (pair probe, gateway connect); no-op when piped/quiet/json |
| `desktop/src/lib/usage.ts` | `UsageSpec` + `renderUsage`/`printUsage`/`unknownSubcommand` — per-subcommand `--help` + self-documenting sub-verb fallback |
| `desktop/src/lib/hints.ts` | `suggestedFix(err, ctx)` → next-step command (re-pair on auth fail, etc.); `formatError` renders error + hint |
| `desktop/src/lib/logo.ts` | Slim box-drawing "Hermes Relay" wordmark; shown atop `--help`, first-run welcome, REPL header, and `hermes-relay logo`; theme/no-color aware |
| `desktop/src/lib/auditLog.ts` | Local desktop-tool audit JSONL (`~/.hermes/desktop-audit.jsonl`); router appends per dispatch; backs `audit` command (relay's ring is loopback-only) |
| `desktop/src/lib/daemonStatus.ts` | Daemon heartbeat file (`~/.hermes/daemon-status.json`) + `isPidAlive` liveness; backs `daemon --status` |
| `desktop/src/commands/audit.ts` | `hermes-relay audit` — tails the local audit log into a table (WHEN/TOOL/STATUS/DETAIL); `--limit`, `--json` |
| `desktop/src/commands/relay.ts` | `hermes-relay relay info/security/context/queue` — relay-server management surface; info/security/queue loopback-only, context works remote with bearer; `queue` lists/cancels the agent→phone outbound buffer (`--clear` / `--cancel <id>`) |
| `desktop/src/commands/chat.ts` | REPL + one-shot + piped-stdin; `runOneTurn` returns `{promise, cancel}` for safe SIGINT; auto-wires `DesktopToolRouter` when consented |
| `desktop/src/commands/shell.ts` | Pipes the `terminal` relay channel to raw-mode stdin/stdout; post-attach `exec hermes` 350ms after tmux settles; `Ctrl+A .` detach / `Ctrl+A k` kill / `Ctrl+A Ctrl+A` literal |
| `desktop/src/commands/pair.ts` | Either 6-char code + `--remote`, or full v3 QR via `--pair-qr` — probes + picks endpoint, records role; `--grant-tools` (TTY prompt) / `--auto-grant-tools` (silent) stamp `toolsConsented` so `daemon` works without a `shell` round-trip |
| `desktop/src/commands/tools.ts` | `tools.list` RPC → enabled/available toolsets; `--verbose` lists individual tools |
| `desktop/src/commands/status.ts` | Local read of `~/.hermes/remote-sessions.json`; renders `grants:` + `expires:` + `route:`; `--json` redacts tokens, `--reveal-tokens` opts in |
| `desktop/src/commands/devices.ts` | Server-side session management — `GET/DELETE/PATCH /sessions` via `fetch` over http(s)://host:port; `list` / `revoke <prefix>` / `extend <prefix> --ttl <s>` |
| `desktop/src/banner.ts` | `buildConnectBanner({url, meta, endpointRole})` → "Connected via LAN (plain) — server 0.6.0"; `humanExpiry()` for TTL formatting |
| `desktop/src/endpoint.ts` | `EndpointCandidate` / `EndpointRole` types + `displayLabel()` — mirrors Android `data/Endpoint.kt` |
| `desktop/src/pairingQr.ts` | `decodePairingPayload` (JSON or base64), `payloadToCandidates` (v3 verbatim / v1–v2 synthesized), `probeCandidatesByPriority` (`Promise.any` within tier, `AbortSignal.any`, 4s timeout, 60s cache) |
| `desktop/src/certPin.ts` | `extractSpkiSha256(der)` via `crypto.X509Certificate` + `publicKey.export({type:'spki'})`; `pinKey(url)`, `comparePins()`, `isSecureUrl()` |
| `desktop/src/tools/router.ts` | `DesktopToolRouter.attach(relay)` — `onChannel('desktop')` dispatch under 30s `AbortController`; heartbeat enriched with host/platform/version/uptime_ms + sticky `last_error` for `desktop_health` |
| `desktop/src/tools/handlerSet.ts` | Single source of truth for the desktop tool map — `DESKTOP_HANDLERS` + `DESKTOP_ADVERTISED_TOOLS`; consumed by `chat.ts` / `shell.ts` / `daemon.ts` so adding a tool is a one-file change |
| `desktop/src/tools/consent.ts` | `ensureToolsConsent(url)` — stored per-URL in `toolsConsented`; TTY prompt; non-TTY fails closed |
| `desktop/src/tools/handlers/fs.ts` | `readFileHandler` / `writeFileHandler` / `patchHandler` — strict unified-diff applier, no fuzz |
| `desktop/src/tools/handlers/terminal.ts` | `bash -lc` / `cmd /c`, SIGKILL on timeout or abort, returns `{stdout, stderr, exit_code, duration_ms}` |
| `desktop/src/tools/handlers/powershell.ts` | Spawns `pwsh`/`powershell` directly with `-Command -`, script piped via stdin — no cmd.exe quote-mangling; auto-picks pwsh &gt; powershell |
| `desktop/src/tools/handlers/process.ts` | `spawn_detached` (unref'd, returns pid+log_path), `list_processes` (tasklist /FO CSV — no /V to dodge window-title latency), `kill_process`, `find_pid_by_port` (netstat/lsof/ss) |
| `desktop/src/tools/handlers/jobs.ts` | Job API — `~/.hermes/desktop-jobs/<id>/{stdout.log, stderr.log, meta.json}` is source of truth across daemon restarts; `taskkill /T` on Windows so build trees die fully |
| `desktop/src/tools/handlers/transfer.ts` | `copy_directory` via `fs.cp`, `zip`/`unzip` via tar &gt; zip &gt; PowerShell probe, `checksum` streamed (sha256/sha1/md5) |
| `desktop/src/tools/handlers/search.ts` | ripgrep with pure-Node fallback, skips `.git`/`node_modules`/`dist`/`.next`/`.cache` |
| `desktop/src/renderer.ts` | Streams `message.delta` → stdout, tool events → decorated lines; NO_COLOR / --json / --quiet aware |
| `desktop/src/pairing.ts` | readline-based 6-char prompt (`A-Z0-9`); headless mirror of TUI's Ink prompt; `validatePairingPayloadString` discriminated-union wrapper |
| `desktop/src/credentials.ts` | Precedence: `--token` → `--pair-qr` (probe+pair) → `--code` → stored → prompt; returns `Credentials{sessionToken?, pairingCode?, resolvedEndpoint?}` |
| `desktop/src/transport/RelayTransport.ts` | Fork of ui-tui's transport + reconnect state machine (`idle/connecting/connected/reconnecting`, exp backoff 1→30s, 5min on 429, gate re-check post-sleep) + pre-WS TLS probe for TOFU |
| `desktop/src/remoteSessions.ts` | Same file path as TUI (`~/.hermes/remote-sessions.json`, 0600); schema widened with `grants`, `ttlExpiresAt`, `endpointRole`, `toolsConsented`; `saveSession` back-compat overload |
| `desktop/src/commands/daemon.ts` | Headless WSS + tool router for always-on access; JSON-line logs; fails closed on missing consent unless `--allow-tools` with explicit `--token` |
| `desktop/src/commands/doctor.ts` | Local-only diagnostic report — version / binary path / PATH / sessions / daemon detection; `--json` for support-paste; omits tokens entirely |
| `desktop/src/relayUrlPrompt.ts` | First-run URL fallback — `resolveFirstRunUrl()` auto-picks single stored session, numbered picker for multiple, welcome banner for zero; throws on non-interactive + ambiguous |
| `desktop/src/version.ts` | Build-time-generated constant (`npm run gen:version` before every build) — Bun compiled binaries can't read package.json via `__dirname` so version is embedded at build |
| `desktop/scripts/install.sh` / `install.ps1` | curl/iwr one-liner installers — download prebuilt Bun binary (no Node required), SHA256-verified, API-resolver for `latest` that includes prereleases, version-aware pre/post-install readback |
| `desktop/scripts/uninstall.sh` / `uninstall.ps1` | 3-tier removal — default (binary + PATH), `--purge` (also wipes `~/.hermes/remote-sessions.json`), `--service` (stub for future service installers); Windows iex-safe env-var fallback |
| `desktop/README.md` | User-facing install + usage reference |
| **Desktop CLI — dev iteration** | |
| `npm run smoke` (in `desktop/`) | Builds Windows binary + runs `--version` / `--help` / `doctor`, fails loud on zero-output. Local pre-flight before cutting any tag. |
| `npm run gen:version` | Regenerates `src/version.ts` from `package.json`. Runs automatically before every `build` / `build:bin:*`. |
| `release-cli.yml → Smoke-test Linux binary` step | CI-side equivalent: runs compiled Linux binary through the same 3-command check before uploading assets. Catches silent-exit-0 + segfault classes. |
| **Server — Desktop tool routing (Phase B)** | |
| `plugin/relay/channels/desktop.py` | Mirrors `bridge.py` — `desktop.command`/`desktop.response`/`desktop.status`, UUID-correlated futures, 30s timeout, single-client MVP, per-session advertised-tools set |
| `plugin/tools/desktop_tool.py` | 24 `desktop_*` tools (fs/shell/powershell/process/jobs/transfer/health) — registers with `tools.registry` under `desktop` toolset; per-tool `check_fn` pings `/desktop/_ping?tool=<name>`; `desktop_health` is `_RELAY_ONLY` and pings `/desktop/health` so it works even when the client is wedged |
| **Gradle modules — experimental Quest/XR (in development)** | |
| `relay-core/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.core`) — shared pairing/transport/terminal/voice/wire for the Quest port; not yet wired into the shipped `:app` |
| `relay-ui/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.ui`) — shared Compose UI (sphere, terminal WebView, QR scanner) for the Quest port; carries its own sphere copy |
| `quest/` | [EXPERIMENTAL] Meta Spatial SDK Quest/XR app — gradle `includeBuild("quest")`; needs further development, not shipped |
| **Tooling — dev iteration (not shipped)** | |
| `ui-preview/` | Desktop Compose Hot Reload harness — JVM Compose for Desktop; source-shares `MorphingSphereCore` from `:relay-ui`; `Main.kt` gallery; see `ui-preview/README.md` |
| `app/src/test/.../screenshots/StoreScreenshotTest.kt` | Roborazzi host-side store/docs screenshot renderer — deterministic, no device, exact 1080×2160; reuses real components+chrome with mock data; `capture(name, themeId){…}` renders any view; see `docs/screenshot-automation.md` §Deterministic rendering (JDK-21 + no-plugin gotchas) |
## What NOT to Do
- **Don't use XML layouts** — Compose only
- **Don't use Gson** — kotlinx.serialization
- **Don't use Ktor for networking** — OkHttp for WebSocket
- **Don't use plaintext WebSocket** — `wss://` only, even in development
- **Don't put documentation in root** — long-form docs go in `docs/`
- **Don't forget DEVLOG.md** — update it (record *what happened*)
- **Don't bury follow-ups** — deferred work / known gaps go in `TODO.md`, never in DEVLOG or one-off code/doc comments
- **Don't touch production / remote hosts** — automation and orchestrated agents must NEVER SSH into, deploy to, pull/restart/reconfigure, or push code to a live/remote Hermes host. Building, on-device testing, and server deployment are owner-driven (see Server Deployment). Stop at committing on your branch; surface "this needs a deploy/on-device check" rather than doing it.
## MCP Tooling
Two MCP servers are configured for AI-assisted development. See `docs/mcp-tooling.md` for full reference.
| Server | Layer | Requires |
| ------------------- | --------------------------------------------------------------- | ---------------------------------------- |
| `android-tools-mcp` | IDE/Build — Compose previews, Gradle, code search, Android docs | Android Studio running with project open |
| `mobile-mcp` | Device/Runtime — tap, swipe, screenshot, app management | ADB + connected device/emulator |
## Dev Workflow
```bash
scripts/dev.bat build # Build debug APK (DEV_MODE=true)
scripts/dev.bat release # Build signed release APK (DEV_MODE=false)
scripts/dev.bat bundle # Build release AAB for Google Play upload
scripts/dev.bat run # Build + install + launch + logcat
scripts/dev.bat test # Run unit tests
scripts/dev.bat version # Show current version from libs.versions.toml
scripts/dev.bat relay # Start relay server (dev mode, no SSL)
```
### Bridge smoke test (run on hermes-host, not local PC)
```bash
scripts/bridge-smoke.sh # full suite, destructive ON
scripts/bridge-smoke.sh --no-destructive # read-only paths only
scripts/bridge-smoke.sh --filter open_app # re-run a single test
scripts/bridge-smoke.sh --pair ABCDEF # register pairing code first
```
Curls every bridge HTTP route via `localhost:8767`. Catches the silent-drop regression class (Python relay registers a route but Kotlin dispatcher's `when (path)` has no matching branch). Run after every relay restart.
### Typical Dev Loop
1. **Edit locally** — Windows checkout. Both plugin (`plugin/`) and app (`app/`) live here.
2. **Python syntax check** — `python -m py_compile plugin/<file>.py`. Full tests run on the server.
3. **Kotlin changes** — do NOT run `gradle build`. Bailey builds via Android Studio's ▶ button. Never `adb install` from Claude.
4. **Before pushing Kotlin changes** — run `./gradlew lint` locally. It's the exact task CI runs and catches errors Android Studio's live inspections miss — e.g. `UnsafeOptInUsageError` with `kotlin.OptIn` vs `androidx.annotation.OptIn`, `FlowOperatorInvokedInComposition` (mapped flows inside Composables), Media3 `@UnstableApi` propagation. Android CI runs lint alongside build/test for faster feedback, but a local lint run still surfaces issues before the workflow spends runner time compiling and packaging.
5. **Commit + push** — follow `AGENTS.md` and `RELEASE.md`; normal work PRs to `dev`.
6. **Pull + restart on server** — see Server Deployment below.
7. **Test on phone** — Bailey builds from Studio, installs to Samsung device, pairs via `/hermes-relay-pair`.
### Server Deployment
Server is a Linux box running hermes-agent with hermes-relay editable-installed (`pip install -e`). Sensitive details (IP, user, secrets) in `~/SYSTEM.md` on the server — not in this repo.
| What | Where |
| ------------------ | ------------------------------------------------------------------ |
| hermes-agent repo | `~/.hermes/hermes-agent/` |
| hermes-relay clone | `~/.hermes/hermes-relay/` |
| Plugin symlink | `~/.hermes/plugins/hermes-relay` → `~/.hermes/hermes-relay/plugin` |
| Config | `~/.hermes/config.yaml` + `~/.hermes/.env` |
| Relay log | `journalctl --user -u hermes-relay -f` |
**Update:** `hermes-relay-update` (idempotent, re-fetches install.sh). Or manually: `git pull --ff-only && systemctl --user restart hermes-relay`.
**Compat hook:** `hermes relay compat status/install/remove` manages only the
optional `hermes_relay_bootstrap.pth` startup hook. New installs load the
plugin-owned bootstrap from `plugin/hermes_relay_bootstrap/`; the repo-root
package is only a legacy import shim. Vanilla Hermes chat, Manage, and dashboard voice
must not depend on this hook.
**Key conventions:**
- Phone pairing **survives** relay restart — `SessionManager` persists sessions to `~/.hermes/hermes-relay-sessions.json` (`server.py:88-90`, `persistence_path` from `RelayConfig.from_env`); a trusted-device refresh token recovers a lost/revoked/reset session without a new QR scan. (Only the in-memory *live-connection presence* clears on restart; the phone reconnects automatically.)
- Use `python -m unittest` not `pytest` — conftest imports `responses` which may not be installed
- `_env_bootstrap.py` loads `~/.hermes/.env` on every relay start — no stale API keys
### Where Python vs. Kotlin changes land
| Change type | Who restarts? | Command |
| ------------------------------------ | ------------------------ | -------------------------------------------------- |
| Plugin tool (`android_tool.py` etc.) | `hermes-gateway.service` | `systemctl --user restart hermes-gateway` |
| Relay code (`plugin/relay/*.py`) | `hermes-relay.service` | `systemctl --user restart hermes-relay` |
| Pair CLI / skill files | — | No restart — fresh process / scanned on invocation |
| Android app | Bailey (Studio) | Studio run button |
### Release Process
See [AGENTS.md](AGENTS.md) for the canonical branch contract and
[RELEASE.md](RELEASE.md) for version sources, release trains, surface tags,
hotfixes, secrets, publishing, and verification. Claude-specific automation
must not infer release authority from feature completion.
## Integration Points
| Surface | Endpoint | Notes |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chat (gateway) | Dashboard `POST /api/auth/ws-ticket` -&gt; WS `/api/ws` | Vanilla Hermes dashboard/tui_gateway path; live thinking/reasoning; requires dashboard auth |
| Chat streaming | `POST /v1/runs` → `GET /v1/runs/{id}/events` | Structured tool events; async run-control path |
| Chat (sessions) | `POST /api/sessions/{id}/chat/stream` | Native upstream session-persisted SSE; preferred when capability probe finds it |
| Chat (compat) | `POST /v1/chat/completions` (stream=true) | Inline tool annotations only |
| Session CRUD | `GET/POST/PATCH/DELETE /api/sessions` | Native upstream (#33134); bootstrap fallback retired |
| Manage | Dashboard `/api/status`, `/api/auth/me`, `/api/config`, `/api/profiles/*`, `/api/env`, `/api/model/*`, `/api/mcp/*` | Vanilla Hermes dashboard surface; do not proxy through Relay |
| Vanilla Hermes voice | Dashboard `POST /api/audio/transcribe`, `POST /api/audio/speak` | Vanilla Hermes no-plugin voice; uses dashboard session from Manage |
| Pairing (QR) | `POST /pairing/register` (loopback only) | Via `/hermes-relay-pair` or `hermes-pair` shim; accepts optional `endpoints` for multi-endpoint QRs |
| Pairing (multi-endpoint) | QR `endpoints` array (ADR 24) | `hermes: 3` schema; ordered `lan`/`tailscale`/`public`/... candidates; phone re-probes on network change |
| Pairing auth | WSS `auth.ok` payload | Includes `expires_at`, `grants`, `transport_hint` |
| Tailscale Serve (ADR 25) | `hermes-relay-tailscale enable|disable|status` CLI | Fronts loopback `:8767` with `tailscale serve --bg --https=<port>`; auto-retires on upstream PR #9295 |
| Inbound media (token) | `GET /media/{token}` | Bearer auth; 24h TTL |
| Inbound media (path) | `GET /media/by-path?path=<abs>` | Permissive by default; `RELAY_MEDIA_STRICT_SANDBOX=1` to restrict |
| Session management | `GET /sessions`, `DELETE /sessions/{prefix}`, `PATCH /sessions/{prefix}` | List/revoke/extend; RelayHttpClient |
| Voice transcribe | `POST /voice/transcribe` | multipart/form-data; bearer auth |
| Voice synthesize | `POST /voice/synthesize` | JSON → audio/mpeg; max 5000 chars |
| Voice config | `GET /voice/config` | Returns current tts/stt provider info |
| Plugin diagnostics | `hermes relay doctor --json` | Reports upstream route reachability, Relay loopback state, plugin layout, and legacy bootstrap state |
| Compat hook lifecycle | `hermes relay compat status/install/remove` | Optional legacy API compatibility hook; not required for the standard path |
| Notifications | `GET /notifications/recent?limit=N` | Loopback callers skip bearer |
| Relay health | `GET /health` on `:8767` | Used by `RelayHttpClient.probeHealth()` |
| Capabilities | `GET /v1/capabilities` plus targeted `HEAD` probes | Prefer capabilities when present; HEAD probes keep mixed-version fallback working |
| Desktop CLI (tui channel) | WSS `tui.attach` / `tui.rpc.request` / `tui.rpc.event` | Same channel + envelopes as the Ink TUI — the CLI just renders events as plain lines. Zero server changes. |
| Desktop CLI (terminal channel) | WSS `terminal.attach` / `terminal.input` / `terminal.output` / `terminal.resize` / `terminal.detached` | Existing channel (shared with Android). CLI `shell` subcommand attaches, injects `clear; exec hermes\n` 350ms after ack, pipes raw bytes. `Ctrl+A .` detaches (tmux preserved), `Ctrl+A k` kills. |
| Desktop CLI tool visibility | `tools.list` RPC on the shared tui channel | Returns `{toolsets: [{name, description, tool_count, enabled, tools:[]}]}`; surfaced by `hermes-relay tools` |
| Desktop CLI devices | HTTP `GET/DELETE/PATCH /sessions` on the relay's same port | Wrapped by `hermes-relay devices list |
| Desktop tool routing (Phase B) | WSS `desktop.command` (s→c) + `desktop.response` (c→s) + `desktop.status` (c→s heartbeat) | New channel. Hermes calls `desktop_read_file(path)` → Python handler POSTs to `/desktop/desktop_read_file` → relay forwards over `desktop.command` → Node client's `DesktopToolRouter` runs the handler locally → response bubbles back. Mirror of Android's `bridge.command` pattern. |
| Desktop tool check_fn | HTTP `GET /desktop/_ping?tool=<name>` | Returns 200 if a client is connected AND advertises this tool; 503 otherwise. Hermes uses this to fail the tool quickly when no desktop client is live, instead of waiting 30s for the dispatch timeout. |
| Desktop health | HTTP `GET /desktop/health` | Returns full status snapshot — connected/host/platform/version/pid/uptime/advertised_tools/last_error/recent_commands. Loopback-only. Backs the `desktop_health` agent tool, which intentionally does NOT round-trip through the client so it remains callable when other tools are wedged. |
## Upstream References
| Topic | Upstream File |
| -------------------------- | ----------------------------------------------------------------------------- |
| API endpoints | `gateway/platforms/api_server.py` — all registered HTTP routes |
| Platform adapter interface | `gateway/platforms/base.py` — `BasePlatformAdapter` abstract class |
| Adding a platform | `gateway/platforms/ADDING_A_PLATFORM.md` — 16-step checklist |
| Platform registration | `gateway/run.py` → `_create_adapter()`, `gateway/config.py` → `Platform` enum |
| Channel directory | `gateway/channel_directory.py` — how platforms/channels are enumerated |
| Send message routing | `tools/send_message_tool.py` → `platform_map` dict |
| SSE streaming (runs) | `gateway/platforms/api_server.py` → runs endpoint, `_on_tool_progress` |
## Related Projects
- [**hermes-agent**](https://github.com/NousResearch/hermes-agent) — the agent platform (gateway, WebAPI, plugin system)
- [**android-tools-mcp**](https://github.com/Codename-11/android-tools-mcp) — our fork of Android Studio MCP bridge (Compose previews, Gradle, docs)
- [**mobile-mcp**](https://github.com/mobile-next/mobile-mcp) — device control MCP server (ADB, tap/swipe, screenshots)
@AGENTS.md
+6 -22
View File
@@ -1,33 +1,22 @@
# Hermes-Relay CLI+UI v__VERSION__
**Release Date:** 2026-08-25
**Release Date:** 2026-08-30
This beta makes the Desktop connector resilient through Relay interruptions,
aligns Windows computer control with current CUA Driver releases, adds a native
Linux ARM64 build, and hardens installation and update discovery.
This beta preserves complete multi-route pairing while preventing Desktop from dialing Dashboard-ingress Relay routes before Dashboard WebSocket ticket support is available. (Related: #399)
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64/arm64, and macOS x64/arm64; the management UI is Windows-only.
## What's changed
### Added
- **Linux ARM64 is a first-class release target.** The one-line installer,
updater, checksums, and release artifacts now cover both Linux x64 and arm64.
- **The public site shows the real Windows CLI UI.** Deterministic screenshots
cover connections, host access, activity, computer control, and updates.
### Changed
- **Public naming is aligned.** Releases use `Hermes-Relay CLI+UI` while the
beta keeps its existing `desktop-v*` tag and updater contract.
- **Saved hosts retain the full route topology.** Dashboard, Relay, optional API, route priority, transport protection, certificate pins, and the selected host survive LAN, Tailscale, and public-route changes without creating duplicate hosts.
- **API-less pairing is first-class.** Dashboard plus direct Relay can pair without inventing an optional API server, while secure-first ranking retains plain LAN as the final fallback.
### Fixed
- **The daemon reconnects instead of exiting after an interrupted Relay socket.** Relay restarts and repeated transient replacement failures stay on bounded automatic backoff, and terminal failures persist an accurate stopped reason for the UI.
- **Oversized desktop-tool output no longer closes the shared connection.** PowerShell output and every serialized desktop response stay inside the Relay WebSocket budget.
- **Current CUA Driver releases remain compatible by contract.** Driver 0.20 and newer are accepted when their manifest and required tools match Hermes, and Windows uses the manifest-declared direct standard-mode runtime instead of a stale machine-wide daemon.
- **Install and update discovery paginates the multi-surface release history.** Desktop releases remain discoverable after more Android and Server releases, Windows cooperative updates clean their released backup, and unsigned installers retain the normal SmartScreen warning.
- **Dashboard-ingress Relay routes fail closed on Desktop.** The daemon, host selector, and Relay transport reject ingress that requires a Dashboard WebSocket ticket and choose a compatible direct Relay fallback instead of attempting an unauthenticated dial.
- **Pairing accepts the current v3 candidate shape.** Optional API records, same-origin Dashboard/Relay routes, and legacy top-level payloads remain compatible without collapsing route ownership.
## Install
@@ -58,9 +47,4 @@ hermes-relay --version
hermes-relay hosts list --json
hermes-relay daemon start
hermes-relay daemon status --json
hermes-relay computer-use status --json
```
On Windows, click the Hermes-Relay CLI UI notification-area icon to open the management popup directly above it.
See the [CLI and tray guide](https://hermes-relay.dev/docs/desktop/) for installation, access modes, grants, and troubleshooting.
+24 -8
View File
@@ -61,6 +61,15 @@ configuration between invocations and do not add `--no-daemon` to normal dev
commands; a different heap or Java home starts a separate daemon and discards
the warm-process benefit.
On Windows, all repository dev helpers serialize Android build and device work
through one machine-wide lane shared by every Hermes-Relay worktree. Use
`scripts/android-lane.ps1` for ad hoc Gradle, connected-test, and APK-install
commands, and keep Android Studio idle while another owner holds the lane. For
an exact commit that is already pushed, prefer the `Android On-Demand` workflow
for heavy verification so concurrent worktrees use isolated GitHub-hosted
runners. See [Android build execution](docs/android-build-lane.md) for cloud
presets, the optional full local gate, status, and recovery modes.
Use the narrowest command that proves the change:
1. `scripts/dev.bat compile` for a Kotlin compile check.
@@ -68,7 +77,10 @@ Use the narrowest command that proves the change:
3. `scripts/dev.bat install-fast` when the result must run on the connected
arm64 phone. This passes `-Phermes.devAbi=arm64-v8a`, avoiding the x86,
x86_64, and armeabi-v7a native libraries in the local APK.
4. `scripts/dev.bat prepush` before pushing Android work.
4. `Android On-Demand` after an exact commit is pushed for lint, broad checks,
assemblies, or release smoke.
5. `scripts/dev.bat prepush` only when full local verification is explicitly
wanted or cloud execution is unavailable.
`install-fast` is intentionally phone-specific. Use `install` for a universal
sideload debug APK or when the target ABI is not arm64. Release builds remain
@@ -258,12 +270,16 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
## Testing
- **Android pre-push gate:** `scripts\dev.bat prepush` on Windows or
`./scripts/dev.sh prepush` on macOS/Linux. This runs the Android repository
checks, Google Play debug lint, and the same focused unit-test shard used by
CI in one cached Gradle invocation. Run it before pushing Android PR updates
to catch common hosted failures without waiting for another full Actions
cycle; hosted CI remains the exhaustive all-variant gate.
- **Android cloud verification (preferred for pushed work):** dispatch the
registered `Required checks` workflow with an exact base/head SHA pair and
`android_preset` set to `focused`, `lint`, `assemble-debug`, `release-smoke`,
or `all-final`. It calls the reusable Android workflow from `dev`. Check for
an existing run before dispatching the same SHA/preset again. The four
`all-final` compute jobs use isolated runners and may execute concurrently.
- **Full local Android gate (optional):** `scripts\dev.bat prepush` on Windows
or `./scripts/dev.sh prepush` on macOS/Linux. This retains the repository
checks, full Android lint, and both focused flavor shards for an explicit local
run or cloud outage. On Windows it acquires the machine-wide lane.
- **Focused Android unit test:** `scripts/dev.bat test-one "<fully-qualified-class-or-pattern>"`
- **Android unit tests:** `scripts/dev.bat test` (runs the sideload debug JUnit + MockK + Compose suite)
- **Gateway contract lab:** [`docs/gateway-contract-testing.md`](docs/gateway-contract-testing.md)
@@ -272,7 +288,7 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
device lane is scheduled automatically.
- **Python tests:** `python -m unittest plugin.tests.test_<name>` from the repo root with the hermes-agent venv active. `pytest` works too but the pre-existing `conftest.py` imports a module that isn't always installed — `unittest` avoids that entirely.
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched.
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched. The registered `ci-required.yml` dispatcher calls `android-on-demand.yml` as the trusted manual compute lane for an exact pushed commit; it does not replace required PR checks.
Superseded Android runs on `dev` and PR refs are canceled automatically; `main`
runs are never canceled because each release-branch commit must complete its
independent validation.
+35
View File
@@ -1,5 +1,40 @@
# Hermes-Relay — Dev Log
## 2026-08-31 — Android Gateway compaction watchdog lease
Gateway turns now recognize the upstream `status.update` payload kind
`compacting` and arm a ten-minute idle lease instead of the ordinary
three-minute watchdog. A single current-Gateway status protects silent
compaction, while repeated status heartbeats from newer gateways refresh the
same lease. Other status payloads retain the ordinary watchdog.
Focused Gateway client coverage uses shortened timeout seams to prove the
single-status, repeated-heartbeat, ordinary-silence, and payload-fencing paths
without waiting production minutes. The declarative vanilla-Gateway fixture
also models repeated compaction status before terminal completion.
## 2026-08-31 — Complete, readable Android release notes
Android release metadata now keeps one overall title and summary plus a complete
typed inventory of user-visible additions, improvements, and fixes. Stable
change ids prevent duplicate records, selected highlights lead the expanded
view, and compatibility boundaries remain visible without turning the compact
notice into technical release documentation. Toast counts and previews are
derived from the same non-highlighted changes the dialog and history render, so
View all reaches every counted item. Older bundled changelog entries retain
their existing rendering path.
The Android 1.14.0 record was migrated to the complete schema and reconciled
against its released Android changelog: four highlights, two additional
improvements, ten fixes, and three compatibility notes. The dialog, full
history, large-text toast, seven Android resource catalogs, legacy text
fallback, Play note, listing copy, release-prep instructions, and validation
tests were updated together.
Structured release-note tests, focused Kotlin tests, Android locale and
collection-API gates, rendered 360×640 dark-theme screenshots including 135%
text, sideload APK assembly, Android lint, and diff checks passed.
## 2026-08-27 — Fixed issue ownership and bounded PR intake
The automated issue first-response lane now assigns only `Codename-11` when the
+14 -9
View File
@@ -1,26 +1,29 @@
# Hermes-Relay Plugin v__VERSION__
**Release Date:** August 25, 2026
**Release Date:** August 30, 2026
## Summary
This release adds a provider-neutral account-usage surface for Android and Dashboard clients. Relay resolves Codex credential pools, structured Nous balances, and OpenCode Go windows on the Hermes host without returning provider credentials.
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
This release lets one authenticated Hermes Dashboard origin carry Gateway plus optional Relay extensions, adds a bounded Git workspace, and reorganizes the Dashboard plugin around operator tasks. Standard chat, session history, profiles, Manage, and standard voice remain upstream-owned and do not require this plugin.
## Added
- **Provider-neutral usage snapshots.** Authenticated Dashboard clients can resolve the exact active Codex pool entry, Nous balances, and OpenCode Go account windows through one normalized schema.
- **Bounded paired-client fallback.** Operators may explicitly enable the Relay usage route for paired standalone clients while credentials remain host-side.
- **Dashboard same-origin Relay ingress.** Fixed allowlisted HTTP and WebSocket routes proxy to the local Relay while Dashboard admission and Relay session authentication remain independent. (Related: #399)
- **Bounded Git workspace.** Configured roots, path containment, line totals, diffs, branches, staging, commits, remotes, grants, and explicit confirmations protect repository operations.
## Changed
- **Usage capabilities are explicit.** Responses identify Relay-enhanced credential pools, structured balances, and provider adapters instead of implying unsupported upstream data.
- **Public product naming is aligned.** Releases use `Hermes-Relay Plugin` while retaining the `server-v*` tag and installation contract.
- **Task-oriented Dashboard UI.** Overview, Devices, Activity, Remote Access, Git, and Settings now have dedicated surfaces with QR-first pairing, responsive device cards, and honest media diagnostics. (#486)
- **One explicit route topology.** Dashboard, CLI, and TUI pairing advertise Dashboard, Relay, and optional API surfaces with stable priorities across Tailscale, public HTTPS, and LAN.
- **Dedicated Tailscale listener.** Recommended setup uses tailnet HTTPS `:10443` to local Dashboard `:9119`, avoiding ownership of a reverse proxy's `:443`. Existing `:443`, `:9119`, and direct `:8767` routes remain migration compatibility.
## Fixed
- **Custom Hermes homes resolve correctly.** Relay profile discovery and session persistence follow `HERMES_HOME` by default while preserving the explicit `RELAY_HERMES_CONFIG` override.
- Public and roaming invites no longer synthesize closed direct Relay `:8767` or wrong Dashboard `:9119` routes.
- Ambiguous, credential-bearing, or plaintext public candidates fail closed before an invite is exposed.
- Dense pairing QRs use integer-sized modules and a full quiet zone.
- Inactive optional API routes are omitted; protected Dashboard-ingress `401/403` responses display as authentication-required while direct Relay and API failures remain failures.
- Default Tailscale disable actions remove only owned listeners, and explicit migration cleanup accepts only the bounded supported ports.
## Install / update
@@ -32,6 +35,8 @@ Standard chat, session history, and Vanilla Hermes voice remain upstream-owned a
# or, if already installed:
hermes-relay-update
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest, routes, and committed Dashboard bundle are active.
## Verify
hermes relay doctor
+5 -5
View File
@@ -99,7 +99,7 @@ The wizard probes everything and finishes with a capability card:
| **Chat** | Dashboard/Gateway ready — you can talk |
| **Manage** | Models, keys, skills, and profiles are available from the phone |
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
| **API fallback** | Optional API route available/unavailable |
| **Direct API** | Optional API-only compatibility route available/unavailable |
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
@@ -140,7 +140,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. The API fallback is optional; the Hermes-Relay plugin is encouraged for the complete experience.
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
## Screenshots
@@ -240,13 +240,13 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
```
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
```
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
install needs no plugin for either. The optional relay on `:8767` adds the power
surfaces: terminal, bridge phone control, media handoff, machine tools, and
+30 -27
View File
@@ -531,13 +531,14 @@ the new app version and a higher `appVersionCode`.
`retrace <mapping.txt> <obfuscated-trace.txt>`. Play reports can additionally
use the mapping bundled into the uploaded AAB through Play Console.
- `app/src/main/assets/changelog.json` — curated source for the in-app
**What's New** dialog and Android release history. Prepend the newest entry
with one explicit `highlight` (`title`, plain-language `summary`, and 1–3
user-benefit bullets), up to two quieter `improvements`, Android-only
`playNotes`, a `toastDigest` with counts and 0–2 short previews for noteworthy
items beyond the hero, and the existing technical `sections` used by older clients.
Do not derive the highlight mechanically from `CHANGELOG.md`; choosing the
release's main reason to care is an editorial release-prep decision.
**What's New** dialog and Android release history. Prepend one schema-3 entry
with a single descriptive release `title`, a plain-language `summary`, and a
complete `changes` inventory. Every user-visible change has a stable `id`, a
`kind` (`added`, `improved`, or `fixed`), a short title, a useful explanation,
and an optional `highlight: true`; select 1–4 highlights. Add `compatibility`
bullets only when users need an availability, migration, flavor, or Plugin
boundary, plus Android-only `playNotes`. The app derives toast counts and
previews from the same inventory and renders every change exactly once.
- `app/src/main/assets/whats_new.txt` — legacy in-app fallback generated from
the newest structured entry. Do not edit it independently.
- `app/src/googlePlay/play/release-notes/en-US/default.txt` — the Play
@@ -551,8 +552,8 @@ the new app version and a higher `appVersionCode`.
block and the Gradle Play Publisher note are generated from `playNotes`.
After editing the newest structured entry, run
`python scripts/check-android-release-notes.py --write`, then run it again
without `--write` to validate the 1–3 / 0–2 editorial limits, current Android
version, GitHub-release/changelog headings, derived files, and Play's
without `--write` to validate complete unique change records, 1–4 highlights,
the current Android version, GitHub-release/changelog headings, derived files, and Play's
**500-character** limit. Frame Play copy around the release's themes, not a
feature dump. Compare its **Foreground service
permissions** section with the merged `googlePlayRelease` manifest and
@@ -570,28 +571,30 @@ authoring contract; do not maintain a separate prompt file.
boundary that users must understand. Do not generate from commit titles or
a mixed-surface changelog block alone.
2. Before editing release files, show a temporary coverage ledger in the task
output. Map every selected source change to exactly one placement:
`hero`, `secondary`, or `full-only`. Include the change kind (`feature`,
`change`, or `fix`) and a short reason. The ledger is review evidence, not a
committed public artifact; no selected source item may disappear silently.
3. Choose exactly one `hero`: the strongest user-facing reason to care about
the release. Its summary is one plain-language outcome, and its 1–3 bullets
are distinct user benefits rather than implementation steps or filler.
4. Use `secondary` for other important user-visible features and fixes. The
`toastDigest` counts only these items, excluding the hero. Preview the
strongest 1–2 secondary items in short phrases. If there are no legitimate
secondary items, set both counts to `0` and `preview` to `[]`; the app hides
the footer. Never invent an item to satisfy the layout.
5. Use `full-only` for technically relevant details that belong in
`RELEASE_NOTES.md` or `CHANGELOG.md` but would make the collapsed update card
noisy. Preserve user-relevant trust and compatibility limits; omit branches,
worktrees, CI mechanics, debugging history, and private/operator context.
output. Map every selected Android source change to one stable change id and
one kind (`added`, `improved`, or `fixed`), and mark whether it is a
highlight. The ledger is review evidence, not a committed public artifact;
no selected user-visible change may disappear silently or be counted twice.
3. Write one release title that describes the release as a whole. Do not let a
narrow feature name, internal project label, or poetic codename replace the
title users see in the toast and history. Follow it with a one- or two-sentence
summary that gives the release's overall outcome without becoming a feature dump.
4. Select 1–4 highlights from the complete change inventory. A highlight is a
strong reason to care, not a second copy of the change: the app presents it
once in the highlight section and derives the remaining counts and previews
from non-highlighted changes.
5. Include every meaningful user-visible addition, improvement, and fix in
`changes`, using plain titles and enough explanation for someone to recognize
the affected behavior. Internal refactors, tests, CI mechanics, branch work,
and debugging history stay in `RELEASE_NOTES.md`, `CHANGELOG.md`, or engineering
records unless they materially change reliability, security, or compatibility.
6. Write each surface for its audience:
- `RELEASE_NOTES.md`: concise Summary plus Added/Changed/Fixed; keep the
deterministic Download and Install/Verify scaffolding intact.
- `CHANGELOG.md`: complete, crisp public history for the released surface.
- `changelog.json`: curated hero, optional improvements, digest, Play copy,
and compatibility `sections` for older clients.
- `changelog.json`: overall title/summary, complete typed changes, selected
highlights, compatibility boundaries, and Play copy. Counts and previews
are derived; never author a parallel digest.
- `playNotes`: Android-only themes within the rendered 500-character limit.
7. Before presenting the draft, check that wording begins with user outcomes,
avoids unexplained implementation terminology, uses exact public product
+24 -11
View File
@@ -1,10 +1,10 @@
# Hermes-Relay Android v1.13.2
# Hermes-Relay Android v1.14.0
**Release Date:** August 25, 2026
**Release Date:** August 30, 2026
## Download
> Installing on your phone? Download `hermes-relay-1.13.2-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
> Installing on your phone? Download `hermes-relay-1.14.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
@@ -12,20 +12,33 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
## Summary
This release adds a parent-configured Supervised Mode and improves its return from full settings. It also keeps session rows neutral until live activity is confirmed.
This release makes saved Hermes connections reliable across LAN, Tailscale, and public HTTPS while keeping Dashboard authentication bound to its exact trusted origin. It also adds delegated-agent previews and an optional native Git workspace, and improves Voice, Assistant, Threads, profile drafts, and Clarify interactions.
## Added
- Use a profile-pinned Supervised Mode with parent-controlled attachments, Standard voice, generated media, history, actions, and technical details. Device authentication protects full settings; this remains a client-side restricted view rather than a server-enforced account boundary.
- **Delegated-agent previews.** Follow bounded lifecycle, progress, tool previews, and available read-only child history without leaving the parent chat. Partial history and reconnect gaps remain explicit. (#447)
- **Native Git workspace.** Review repository state, diffs, branches, staging, commits, and remotes from Chat or Settings. Git operations require Hermes-Relay Plugin v1.11.0 and retain confirmation and grant boundaries.
## Changed
- **Route-aware connections.** Dashboard, Relay, and optional API health are evaluated independently across LAN, Tailscale, and public HTTPS. Same-origin Relay ingress stays on the Dashboard origin that owns authentication, while direct compatibility routes keep separate credentials. (Related: #399)
- **Voice Focus controls.** Stop and immediate spoken steering remain accessible while Hermes is Thinking, Transcribing, or Speaking, including TalkBack, Switch Access, keyboard, and sideload overlay surfaces.
## Fixed
- Keep session rows neutral while optional live activity is unavailable or still loading, and reserve full-row activity borders for actual Starting or Working turns.
- Keep Supervised Chat rendered when parent access relocks after visiting full settings.
- Wake-word detection packages one compatible ONNX Runtime for sherpa and Java JNI on every supported ABI. (#444)
- Continuous voice waits for barge-in microphone teardown before listening again. (#464)
- Fresh chats retain their selected profile without reopening a previous session or carrying a proactive Thread route across profiles. (#436)
- Provisional Threads can be removed locally and reconcile with promoted sessions without deleting server history. (#461)
- Clarify cards expose a reachable Other answer, keyboard Send, and authoritative expiry behavior. (#446)
- Passive Android browsing no longer claims or interrupts a turn owned by another client. (Related: #365)
- Assistant sessions show retryable no-speech feedback, recover their active state after recreation, and redact conversation details behind the keyguard. (Related: #424)
- Protected Relay ingress `401/403` responses are recognized as authentication boundaries rather than outages; malformed, different-origin, and direct unauthorized routes still fail closed.
## Install / Verify
- App version: **1.13.2** (versionCode **51**).
- Standard Chat, sessions, Manage, sharing, profile switching, and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
- Granular Device Control remains sideload-only; the Google Play build continues to ship Hermes Bridge Core without AccessibilityService Device Control.
- The optional Relay plugin remains unnecessary for standard Android chat, sessions, Manage, and Vanilla Hermes voice.
- App version: **1.14.0** (versionCode **52**).
- Standard Chat, sessions, profiles, Manage, and standard voice continue to work against unmodified upstream Hermes without the optional Relay plugin.
- Install Hermes-Relay Plugin v1.11.0 for same-origin Relay extensions, Git workspace actions, Bridge, media, proactive features, and enhanced voice.
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
- Existing connections, drafts, sessions, profile ownership, and legacy direct Relay routes remain data-preserving compatibility paths.
+25
View File
@@ -6,6 +6,31 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
---
## Restore the plugin manifest v2 declaration after the Hermes installer fix ships
Hermes installers in affected stable releases reject `manifest_version: 2`
before the v2-capable runtime loader can inspect the plugin. Track upstream
[PR #85893](https://github.com/NousResearch/hermes-agent/pull/85893). Restore
`plugin/plugin.yaml` to `manifest_version: 2` only after that fix ships in a
stable Hermes release that Hermes-Relay can treat as its minimum supported
version. Until then, keep the v1 compatibility declaration and the additive
metadata consumed by newer hosts.
---
## Consider hosted Android emulator execution
The local API 36 Gradle Managed Device lanes are intentionally on demand and
individually selected. The current Android On-Demand workflow covers hosted
source, unit, lint, and build verification only; it does not run emulators. If
local emulator capacity becomes a recurring constraint, evaluate a separately
approved hosted-emulator design with explicit cost, concurrency, artifact
retention, and trigger policy. Do not schedule the full form-factor matrix or
add a device farm until that policy is approved; keep live-server mutation tests
outside any automatic matrix.
---
## Upstream a public Dashboard plugin WebSocket admission seam
The same-origin Relay ingress follows current upstream's bundled Dashboard
+60 -2
View File
@@ -249,6 +249,58 @@ android {
it.systemProperty("roborazzi.test.record", "true")
it.maxHeapSize = "2g"
}
// On-demand only. Keep each form factor as an individually selected
// Gradle-managed device; there is deliberately no aggregate matrix
// task or scheduled emulator job. See docs/android-emulator-testing.md.
managedDevices {
localDevices {
create("compactPhoneApi36") {
device = "Pixel 2"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("standardPhoneApi36") {
device = "Pixel 6"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("largePhoneApi36") {
device = "Pixel 7 Pro"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("foldableApi36") {
device = "Pixel Fold"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("tabletApi36") {
device = "Pixel Tablet"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("futureApi37Ps16k") {
device = "Pixel 7 Pro"
apiLevel = 37
systemImageSource = "google_apis_playstore"
require64Bit = true
testedAbi = "x86_64"
pageAlignment =
com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES
}
}
}
}
}
@@ -390,6 +442,12 @@ dependencies {
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
testImplementation(libs.konsist)
androidTestImplementation(libs.compose.ui.test.junit4)
// Compose UI Test still declares Espresso 3.5.0 transitively. API 37
// removed the reflected InputManager.getInstance() seam; Espresso 3.7.0
// uses Context.getSystemService and is the current stable AndroidX line.
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test:runner:1.7.0")
androidTestImplementation("androidx.test.ext:junit:1.3.0")
// On-device vanilla-Gateway contract tests exercise the production
// Dashboard ticket + WebSocket stack over real loopback sockets.
androidTestImplementation(libs.okhttp.mockwebserver)
@@ -399,8 +457,8 @@ dependencies {
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
// Renders real composables on the JVM at an exact canvas — no device, no
// status bar, no clipping. See StoreScreenshotTest.
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.72.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.72.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.73.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.73.0")
testImplementation(libs.compose.ui.test.junit4)
testImplementation(libs.compose.ui.test.manifest)
testImplementation("androidx.test.ext:junit:1.3.0")
@@ -6,8 +6,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.test.platform.app.InstrumentationRegistry
@@ -28,50 +27,6 @@ class AmbientVisualizationVisibilityTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun cleanMode_backgroundOff_hidesSphereAndKeepsComposer() {
composeTestRule.setContent {
AmbientTestProviders(enabled = false) {
CleanChatMode(
messages = emptyList(),
isStreaming = false,
sphereState = SphereState.Idle,
streamingIntensity = 0f,
toolCallBurst = 0f,
animationEnabled = true,
enabled = true,
onSend = {},
onExit = {},
)
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertDoesNotExist()
composeTestRule.onNodeWithContentDescription(targetString(R.string.agent_text_send_cd))
.assertExists()
}
@Test
fun cleanMode_backgroundOn_rendersSphere() {
composeTestRule.setContent {
AmbientTestProviders(enabled = true) {
CleanChatMode(
messages = emptyList(),
isStreaming = false,
sphereState = SphereState.Idle,
streamingIntensity = 0f,
toolCallBurst = 0f,
animationEnabled = false,
enabled = true,
onSend = {},
onExit = {},
)
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertExists()
}
@Test
fun voiceMode_backgroundOff_hidesSphereAndKeepsVoiceUi() {
composeTestRule.setContent {
@@ -0,0 +1,160 @@
package com.hermesandroid.relay.ui.screens
import android.os.Handler
import android.os.Looper
import android.view.accessibility.AccessibilityNodeInfo
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import androidx.test.platform.app.InstrumentationRegistry
import com.hermesandroid.relay.data.BotGatewayRoute
import com.hermesandroid.relay.data.BotGatewayRouteKey
import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.viewmodel.AndroidGatewayContractFixture
import com.hermesandroid.relay.viewmodel.ChatViewModel
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.JsonPrimitive
import okhttp3.OkHttpClient
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/** On-device proof for the route-owned first-composition collection boundary. */
class BotChatScreenBindingInstrumentedTest {
private lateinit var fixture: AndroidGatewayContractFixture
private lateinit var gatewayScope: CoroutineScope
private lateinit var dashboardClient: DashboardApiClient
private lateinit var gatewayClient: GatewayChatClient
private lateinit var viewModel: ChatViewModel
private lateinit var handler: ChatHandler
private var activityScenario: ActivityScenario<BotChatBindingTestActivity>? = null
@Before
fun setUp() {
fixture = AndroidGatewayContractFixture()
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
dashboardClient = DashboardApiClient(
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
okHttpClient = OkHttpClient(),
)
gatewayClient = GatewayChatClient(
initialDashboardClient = dashboardClient,
okHttpClient = OkHttpClient(),
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
scope = gatewayScope,
reconnectJitterUnit = { 0.0 },
)
viewModel = ChatViewModel()
handler = ChatHandler()
}
@After
fun tearDown() {
activityScenario?.close()
viewModel.updateGatewayClient(null)
gatewayClient.shutdown()
gatewayScope.cancel()
dashboardClient.shutdown()
fixture.shutdown()
}
@Test
fun fastInitialHistoryRendersBeforeNavigationAndSurvivesLifecycleResume() {
val route = BotGatewayRoute(
key = BotGatewayRouteKey("fixture-gateway", PROFILE_NAME),
connectionLabel = "Fixture gateway",
)
val bot = BotRosterEntry(
profile = Profile(
name = PROFILE_NAME,
model = "fixture-model",
description = "Fixture profile",
),
displayName = "Research",
route = route,
)
val scenario = ActivityScenario.launch(BotChatBindingTestActivity::class.java)
.also { activityScenario = it }
scenario.onActivity { activity ->
activity.setContent {
MaterialTheme {
BotChatScreen(
route = route,
bot = bot,
sessionId = STORED_SESSION_ID,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = viewModel,
onBack = {},
handlerFactory = { handler },
historyLoader = { _, _, _ ->
Result.success(
listOf(
MessageItem(
id = HISTORY_ID,
sessionId = STORED_SESSION_ID,
role = "assistant",
content = JsonPrimitive(HISTORY_TEXT),
timestamp = 1.0,
finishReason = "stop",
),
),
)
},
profileIconFlow = { _, _ -> MutableStateFlow(null) },
)
}
}
}
waitUntil { handler.messages.value.singleOrNull()?.content == HISTORY_TEXT }
waitUntil { renderedTextExists(HISTORY_TEXT) }
scenario.moveToState(Lifecycle.State.STARTED)
scenario.moveToState(Lifecycle.State.RESUMED)
waitUntil { renderedTextExists(HISTORY_TEXT) }
assertEquals(0, fixture.rpcCount("prompt.submit"))
}
private fun renderedTextExists(expected: String): Boolean {
val instrumentation = InstrumentationRegistry.getInstrumentation()
instrumentation.waitForIdleSync()
val root = instrumentation.uiAutomation.rootInActiveWindow ?: return false
return root.containsText(expected)
}
private fun AccessibilityNodeInfo.containsText(expected: String): Boolean {
if (text?.toString() == expected || contentDescription?.toString() == expected) return true
return (0 until childCount).any { index -> getChild(index)?.containsText(expected) == true }
}
private fun waitUntil(condition: () -> Boolean) {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (System.nanoTime() < deadline) {
if (condition()) return
Thread.sleep(25)
}
assertTrue("Condition was not satisfied within 5 seconds", condition())
}
private companion object {
const val PROFILE_NAME = "research"
const val STORED_SESSION_ID = "20260829_120000_bot_chat"
const val HISTORY_ID = "persisted-bot-history"
const val HISTORY_TEXT = "Durable Bot Chat history is ready."
}
}
@@ -4,6 +4,7 @@ import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.Modifier
@@ -17,6 +18,11 @@ import androidx.compose.ui.test.onNodeWithTag
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
import com.hermesandroid.relay.data.ChatTurnCheckpoint
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
@@ -27,6 +33,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
@@ -44,6 +51,7 @@ import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
@@ -74,10 +82,11 @@ class GatewayForegroundRecoveryInstrumentedTest {
@Volatile
private var persistedHistory: List<MessageItem> = emptyList()
private val historySignInRequired = MutableStateFlow(false)
@Before
fun setUp() {
fixture = AndroidGatewayContractFixture()
fixture = AndroidGatewayContractFixture().also { it.profileName = PROFILE_NAME }
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
val okHttp = OkHttpClient()
gatewayClient = GatewayChatClient(
@@ -97,6 +106,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
handler,
)
it.streamingEndpoint = "gateway"
it.setSessionProfileNameProvider { PROFILE_NAME }
it.setProfileMessageLoader { Result.success(persistedHistory) }
it.updateGatewayClient(gatewayClient)
it.setChatVisible(true)
@@ -105,6 +115,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
compose.setContent {
val messages by viewModel.messages.collectAsStateWithLifecycle()
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
MaterialTheme {
Column(Modifier.testTag("contract-transcript")) {
Text(
@@ -117,6 +128,14 @@ class GatewayForegroundRecoveryInstrumentedTest {
modifier = Modifier.testTag("message-${message.id}"),
)
}
if (signInRequired) {
Button(
onClick = {},
modifier = Modifier.testTag("dashboard-sign-in-recovery"),
) {
Text("SIGN IN")
}
}
}
}
}
@@ -252,9 +271,6 @@ class GatewayForegroundRecoveryInstrumentedTest {
"session.interrupt",
"prompt.submit",
)
val baseline = controlMethods.associateWith(fixture::rpcCount)
val baselineActiveList = fixture.rpcCount("session.active_list")
fixture.activeSessionStatus = "working"
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
val okHttp = OkHttpClient()
gatewayClient = GatewayChatClient(
@@ -269,6 +285,17 @@ class GatewayForegroundRecoveryInstrumentedTest {
)
viewModel.setChatTurnCheckpointStore(null)
viewModel.updateGatewayClient(gatewayClient)
assertTrue(runBlocking { gatewayClient.observeAwait() })
serverSocket = fixture.awaitServerSocket()
viewModel.switchProfileContext(
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
STORED_SESSION_ID,
)
viewModel.updateSessionActivityDirectory(listOf(PROFILE_NAME to STORED_SESSION_ID))
val baseline = controlMethods.associateWith(fixture::rpcCount)
val baselineActiveList = fixture.rpcCount("session.active_list")
fixture.activeSessionStatus = "working"
viewModel.setChatVisible(true)
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
@@ -293,6 +320,141 @@ class GatewayForegroundRecoveryInstrumentedTest {
)
}
@Test
fun normalCompletion_genericHistory401RetainsTranscriptAndRequiresProfileSignIn() {
bindDashboardHistoryFailure(
body = "Unauthorized",
profileName = PROFILE_NAME,
)
viewModel.sendMessage("Keep this local transcript")
fixture.awaitRpc("prompt.submit")
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
serverSocket.send(
fixture.event(
"message.delta",
buildJsonObject { put("text", LOCAL_COMPLETION) },
LIVE_SESSION_ID,
),
)
serverSocket.send(
fixture.event(
"message.complete",
buildJsonObject { put("text", LOCAL_COMPLETION) },
LIVE_SESSION_ID,
),
)
compose.waitUntil(15_000) {
historySignInRequired.value &&
!handler.isStreaming.value &&
handler.messages.value.any { it.content == LOCAL_COMPLETION }
}
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
assertFalse(viewModel.isLoadingHistory.value)
assertTrue(handler.messages.value.any { it.content == "Keep this local transcript" })
assertTrue(handler.messages.value.any { it.content == LOCAL_COMPLETION })
assertNull(viewModel.chatFailure.value)
assertExactProfileHistoryOnly(PROFILE_NAME)
}
@Test
fun recoveredCompletion_sessionExpiredHistoryRetainsSettledTranscript() {
bindDashboardHistoryFailure(
body = """{"reason":"session_expired"}""",
profileName = PROFILE_NAME,
)
val now = System.currentTimeMillis()
val contextKey = AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME)
viewModel.setChatTurnCheckpointStore(
MemoryCheckpointStore(
ChatTurnCheckpoint(
contextKey = contextKey,
profileKey = PROFILE_NAME,
sessionId = STORED_SESSION_ID,
liveSessionId = LIVE_SESSION_ID,
transport = "gateway",
user = ChatTurnUserCheckpoint("recovered-user", "Resume this turn", now - 2_000L),
assistant = ChatTurnAssistantCheckpoint(
id = "recovered-assistant",
content = "Recovered partial",
timestamp = now - 1_900L,
),
priorUserMessageCount = 0,
baselineAssistantCount = 0,
startedAt = now - 2_000L,
updatedAt = now,
),
),
)
fixture.recoveryRunning = true
handler.setSessionId(null)
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
fixture.awaitRpc("session.activate")
serverSocket.send(
fixture.event(
"message.delta",
buildJsonObject { put("text", RECOVERED_COMPLETION) },
LIVE_SESSION_ID,
),
)
serverSocket.send(
fixture.event(
"message.complete",
buildJsonObject { put("text", RECOVERED_COMPLETION) },
LIVE_SESSION_ID,
),
)
compose.waitUntil(15_000) {
historySignInRequired.value && !handler.isStreaming.value
}
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
assertFalse(viewModel.isLoadingHistory.value)
assertTrue(
"recovered completion was not retained: ${handler.messages.value}",
handler.messages.value.any { it.content.contains(RECOVERED_COMPLETION.trim()) },
)
assertFalse(handler.messages.value.any { it.isStreaming || it.isThinkingStreaming })
assertNull(viewModel.chatFailure.value)
assertExactProfileHistoryOnly(PROFILE_NAME)
}
private fun bindDashboardHistoryFailure(body: String, profileName: String) {
fixture.profileName = profileName
fixture.historyFailureBody = body
val dashboard = DashboardApiClient(
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
okHttpClient = OkHttpClient(),
)
viewModel.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
dashboard.getSessionMessages(sessionId, profile, mode)
}
viewModel.setDashboardSignInRequiredHandler {
historySignInRequired.value = true
}
}
private fun assertExactProfileHistoryOnly(profileName: String) {
val historyRequests = fixture.historyRequestPaths()
assertTrue("no Dashboard history request was observed", historyRequests.isNotEmpty())
assertTrue(
"history escaped the exact profile: $historyRequests",
historyRequests.all { it.contains("profile=$profileName") },
)
}
private companion object {
const val STORED_SESSION_ID = "20260821_120000_fixture"
const val LIVE_SESSION_ID = "fixture-live-1"
@@ -301,6 +463,23 @@ class GatewayForegroundRecoveryInstrumentedTest {
const val PARTIAL_ANSWER = "Partial foreground answer"
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
const val FOREIGN_ANSWER = "Wrong session content"
const val PROFILE_NAME = "research"
const val LOCAL_COMPLETION = "Completed before Dashboard auth expired."
const val RECOVERED_COMPLETION = " and then recovered to completion."
}
}
private class MemoryCheckpointStore(
private var checkpoint: ChatTurnCheckpoint?,
) : ChatTurnCheckpointStore {
override suspend fun read(): ChatTurnCheckpoint? = checkpoint
override suspend fun write(checkpoint: ChatTurnCheckpoint) {
this.checkpoint = checkpoint
}
override suspend fun clear() {
checkpoint = null
}
}
@@ -320,6 +499,12 @@ internal class AndroidGatewayContractFixture {
@Volatile
var activeSessionStatus: String? = null
@Volatile
var historyFailureBody: String? = null
@Volatile
var profileName: String = "default"
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
sockets.add(webSocket)
@@ -377,6 +562,11 @@ internal class AndroidGatewayContractFixture {
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
)
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
path.startsWith("/api/sessions/") && path.contains("/messages") &&
historyFailureBody != null -> MockResponse()
.setResponseCode(401)
.setHeader("Content-Type", "application/json")
.setBody(historyFailureBody.orEmpty())
else -> MockResponse().setResponseCode(404)
}
}
@@ -388,7 +578,7 @@ internal class AndroidGatewayContractFixture {
put("session_id", sessionId)
put("running", recoveryRunning)
put("status", if (recoveryRunning) "streaming" else "idle")
put("info", buildJsonObject { put("profile_name", "default") })
put("info", buildJsonObject { put("profile_name", profileName) })
}
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
@@ -406,7 +596,7 @@ internal class AndroidGatewayContractFixture {
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
fun awaitRpc(method: String): JsonObject {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
while (System.nanoTime() < deadline) {
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
Thread.sleep(20)
@@ -415,7 +605,7 @@ internal class AndroidGatewayContractFixture {
}
fun awaitRpcCount(method: String, count: Int) {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
while (System.nanoTime() < deadline) {
if (rpcCount(method) >= count) return
Thread.sleep(20)
@@ -425,6 +615,10 @@ internal class AndroidGatewayContractFixture {
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
fun historyRequestPaths(): List<String> = requestPaths.filter {
it.startsWith("/api/sessions/") && it.contains("/messages")
}
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
fun shutdown() {
+4
View File
@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name="com.hermesandroid.relay.ui.screens.BotChatBindingTestActivity"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name="com.hermesandroid.relay.ui.screens.VoiceSettingsDesignQaActivity"
android:exported="true"
@@ -0,0 +1,6 @@
package com.hermesandroid.relay.ui.screens
import androidx.activity.ComponentActivity
/** Empty debug-only host populated by the Bot Chat lifecycle instrumentation. */
class BotChatBindingTestActivity : ComponentActivity()
@@ -1,3 +1,3 @@
v1.13.2 - Supervised Mode and clearer activity
v1.14.0 - Connections, delegated work, Git, and voice
Supervised Mode creates a simpler, profile-focused chat with device-protected parent settings and control over attachments, Standard voice, generated media, history, actions, and technical details. Activity indicators now appear only while Hermes is genuinely working, and returning from parent settings keeps Supervised Chat open.
Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.
+116 -1
View File
@@ -1,6 +1,121 @@
{
"schema": 2,
"schema": 3,
"versions": [
{
"version": "1.14.0",
"title": "Connections, delegated work, Git, and voice",
"date": "2026-08-30",
"summary": "Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.",
"changes": [
{
"id": "route-aware-connections",
"kind": "improved",
"title": "Connections recover independently",
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.",
"highlight": true
},
{
"id": "delegated-agent-previews",
"kind": "added",
"title": "Follow delegated-agent activity",
"summary": "See lifecycle, progress, tool previews, and available read-only child history from the parent chat.",
"highlight": true
},
{
"id": "native-git-workspace",
"kind": "added",
"title": "Work with repositories from Android",
"summary": "Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.",
"highlight": true
},
{
"id": "voice-focus-controls",
"kind": "improved",
"title": "Steer voice at any time",
"summary": "Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.",
"highlight": true
},
{
"id": "non-blocking-release-notice",
"kind": "improved",
"title": "Release notes stay out of your way",
"summary": "A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings."
},
{
"id": "single-chat-presentation",
"kind": "improved",
"title": "Chat uses one consistent presentation",
"summary": "The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available."
},
{
"id": "wake-word-runtime",
"kind": "fixed",
"title": "Wake-word detection starts reliably",
"summary": "Compatible native voice components are now packaged for every supported phone architecture."
},
{
"id": "sphere-motion",
"kind": "fixed",
"title": "The visible Sphere keeps moving smoothly",
"summary": "Foreground animation no longer falls back to a stepped ambient pulse."
},
{
"id": "continuous-microphone-handoff",
"kind": "fixed",
"title": "Continuous voice keeps the microphone",
"summary": "The next listening turn waits for barge-in recording to release cleanly."
},
{
"id": "fresh-profile-drafts",
"kind": "fixed",
"title": "New chats keep the selected profile",
"summary": "Fresh drafts no longer reopen an older session or carry a Thread route into another profile."
},
{
"id": "provisional-thread-removal",
"kind": "fixed",
"title": "Provisional Threads can be removed safely",
"summary": "Local removal and later session promotion no longer risk duplicate rows or server history."
},
{
"id": "clarify-custom-answers",
"kind": "fixed",
"title": "Clarify keeps custom answers reachable",
"summary": "Other answers, keyboard Send, and expired prompts now behave consistently."
},
{
"id": "passive-session-observation",
"kind": "fixed",
"title": "Browsing no longer interrupts another client",
"summary": "Passive Android observation does not claim a turn owned by Desktop, TUI, or another client."
},
{
"id": "assistant-recovery-privacy",
"kind": "fixed",
"title": "Assistant sessions recover more clearly",
"summary": "No-speech feedback, recreated session state, and keyguard privacy now remain intact."
},
{
"id": "relay-auth-boundaries",
"kind": "fixed",
"title": "Protected Relay routes report the right problem",
"summary": "Authentication challenges are no longer presented as outages, while unsafe routes still fail closed."
},
{
"id": "connection-session-readiness",
"kind": "fixed",
"title": "Connections and sessions become ready sooner",
"summary": "Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history."
}
],
"compatibility": [
"Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.",
"The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.",
"Granular Device Control and the system Voice Focus overlay remain available only in the sideload build."
],
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
"sections": []
},
{
"version": "1.13.2",
"title": "Supervised Mode and clearer activity",
+29 -7
View File
@@ -1,9 +1,31 @@
v1.13.2 - Supervised Mode and clearer activity
v1.14.0 - Connections, delegated work, Git, and voice
Supervised Mode
* Protect parent settings with your phone's device authentication.
* Choose access to attachments, Standard voice, generated media, history, actions, and technical details.
* Keep Supervised Chat open when returning from parent settings.
Summary
* Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.
Also improved
* Activity indicators now appear only while Hermes is genuinely working.
Highlights
* Connections recover independently — Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.
* Follow delegated-agent activity — See lifecycle, progress, tool previews, and available read-only child history from the parent chat.
* Work with repositories from Android — Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.
* Steer voice at any time — Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.
Improved
* Release notes stay out of your way — A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings.
* Chat uses one consistent presentation — The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available.
Fixed
* Wake-word detection starts reliably — Compatible native voice components are now packaged for every supported phone architecture.
* The visible Sphere keeps moving smoothly — Foreground animation no longer falls back to a stepped ambient pulse.
* Continuous voice keeps the microphone — The next listening turn waits for barge-in recording to release cleanly.
* New chats keep the selected profile — Fresh drafts no longer reopen an older session or carry a Thread route into another profile.
* Provisional Threads can be removed safely — Local removal and later session promotion no longer risk duplicate rows or server history.
* Clarify keeps custom answers reachable — Other answers, keyboard Send, and expired prompts now behave consistently.
* Browsing no longer interrupts another client — Passive Android observation does not claim a turn owned by Desktop, TUI, or another client.
* Assistant sessions recover more clearly — No-speech feedback, recreated session state, and keyguard privacy now remain intact.
* Protected Relay routes report the right problem — Authentication challenges are no longer presented as outages, while unsafe routes still fail closed.
* Connections and sessions become ready sooner — Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history.
Compatibility
* Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.
* The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.
* Granular Device Control and the system Voice Focus overlay remain available only in the sideload build.
@@ -10,6 +10,16 @@ package com.hermesandroid.relay.data
*/
enum class AttachmentState { LOADING, LOADED, FAILED }
/**
* Gateway tool events do not yet expose an output kind before completion.
* Recognize the upstream built-in plus the profile-tool naming convention used
* for image generators without guessing from generic prompt arguments.
*/
internal fun isImageGenerationToolName(name: String): Boolean {
val normalized = name.trim().lowercase()
return normalized == "image_generate" || normalized.endsWith("_create_image")
}
/**
* How the UI should render a loaded attachment. Derived from the MIME type.
* - [IMAGE] inline image (decode bytes / load URI).
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
apiServerConfigured = apiServerUrl.isNotBlank(),
relayConfigured = relayUrl.isNotBlank(),
)
/**
* Stable owner for an Auto chat before a conversation is opened.
*
* A legacy API-only record has no persisted Dashboard route; the conventional
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
* must not silently turn that compatibility record into a Gateway-owned chat.
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
* standard Chat belongs to Gateway even while that route is signed out or
* temporarily unreachable.
*/
val Connection.automaticChatTransport: SessionTransport
get() {
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
!authenticatedDashboardOrigin.isNullOrBlank()
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
}
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
if (preference == "auto") automaticChatTransport
else SessionTransport.forEndpoint(preference)
@@ -124,7 +124,7 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
val normalized = url.trim().trimEnd('/')
val service = when (label) {
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
"API / sessions", "API fallback" -> "api"
"API / sessions", "API fallback", "Direct API" -> "api"
"Relay tools" -> "relay"
else -> return false
}
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
add(
classifySurfaceSecurity(
label = "API fallback",
label = "Direct API",
url = it,
activeEndpoint = apiEndpoint,
isTailscaleDetected = isTailscaleDetected,
@@ -81,6 +81,24 @@ class SupervisedModeStore private constructor(
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
}
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
internal suspend fun disableAllAndRemoveCredential(
parentCredentialKey: Preferences.Key<String>,
) {
dataStore.edit { preferences ->
val decoded = decode(preferences[KEY_POLICIES])
if (decoded.corrupt || decoded.policies.isEmpty()) {
preferences.remove(KEY_POLICIES)
} else {
val disabled = decoded.policies.mapValues { (_, policy) ->
policy.copy(enabled = false).normalized()
}
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
}
preferences.remove(parentCredentialKey)
}
}
private fun decode(raw: String?): DecodeResult {
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
return try {
@@ -0,0 +1,461 @@
package com.hermesandroid.relay.data
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
/** Availability of the app-specific parent credential. */
enum class SupervisedParentAuthStatus {
Missing,
Configured,
Corrupt,
}
/** Input method selected for the app-specific parent credential. */
@Serializable
enum class SupervisedParentCredentialType {
Legacy,
Pin,
Password,
}
@Serializable
private enum class SupervisedRecoveryFormat {
LegacyCode,
WordPhrase,
}
/** Result of a parent-secret or recovery-phrase verification attempt. */
sealed interface SupervisedParentAuthResult {
data object Success : SupervisedParentAuthResult
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
data object Missing : SupervisedParentAuthResult
data object Corrupt : SupervisedParentAuthResult
}
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
data class SupervisedParentEnrollment(val recoveryPhrase: String)
/** Validation result for a new parent PIN or password. */
data class SupervisedParentSecretValidation(
val valid: Boolean,
val message: String? = null,
)
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
interface SupervisedParentAuthenticator {
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
suspend fun enroll(
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
suspend fun change(
currentSecret: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
suspend fun resetWithRecoveryPhrase(
recoveryPhrase: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
}
/**
* App-specific parent authentication for Supervised Mode.
*
* This store deliberately does not delegate to Android's device credential: a
* child can legitimately own the PIN or biometrics on their Android profile.
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
* secret and recovery phrase are never persisted.
*/
class SupervisedParentAuthStore private constructor(
private val dataStore: DataStore<Preferences>,
private val iterations: Int,
private val minimumAcceptedIterations: Int,
private val random: SecureRandom,
private val nowMillis: () -> Long,
) : SupervisedParentAuthenticator {
constructor(context: Context) : this(
dataStore = context.applicationContext.relayDataStore,
iterations = DEFAULT_PBKDF2_ITERATIONS,
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
random = SecureRandom(),
nowMillis = System::currentTimeMillis,
)
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
decode(preferences[KEY_RECORD]).status
}
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
decode(preferences[KEY_RECORD]).record?.credentialType
}
override suspend fun enroll(
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
}
runCatching { enrollLocked(newSecret, credentialType) }
}
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
verifyLocked(secret, AuthTarget.ParentSecret)
}
override suspend fun change(
currentSecret: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
else -> Result.failure(ParentAuthenticationException(verified))
}
}
override suspend fun resetWithRecoveryPhrase(
recoveryPhrase: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
val record = decode(dataStore.data.first()[KEY_RECORD]).record
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
try {
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
else -> Result.failure(ParentAuthenticationException(verified))
}
} finally {
normalizedRecovery.fill('\u0000')
}
}
/**
* Authenticated escape hatch used by the parent controls.
*
* The app-global credential cannot be removed while leaving any supervised
* policy enabled. Every policy is disabled, but its configuration is retained,
* in the same transaction that removes the credential.
*/
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
runCatching {
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
Unit
}
}
private suspend fun enrollLocked(
secret: CharArray,
credentialType: SupervisedParentCredentialType,
): SupervisedParentEnrollment {
require(credentialType != SupervisedParentCredentialType.Legacy)
val recoveryChars = generateRecoveryPhrase().toCharArray()
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
var parentVerifier = ByteArray(0)
var recoveryVerifier = ByteArray(0)
try {
parentVerifier = derive(secret, parentSalt, iterations)
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
val record = PersistedParentAuth(
iterations = iterations,
parentSalt = encode(parentSalt),
parentVerifier = encode(parentVerifier),
recoverySalt = encode(recoverySalt),
recoveryVerifier = encode(recoveryVerifier),
credentialType = credentialType,
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
)
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
return SupervisedParentEnrollment(recoveryChars.concatToString())
} finally {
recoveryChars.fill('\u0000')
parentSalt.fill(0)
recoverySalt.fill(0)
parentVerifier.fill(0)
recoveryVerifier.fill(0)
}
}
private suspend fun verifyLocked(
candidate: CharArray,
target: AuthTarget,
): SupervisedParentAuthResult {
val decoded = decode(dataStore.data.first()[KEY_RECORD])
val record = decoded.record ?: return when (decoded.status) {
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
else -> SupervisedParentAuthResult.Corrupt
}
val now = nowMillis()
if (record.blockedUntilEpochMillis > now) {
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
}
val saltText = when (target) {
AuthTarget.ParentSecret -> record.parentSalt
AuthTarget.RecoveryCode -> record.recoverySalt
}
val verifierText = when (target) {
AuthTarget.ParentSecret -> record.parentVerifier
AuthTarget.RecoveryCode -> record.recoveryVerifier
}
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
val actual = try {
derive(candidate, salt, record.iterations)
} catch (error: Exception) {
Log.w(TAG, "Unable to derive supervised parent verifier", error)
return SupervisedParentAuthResult.Corrupt
} finally {
salt.fill(0)
}
val matches = try {
MessageDigest.isEqual(expected, actual)
} finally {
expected.fill(0)
actual.fill(0)
}
if (matches) {
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
}
return SupervisedParentAuthResult.Success
}
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
val delayMillis = backoffMillis(failures)
save(
record.copy(
failedAttempts = failures,
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
),
)
return if (delayMillis == 0L) {
SupervisedParentAuthResult.Invalid(
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
)
} else {
SupervisedParentAuthResult.Throttled(delayMillis)
}
}
private suspend fun save(record: PersistedParentAuth) {
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
}
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
withContext(Dispatchers.Default) {
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
try {
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
}
private fun decode(raw: String?): DecodedRecord {
if (raw.isNullOrBlank()) {
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
}
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
.getOrElse {
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
}
val valid = record.version == RECORD_VERSION &&
record.algorithm == KDF_ALGORITHM &&
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
record.blockedUntilEpochMillis >= 0
return if (valid) {
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
} else {
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
}
}
private fun generateRecoveryPhrase(): String {
val available = RECOVERY_WORDS.toMutableList()
val selected = buildList(RECOVERY_WORD_COUNT) {
repeat(RECOVERY_WORD_COUNT) {
add(available.removeAt(random.nextInt(available.size)))
}
}
return selected.joinToString("-")
}
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
private fun decodeBytes(value: String): ByteArray? =
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
private fun backoffMillis(failures: Int): Long = when (failures) {
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
FAILURES_BEFORE_BACKOFF -> 30_000L
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
else -> MAX_BACKOFF_MILLIS
}
@Serializable
private data class PersistedParentAuth(
val version: Int = RECORD_VERSION,
val algorithm: String = KDF_ALGORITHM,
val iterations: Int,
val parentSalt: String,
val parentVerifier: String,
val recoverySalt: String,
val recoveryVerifier: String,
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
val failedAttempts: Int = 0,
val blockedUntilEpochMillis: Long = 0L,
)
private data class DecodedRecord(
val status: SupervisedParentAuthStatus,
val record: PersistedParentAuth?,
)
private enum class AuthTarget { ParentSecret, RecoveryCode }
class ParentAuthenticationException(
val authResult: SupervisedParentAuthResult,
) : IllegalStateException("Parent authentication failed: $authResult")
companion object {
private const val TAG = "SupervisedParentAuth"
private const val RECORD_VERSION = 1
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
private const val MIN_ACCEPTED_ITERATIONS = 100_000
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
private const val SALT_BYTES = 16
private const val KEY_BITS = 256
private const val FAILURES_BEFORE_BACKOFF = 5
private const val MAX_TRACKED_FAILURES = 9
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
private const val RECOVERY_WORD_COUNT = 6
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
private val processMutex = Mutex()
fun validateNewSecret(
secret: CharArray,
credentialType: SupervisedParentCredentialType,
): SupervisedParentSecretValidation {
if (secret.size > 64) {
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
}
if (credentialType == SupervisedParentCredentialType.Pin) {
return if (secret.size == 6 && secret.all(Char::isDigit)) {
SupervisedParentSecretValidation(true)
} else {
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
}
}
return if (
credentialType == SupervisedParentCredentialType.Password &&
secret.size >= 8 && secret.any { !it.isWhitespace() }
) {
SupervisedParentSecretValidation(true)
} else {
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
}
}
private fun normalizeRecoveryPhrase(
value: CharArray,
format: SupervisedRecoveryFormat,
): CharArray = when (format) {
SupervisedRecoveryFormat.LegacyCode -> value
.filterNot { it == '-' || it.isWhitespace() }
.joinToString("")
.uppercase()
.toCharArray()
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
.trim()
.lowercase()
.split(Regex("[-\\s]+"))
.filter(String::isNotBlank)
.joinToString("-")
.toCharArray()
}
private val RECOVERY_WORDS = listOf(
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
)
internal fun forTesting(
dataStore: DataStore<Preferences>,
iterations: Int = MIN_ACCEPTED_ITERATIONS,
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
random: SecureRandom = SecureRandom(),
nowMillis: () -> Long = System::currentTimeMillis,
): SupervisedParentAuthStore = SupervisedParentAuthStore(
dataStore = dataStore,
iterations = iterations,
minimumAcceptedIterations = minimumAcceptedIterations,
random = random,
nowMillis = nowMillis,
)
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
}
}
@@ -13,6 +13,7 @@ import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.MoaReference
import com.hermesandroid.relay.data.RealtimeTurnTrace
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.data.VoiceIntentTrace
import com.hermesandroid.relay.network.shared.LocalDispatchResult
import com.hermesandroid.relay.network.upstream.models.MessageItem
@@ -1499,11 +1500,13 @@ class ChatHandler {
// Run the media marker parser on assistant content; strip matched
// lines and queue hits for post-assignment dispatch.
val messageMediaHits = mutableListOf<Pair<String, MediaMarkerHit>>()
val afterMedia = if (role == MessageRole.ASSISTANT && persistedImages.cleanedText.isNotEmpty()) {
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, pendingMediaHits)
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, messageMediaHits)
} else {
persistedImages.cleanedText
}
pendingMediaHits += messageMediaHits
// Cards are synchronous (no async fetch) so we attach them
// straight onto the reconstructed ChatMessage and strip their
@@ -1537,15 +1540,25 @@ class ChatHandler {
val prior = priorById[messageId]
// Outbound attachments: prefer an id-match (covers any future
// user-message id reconciliation), else fall back to the
// content-keyed queue. Inbound attachments are intentionally
// excluded — they come back via the marker re-dispatch.
// content-keyed queue. Inbound attachments normally come back via
// marker re-dispatch. One narrow exception retains a completed
// image_generate result when the immediate post-turn history read
// still lacks its MEDIA marker; otherwise the rendered image
// disappears during the persistence-lag window.
val carriedAttachments = run {
val persistedImagePaths = persistedImages.paths.toHashSet()
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
isImageGenerationToolName(tool.name) &&
tool.isComplete && tool.success != false
}
val byId = prior?.attachments.orEmpty().filter { attachment ->
attachment.relayToken == null ||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
(
role == MessageRole.USER &&
attachment.relayToken in persistedImagePaths
role == MessageRole.ASSISTANT &&
priorGeneratedImage &&
attachment.isImage &&
messageMediaHits.isEmpty()
)
}
when {
@@ -2436,14 +2436,11 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
java.util.IdentityHashMap<Throwable, Boolean>(),
)
while (current != null && seen.add(current)) {
if (
current is DashboardHttpException &&
current.statusCode == 401 &&
(
current.message.orEmpty().contains("no_cookie", ignoreCase = true) ||
current.message.orEmpty().contains("unauthenticated", ignoreCase = true)
)
) {
// Every 401 from an authenticated Dashboard route means the saved
// browser/native session can no longer authorize this request. Older
// gateways used `no_cookie`/`unauthenticated`; current builds may return
// reason codes such as `session_expired`, or no structured body at all.
if (current is DashboardHttpException && current.statusCode == 401) {
return true
}
current = current.cause
@@ -119,6 +119,8 @@ class GatewayChatClient(
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
/** Test seam — compaction idle lease. Production keeps [COMPACTING_TIMEOUT_MS]. */
private val compactingTimeoutMs: Long = COMPACTING_TIMEOUT_MS,
/** Random source for ordinary reconnect full-jitter. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
) : GatewayProfileEditorClient {
@@ -159,6 +161,19 @@ class GatewayChatClient(
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_000L
/**
* Server-side context compaction summarizes the transcript through a
* (possibly slow) model with NO deltas or tool events flowing until it
* finishes — near the context ceiling that silence routinely exceeds
* [TURN_TIMEOUT_MS], so the idle watchdog would `session.interrupt` a
* healthy compression, roll back its work, and retrigger on the next
* prompt forever. A `status.update` event with kind `compacting`
* (emitted at compaction start, and periodically by newer gateways)
* arms this longer leash instead; any regular event rearms
* [TURN_TIMEOUT_MS].
*/
private const val COMPACTING_TIMEOUT_MS = 600_000L
private const val RPC_TIMEOUT_MS = 15_000L
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
@@ -263,7 +278,7 @@ class GatewayChatClient(
.newBuilder()
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
// reached over Tailscale (DERP cold start) can take longer to complete
// the WS upgrade. A failed connect drops chat to the SSE fallback and a
// the WS upgrade. A failed connect leaves Android on its Gateway owner and a
// 5s cooldown, so give the first remote handshake room.
.connectTimeout(20, TimeUnit.SECONDS)
.pingInterval(30, TimeUnit.SECONDS)
@@ -758,7 +773,7 @@ class GatewayChatClient(
// Once this turn's own events are flowing (or it already
// finished), the prompt provably reached the server — a
// slow, lost, or socket-severed ack must NOT preflight-fail
// into the SSE fallback, which would resubmit the same
// into a second transport, which would resubmit the same
// prompt as a duplicate turn. Recovery belongs to the
// stream: the watchdog and mid-turn rejoin own it.
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
@@ -4226,10 +4241,12 @@ class GatewayChatClient(
// ------------------------------------------------------------------
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
eventType == "status.update" &&
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
else -> turnIdleTimeoutMs
}
@@ -4348,7 +4365,7 @@ class GatewayChatClient(
// Reset on every event — long tool runs keep the turn alive.
// Ask requests block with no further events, so they arm with
// their own (longer) duration via watchdogTimeoutFor.
armWatchdog(watchdogTimeoutFor(type))
armWatchdog(watchdogTimeoutFor(type, payload))
// Queue this immediately before the terminal callbacks. Both are
// marshalled through the same dispatcher, preserving callback order
// even when the WebSocket reader and reconnect coroutine differ.
@@ -4707,7 +4724,7 @@ data class GatewayAttachment(
val sizeBytes: Long? = null,
)
/** Connect/auth/submit failed before the turn started — safe to fall back to SSE. */
/** Connect/auth/submit failed before the turn started; the caller retains transport ownership. */
internal class GatewayPreflightException(message: String) : Exception(message)
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
* is unit-testable without an AndroidViewModel. ConnectionViewModel
* delegates here with its live state.
*
* Manual picks pass through untouched (ChatViewModel handles per-turn
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
* gateway while the dashboard probe is unresolved or ready. A capability-
* preferred SSE fallback is selected only after a definitive unavailable,
* unsupported, or sign-in-required verdict.
* Manual picks pass through untouched. "auto" follows the saved connection's
* stable owner: Dashboard/Gateway for a standard connection, or the
* capability-preferred SSE surface for a true API-only compatibility record.
* Live reachability and sign-in state never change the owner of an open chat.
*/
fun resolveStreamingEndpointPreference(
preference: String,
gateway: GatewayAvailability,
capabilities: ServerCapabilities,
gatewayOwned: Boolean = true,
): String = when (preference) {
"sessions", "completions", "runs", "gateway" -> preference
else -> if (
gateway == GatewayAvailability.Ready ||
gateway == GatewayAvailability.Unknown
) {
"gateway"
} else {
capabilities.preferredChatEndpoint()
}
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
}
/**
@@ -209,6 +209,7 @@ internal class HermesRuntimeBinder(
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
connection.loadProfileScopedMessages(profileName, sessionId, mode)
}
chat.setDashboardSignInRequiredHandler(connection::probeNow)
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
chat.profileSessionDeleter = connection::deleteSession
chat.profileSessionRenamer = connection::renameSession
@@ -261,6 +262,11 @@ internal class HermesRuntimeBinder(
jobs += runtime.coroutineScope.launch {
chat.isStreaming.collect(connection::setChatStreaming)
}
jobs += runtime.coroutineScope.launch {
chat.conversationBinding.collect { binding ->
connection.setActiveConversationTransport(binding.transport)
}
}
jobs += runtime.coroutineScope.launch {
combine(
connection.activeConnectionId,
@@ -136,6 +136,8 @@ import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
import com.hermesandroid.relay.data.BuildFlavor
import com.hermesandroid.relay.data.CandidateBuild
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.SessionTransport
import com.hermesandroid.relay.data.chatTransportForPreference
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.FeatureFlags
import com.hermesandroid.relay.data.SupervisedModePolicy
@@ -144,6 +146,7 @@ import com.hermesandroid.relay.data.VoicePresentationMode
import com.hermesandroid.relay.data.capabilities
import com.hermesandroid.relay.data.displayLabel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -282,6 +285,8 @@ internal fun resolveAppChatRuntimeStatus(
connection: Connection?,
gatewayAvailability: GatewayAvailability,
apiHealth: ConnectionViewModel.HealthStatus,
streamingEndpoint: String = "auto",
conversationOwner: SessionTransport? = null,
): ChatRuntimeStatus {
val capabilities = connection?.capabilities
val gateway = when {
@@ -297,7 +302,11 @@ internal fun resolveAppChatRuntimeStatus(
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
else -> ChatTransportReadiness.Unavailable
}
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
val owner = when (conversationOwner ?: connection?.chatTransportForPreference(streamingEndpoint)) {
SessionTransport.SSE -> ChatTransportPath.ApiSse
else -> ChatTransportPath.Gateway
}
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api, owner = owner)
}
internal fun shouldSettleStartupUnreachable(
@@ -359,7 +368,7 @@ internal fun resolveFooterRouteCandidate(
*
* Endpoint roles are operator and wire metadata, so an internal role such as
* `authenticated_dashboard` must never leak into this constrained surface.
* Gateway labels describe how the Dashboard is reached; API fallback keeps
* Gateway labels describe how the Dashboard is reached; Direct API keeps
* the route's ordinary transport label.
*/
internal fun resolveFooterRouteLabel(
@@ -738,6 +747,10 @@ fun RelayApp() {
val pendingAddConnectionJobs = remember {
mutableMapOf<String, kotlinx.coroutines.Job>()
}
var pendingAddConnectionTargetId by rememberSaveable { mutableStateOf<String?>(null) }
val pendingAddConnectionAbortJobs = remember {
mutableMapOf<String, kotlinx.coroutines.Job>()
}
val prepareAddConnection: (String, Boolean) -> Unit = { id, retryRequested ->
val existingJob = pendingAddConnectionJobs[id]
if (shouldStartPairPreparation(existingJob?.isActive == true, retryRequested)) {
@@ -758,6 +771,25 @@ fun RelayApp() {
job.start()
}
}
val abortAddConnection: (String) -> kotlinx.coroutines.Job = { id ->
pendingAddConnectionAbortJobs[id] ?: connectionSwitchScope.launch {
try {
pendingAddConnectionJobs.remove(id)?.cancelAndJoin()
connectionViewModel.discardPlaceholderConnection(id)
} finally {
if (pendingAddConnectionTargetId == id) {
pendingAddConnectionTargetId = null
}
}
}.also { job ->
pendingAddConnectionAbortJobs[id] = job
job.invokeOnCompletion {
if (pendingAddConnectionAbortJobs[id] === job) {
pendingAddConnectionAbortJobs.remove(id)
}
}
}
}
// One-time init: the terminal channel ViewModel registers with the shared
// multiplexer and observes the relay connection state so it can attach/
@@ -1351,6 +1383,9 @@ fun RelayApp() {
currentRoute = currentRoute,
)
if (redirect) {
pendingAddConnectionTargetId?.let { targetId ->
abortAddConnection(targetId).join()
}
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
@@ -1566,6 +1601,7 @@ fun RelayApp() {
// evidence alone left a window where the reveal showed the CTA for
// the few hundred ms until the client-based health verdict landed.
val chatReady by connectionViewModel.chatReady.collectAsState()
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
var startupGateMinElapsed by remember { mutableStateOf(false) }
var startupGateTimedOut by remember { mutableStateOf(false) }
var startupGateReleased by remember { mutableStateOf(false) }
@@ -1592,6 +1628,8 @@ fun RelayApp() {
connection = activeConnection,
gatewayAvailability = gatewayAvailability,
apiHealth = apiHealth,
streamingEndpoint = streamingEndpoint,
conversationOwner = conversationOwner,
)
// A Dashboard/Gateway-only connection is a complete standard Hermes
// connection. Startup readiness follows the same transport-neutral
@@ -2098,7 +2136,9 @@ fun RelayApp() {
?: stringResource(R.string.status_no_route),
)
val transportStatus = resolveChatTransportStatus(
streamingEndpoint = streamingEndpoint,
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
streamingEndpoint,
),
gatewayAvailability = gatewayAvailability,
serverCapabilities = serverCapabilities,
)
@@ -2113,10 +2153,20 @@ fun RelayApp() {
?: AgentDisplay.displayModelName(serverModelName)
?: stringResource(R.string.status_model_pending)
val footerModelLabel = compactFooterModelLabel(modelLabel)
val openConnections = {
navController.navigate(Screen.ConnectionsSettings.route) {
launchSingleTop = true
val openConnections: (() -> Unit)? = if (
isSupervisedRouteContentAllowed(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
currentRoute = Screen.ConnectionsSettings.route,
)
) {
{
navController.navigate(Screen.ConnectionsSettings.route) {
launchSingleTop = true
}
}
} else {
null
}
RelayStatusStrip(
leadingBadge = {
@@ -2930,7 +2980,12 @@ fun RelayApp() {
}
composable(Screen.AdvancedSettings.route) {
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
LaunchedEffect(Unit) { navController.popBackStack() }
LaunchedEffect(Unit) {
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
}
}
} else {
AdvancedSettingsScreen(
supervisedPolicy = supervisedPolicy,
@@ -2961,7 +3016,12 @@ fun RelayApp() {
}
composable(Screen.SupervisedControls.route) {
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
LaunchedEffect(Unit) { navController.popBackStack() }
LaunchedEffect(Unit) {
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
}
}
} else {
SupervisedControlsScreen(
connectionViewModel = connectionViewModel,
@@ -3203,16 +3263,34 @@ fun RelayApp() {
addConnectionEnabled = mayStartAddConnection(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
activeTargetId = pendingAddConnectionTargetId,
),
onAddConnection = {
val id = java.util.UUID.randomUUID().toString()
onAddConnection = addConnection@{
val liveConnectionId = connectionViewModel.activeConnectionId.value
val livePolicyState = supervisedPolicyState.value
?.takeIf { (ownerId, _) -> ownerId == liveConnectionId }
val livePolicy = when {
liveConnectionId == null -> SupervisedModePolicy()
livePolicyState != null -> livePolicyState.second
else -> return@addConnection
}
val liveRoute = navController.currentDestination?.route
val liveParentAccess = parentAccessUnlocked &&
!shouldRelockParentAccess(
supervisedEnabled = livePolicy.enabled,
parentAccessUnlocked = parentAccessUnlocked,
route = liveRoute,
)
runAddConnectionAction(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
navigateToPair = {
supervisedEnabled = livePolicy.enabled,
parentAccessUnlocked = liveParentAccess,
activeTargetId = pendingAddConnectionTargetId,
allocateTarget = { java.util.UUID.randomUUID().toString() },
recordTarget = { id -> pendingAddConnectionTargetId = id },
navigateToPair = { id ->
navController.navigate(Screen.Pair.route(connectionId = id))
},
prepareConnection = { prepareAddConnection(id, false) },
prepareConnection = { id -> prepareAddConnection(id, false) },
)
},
onBack = { navController.popBackStack() },
@@ -3356,9 +3434,15 @@ fun RelayApp() {
if (connectionIdArg != null && pairDraftId == connectionIdArg) {
connectionSwitchScope.launch {
connectionViewModel.commitConnectionDraft(connectionIdArg)
if (pendingAddConnectionTargetId == connectionIdArg) {
pendingAddConnectionTargetId = null
}
navController.popBackStack()
}
} else {
if (pendingAddConnectionTargetId == connectionIdArg) {
pendingAddConnectionTargetId = null
}
navController.popBackStack()
}
},
@@ -3378,6 +3462,9 @@ fun RelayApp() {
runCatching {
connectionViewModel.commitConnectionDraft(targetId)
}.onSuccess {
if (pendingAddConnectionTargetId == targetId) {
pendingAddConnectionTargetId = null
}
android.util.Log.i(
"GatewayPairFlow",
"Opening Dashboard sign-in for staged gateway",
@@ -3414,14 +3501,12 @@ fun RelayApp() {
// never got a pairedAt stamp.
if (connectionIdArg != null) {
connectionSwitchScope.launch {
// If Back wins the race with background
// preparation, wait until the placeholder
// exists before attempting to discard it.
pendingAddConnectionJobs.remove(connectionIdArg)?.join()
connectionViewModel.discardPlaceholderConnection(connectionIdArg)
abortAddConnection(connectionIdArg).join()
navController.popBackStack()
}
} else {
navController.popBackStack()
}
navController.popBackStack()
},
)
}
@@ -15,18 +15,24 @@ internal fun isSupervisedRouteAllowed(route: String?, parentAccessUnlocked: Bool
internal fun mayStartAddConnection(
supervisedEnabled: Boolean,
parentAccessUnlocked: Boolean,
): Boolean = !supervisedEnabled || parentAccessUnlocked
activeTargetId: String? = null,
): Boolean = activeTargetId == null && (!supervisedEnabled || parentAccessUnlocked)
internal inline fun runAddConnectionAction(
supervisedEnabled: Boolean,
parentAccessUnlocked: Boolean,
navigateToPair: () -> Unit,
prepareConnection: () -> Unit,
): Boolean {
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked)) return false
navigateToPair()
prepareConnection()
return true
activeTargetId: String?,
allocateTarget: () -> String,
recordTarget: (String) -> Unit,
navigateToPair: (String) -> Unit,
prepareConnection: (String) -> Unit,
): String? {
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked, activeTargetId)) return null
val targetId = allocateTarget()
recordTarget(targetId)
navigateToPair(targetId)
prepareConnection(targetId)
return targetId
}
/** Do not inspect or mutate a NavController until its first destination exists. */
@@ -132,12 +138,10 @@ internal fun sanitizeSupervisedChatRouteArgs(
}
}
/** A disabled policy may become active only after an enrolled credential succeeds. */
/** A disabled policy may become active only after the app-specific parent credential succeeds. */
internal fun mayEnableSupervisedMode(
policy: SupervisedModePolicy,
deviceSecure: Boolean,
deviceCredentialConfirmed: Boolean,
parentCredentialConfirmed: Boolean,
): Boolean = !policy.enabled &&
policy.isConfigured &&
deviceSecure &&
deviceCredentialConfirmed
parentCredentialConfirmed
@@ -613,7 +613,7 @@ private fun CapabilityRow(
/**
* Advanced compatibility and override content:
* - optional direct API fallback URL/key
* - optional Direct API URL/key
* - explicit direct Relay endpoint override/test
* - allow-insecure-connections development toggle
*
@@ -21,9 +21,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
enum class ChatTransportTier(val endpointId: String, val label: String) {
Gateway("gateway", "⚡ Gateway"),
Sessions("sessions", "📡 Sessions"),
Completions("completions", "Completions"),
Runs("runs", "Runs"),
Sessions("sessions", "Direct API"),
Completions("completions", "Direct API"),
Runs("runs", "Direct API"),
Offline("offline", "offline"),
}
@@ -67,18 +67,6 @@ fun resolveChatTransportStatus(
detail = "No reachable Hermes chat transport is available.",
)
fun sseFallback(gatewayReason: String): ChatTransportStatus {
if (!serverCapabilities.healthy) return offline(gatewayReason)
val tier = preferredAvailableSseTier(serverCapabilities)
?: return offline(gatewayReason)
return ChatTransportStatus(
tier = tier,
tone = ChatTransportTone.Fallback,
reason = "$gatewayReason → ${tier.plainName()}",
detail = "${tier.detailText()} Using this as the fallback while Gateway is unavailable.",
)
}
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
if (!serverCapabilities.healthy) return offline()
return if (supported) {
@@ -94,23 +82,17 @@ fun resolveChatTransportStatus(
}
return when (preference) {
"auto" -> when {
"auto", "gateway" -> when {
gatewayReady -> ChatTransportStatus(
tier = ChatTransportTier.Gateway,
tone = ChatTransportTone.Active,
reason = "auto → Gateway (best)",
reason = "Gateway connected",
detail = ChatTransportTier.Gateway.detailText(),
)
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
}
"gateway" -> when {
gatewayReady -> ChatTransportStatus(
tier = ChatTransportTier.Gateway,
tone = ChatTransportTone.Active,
reason = "Gateway selected",
detail = ChatTransportTier.Gateway.detailText(),
else -> unavailable(
ChatTransportTier.Gateway,
gatewayFallbackReason(gatewayAvailability),
)
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
}
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
@@ -119,42 +101,34 @@ fun resolveChatTransportStatus(
}
}
private fun preferredAvailableSseTier(capabilities: ServerCapabilities): ChatTransportTier? =
when {
capabilities.sessionsChatStream -> ChatTransportTier.Sessions
capabilities.portable -> ChatTransportTier.Completions
capabilities.runs -> ChatTransportTier.Runs
else -> null
}
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
when (availability) {
GatewayAvailability.SignInRequired -> "gateway sign-in required"
GatewayAvailability.Unreachable -> "gateway unavailable"
GatewayAvailability.Unsupported -> "gateway unsupported"
GatewayAvailability.Unknown -> "checking gateway"
GatewayAvailability.Ready -> "gateway ready"
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
GatewayAvailability.Unreachable -> "Gateway unavailable"
GatewayAvailability.Unsupported -> "Gateway unsupported"
GatewayAvailability.Unknown -> "Checking Gateway"
GatewayAvailability.Ready -> "Gateway ready"
}
private fun ChatTransportTier.plainName(): String =
when (this) {
ChatTransportTier.Gateway -> "Gateway"
ChatTransportTier.Sessions -> "Sessions"
ChatTransportTier.Completions -> "Completions"
ChatTransportTier.Runs -> "Runs"
ChatTransportTier.Sessions -> "Direct API"
ChatTransportTier.Completions -> "Direct API"
ChatTransportTier.Runs -> "Direct API"
ChatTransportTier.Offline -> "offline"
}
private fun ChatTransportTier.detailText(): String =
when (this) {
ChatTransportTier.Gateway ->
"Gateway uses the dashboard WebSocket /api/ws for live thinking and rich tool events."
"Hermes Chat uses the signed-in Dashboard connection."
ChatTransportTier.Sessions ->
"Sessions uses /api/sessions/{id}/chat/stream with server-side session history."
"Direct API compatibility chat with server-side session history."
ChatTransportTier.Completions ->
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
"Direct API compatibility chat."
ChatTransportTier.Runs ->
"Runs uses /v1/runs plus streamed run events."
"Direct API compatibility chat with streamed run events."
ChatTransportTier.Offline ->
"No chat transport is reachable."
}
@@ -132,7 +132,7 @@ import java.net.URI
* Settings → Gateways. Hermes setup starts with the one Dashboard address
* the phone can open, probes public `/api/status`, and lets advertised
* capabilities select authentication. A separate public sign-in URL is never
* universally required. API fallback, Relay pairing, and extra LAN/Tailscale
* universally required. Direct API, Relay pairing, and extra LAN/Tailscale
* routes remain explicit advanced paths.
*
* Steps:
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
val label = when (surface) {
EndpointSurface.Standard,
EndpointSurface.Dashboard -> "Dashboard & Gateway"
EndpointSurface.Api -> "API fallback"
EndpointSurface.Api -> "Direct API"
EndpointSurface.Relay -> "Relay tools"
}
val securityVerdict = classifySurfaceSecurity(
@@ -57,6 +57,7 @@ import androidx.compose.ui.unit.IntSize
import androidx.annotation.RequiresApi
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import java.util.Locale
@@ -65,7 +66,6 @@ import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.sin
private const val IMAGE_GENERATION_TOOL = "image_generate"
private const val GRID_COLUMNS = 42
private const val GRID_ROWS = 24
private const val DEFAULT_ANIMATION_DURATION_MS = 4_800
@@ -134,11 +134,11 @@ internal fun resolveImageGenerationVisualStyle(
}
internal fun ToolCall.showsImageGenerationPlaceholder(): Boolean =
!isComplete && name.trim().lowercase() == IMAGE_GENERATION_TOOL
!isComplete && isImageGenerationToolName(name)
internal fun imageGenerationStartedAt(toolCalls: List<ToolCall>): Long? =
toolCalls.lastOrNull {
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
isImageGenerationToolName(it.name)
}?.startedAt
internal fun formatGenerationDuration(elapsedMillis: Long): String =
@@ -155,7 +155,7 @@ internal fun shouldShowImageGenerationPlaceholder(
hasMediaResult: Boolean,
): Boolean {
val imageCalls = toolCalls.filter {
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
isImageGenerationToolName(it.name)
}
if (imageCalls.any { !it.isComplete }) return true
return !hasMediaResult &&
@@ -83,6 +83,7 @@ import com.hermesandroid.relay.data.HermesCardAction
import com.hermesandroid.relay.data.MediaSettingsRepository
import com.hermesandroid.relay.data.MessageDeliveryStatus
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.data.parseChatQuotedPrompt
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
@@ -292,9 +293,7 @@ fun MessageBubble(
append(streamingStatusLabel ?: visibleMessageContent.take(100))
}
val hasImageGenerationCall = remember(message.toolCalls) {
message.toolCalls.any {
it.name.trim().lowercase() == "image_generate"
}
message.toolCalls.any { isImageGenerationToolName(it.name) }
}
val imageGenerationStartMillis = remember(message.toolCalls) {
imageGenerationStartedAt(message.toolCalls)
@@ -25,6 +25,8 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.res.stringResource
import com.hermesandroid.relay.R
import com.hermesandroid.relay.ui.theme.RelayRefresh
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
@@ -41,7 +43,7 @@ fun RelayStatusStrip(
/** Optional security marker rendered just before the route label. */
securityGlyph: (@Composable () -> Unit)? = null,
/**
* When true, the strip shows an amber "Reconnecting…" cue in place of the
* When true, the strip shows an amber "Relay reconnecting" cue in place of the
* route label. This is where a **routine** in-progress relay reconnect
* surfaces — the top chrome stays empty so chat content never shifts.
*/
@@ -108,7 +110,7 @@ fun RelayStatusStrip(
}
/**
* Amber "· Reconnecting…" cue with a softly pulsing dot. This is the *only*
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
* surface for a routine in-progress relay reconnect — the top of the app stays
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
@@ -132,7 +134,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
.background(RelayRefresh.Amber),
)
Text(
text = "Reconnecting…",
text = stringResource(R.string.settings_relay_reconnecting),
style = relayMetadataStyle(),
color = RelayRefresh.Amber,
maxLines = 1,
@@ -401,7 +401,7 @@ internal fun SessionPathDetails(
* Vertical "transport path" ladder, basic → best:
* Completions → Runs → Sessions → Gateway. The active tier is filled +
* highlighted; tiers the server doesn't expose render muted; the resolver's
* reason ("auto → Gateway (best)" / "gateway unavailable → Sessions") is shown
* owner/readiness reason ("Gateway connected" / "Gateway unavailable") is shown
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
* the drawer and the badge can never disagree.
*/
@@ -43,6 +43,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
private val TOOL_ACTIVITY_PET_ROUTES = setOf("chat")
@@ -101,7 +102,8 @@ internal fun ToolCall.requiresStandaloneToolSurface(): Boolean {
!error.isNullOrBlank() ||
outputRisk != null ||
normalized in FILE_EDIT_TOOLS ||
normalized in ATTENTION_TOOLS
normalized in ATTENTION_TOOLS ||
isImageGenerationToolName(name)
}
internal data class ToolActivityCounts(
@@ -294,7 +294,55 @@ fun VersionNotesBlock(
) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
val highlight = entry.highlight
if (highlight == null) {
if (entry.changes.isNotEmpty()) {
if (showVersionLine) {
Text(
text = entry.versionLine(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
entry.title?.takeIf { it.isNotBlank() }?.let { title ->
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
}
}
entry.summary?.takeIf { it.isNotBlank() }?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
)
}
val highlights = entry.highlightedChanges()
if (highlights.isNotEmpty()) {
ReleaseSectionTitle(stringResource(R.string.changelog_highlights))
ReleaseChangeList(highlights)
}
listOf(
CHANGE_KIND_ADDED to R.string.changelog_added,
CHANGE_KIND_IMPROVED to R.string.changelog_improved,
CHANGE_KIND_FIXED to R.string.changelog_fixed,
).forEach { (kind, label) ->
val changes = entry.remainingChangesOfKind(kind)
if (changes.isNotEmpty()) {
ReleaseSectionTitle(stringResource(label))
ReleaseChangeList(changes)
}
}
if (entry.compatibility.isNotEmpty()) {
ReleaseSectionTitle(stringResource(R.string.changelog_compatibility))
VersionNotesBody(
listOf(WhatsNewGroup(header = null, bullets = entry.compatibility)),
)
}
} else if (highlight == null) {
if (showVersionLine) {
Text(
text = entry.subtitle(),
@@ -340,6 +388,47 @@ fun VersionNotesBlock(
}
}
@Composable
private fun ReleaseSectionTitle(title: String) {
Text(
text = title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(top = 6.dp),
)
}
@Composable
private fun ColumnScope.ReleaseChangeList(changes: List<ChangelogChange>) {
changes.forEach { change ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "•",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = change.title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
change.summary?.takeIf { it.isNotBlank() }?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
// ──────────────────────────────────────────────────────────────────────────
// Structured changelog model + loader (kotlinx.serialization).
// ──────────────────────────────────────────────────────────────────────────
@@ -363,16 +452,37 @@ data class ChangelogHighlight(
@Serializable
data class ChangelogToastDigest(
val additionalFeatureCount: Int = 0,
val improvementCount: Int = 0,
val fixCount: Int = 0,
val preview: List<String> = emptyList(),
)
const val CHANGE_KIND_ADDED = "added"
const val CHANGE_KIND_IMPROVED = "improved"
const val CHANGE_KIND_FIXED = "fixed"
/** One complete, user-visible change in a release. */
@Serializable
data class ChangelogChange(
val id: String,
val kind: String,
val title: String,
val summary: String? = null,
val highlight: Boolean = false,
) {
fun fallbackText(): String =
summary?.takeIf { it.isNotBlank() }?.let { "$title — $it" } ?: title
}
/** A single released version's user-facing notes. */
@Serializable
data class ChangelogVersion(
val version: String,
val title: String? = null,
val date: String? = null,
val summary: String? = null,
val changes: List<ChangelogChange> = emptyList(),
val compatibility: List<String> = emptyList(),
val highlight: ChangelogHighlight? = null,
val improvements: List<String> = emptyList(),
val toastDigest: ChangelogToastDigest? = null,
@@ -393,8 +503,48 @@ data class ChangelogVersion(
return "v$version$datePart"
}
fun highlightedChanges(): List<ChangelogChange> = changes.filter { it.highlight }
fun remainingChanges(): List<ChangelogChange> = changes.filterNot { it.highlight }
fun remainingChangesOfKind(kind: String): List<ChangelogChange> =
remainingChanges().filter { it.kind == kind }
/** Derive compact toast metadata from the same changes the expanded view renders. */
fun resolvedToastDigest(): ChangelogToastDigest? {
if (changes.isEmpty()) return toastDigest
val remaining = remainingChanges()
if (remaining.isEmpty()) return null
return ChangelogToastDigest(
additionalFeatureCount = remaining.count { it.kind == CHANGE_KIND_ADDED },
improvementCount = remaining.count { it.kind == CHANGE_KIND_IMPROVED },
fixCount = remaining.count { it.kind == CHANGE_KIND_FIXED },
preview = remaining.take(2).map { it.title },
)
}
fun toGroups(): List<WhatsNewGroup> =
highlight?.let { curated ->
if (changes.isNotEmpty()) {
buildList {
val highlights = highlightedChanges()
if (highlights.isNotEmpty()) {
add(WhatsNewGroup("Highlights", highlights.map { it.fallbackText() }))
}
listOf(
CHANGE_KIND_ADDED to "Added",
CHANGE_KIND_IMPROVED to "Improved",
CHANGE_KIND_FIXED to "Fixed",
).forEach { (kind, label) ->
val items = remainingChangesOfKind(kind)
if (items.isNotEmpty()) {
add(WhatsNewGroup(label, items.map { it.fallbackText() }))
}
}
if (compatibility.isNotEmpty()) {
add(WhatsNewGroup("Compatibility", compatibility))
}
}
} else highlight?.let { curated ->
buildList {
add(WhatsNewGroup(curated.title.takeIf { it.isNotBlank() }, curated.bullets))
if (improvements.isNotEmpty()) {
@@ -185,6 +185,10 @@ internal fun WhatsNewToastContent(
) {
val title = stringResource(R.string.whats_new_title)
val highlight = entry.highlight
val digest = entry.resolvedToastDigest()
val releaseTitle = entry.title?.takeIf(String::isNotBlank) ?: highlight?.title.orEmpty()
val releaseSummary = entry.summary?.takeIf(String::isNotBlank)
?: highlight?.summary?.takeIf(String::isNotBlank)
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
@@ -220,14 +224,14 @@ internal fun WhatsNewToastContent(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = highlight?.title ?: entry.title.orEmpty(),
text = releaseTitle,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
highlight?.summary?.takeIf(String::isNotBlank)?.let { summary ->
releaseSummary?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodySmall,
@@ -251,9 +255,9 @@ internal fun WhatsNewToastContent(
)
}
}
entry.toastDigest?.takeIf {
it.additionalFeatureCount > 0 || it.fixCount > 0
}?.let { digest ->
digest?.takeIf {
it.additionalFeatureCount > 0 || it.improvementCount > 0 || it.fixCount > 0
}?.let { resolvedDigest ->
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.32f),
@@ -272,21 +276,30 @@ internal fun WhatsNewToastContent(
) {
Column(modifier = Modifier.weight(1f)) {
val counts = buildList {
if (digest.additionalFeatureCount > 0) {
if (resolvedDigest.additionalFeatureCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_additional_feature_count,
digest.additionalFeatureCount,
digest.additionalFeatureCount,
resolvedDigest.additionalFeatureCount,
resolvedDigest.additionalFeatureCount,
),
)
}
if (digest.fixCount > 0) {
if (resolvedDigest.improvementCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_improvement_count,
resolvedDigest.improvementCount,
resolvedDigest.improvementCount,
),
)
}
if (resolvedDigest.fixCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_fix_count,
digest.fixCount,
digest.fixCount,
resolvedDigest.fixCount,
resolvedDigest.fixCount,
),
)
}
@@ -298,11 +311,11 @@ internal fun WhatsNewToastContent(
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
text = digest.preview.joinToString(", ") + "…",
text = resolvedDigest.preview.joinToString(", ") + "…",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -56,11 +56,21 @@ import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.ui.components.MessageBubble
import com.hermesandroid.relay.ui.theme.RelayRefresh
import com.hermesandroid.relay.viewmodel.ChatViewModel
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import java.io.File
import kotlinx.coroutines.flow.Flow
internal typealias BotChatHistoryLoader = suspend (
profileName: String,
sessionId: String,
mode: SessionMessageLoadMode,
) -> Result<List<MessageItem>>
internal typealias BotChatProfileIconFlow = (connectionId: String, profileName: String) -> Flow<String?>
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -74,14 +84,52 @@ fun BotChatScreen(
connectionViewModel: ConnectionViewModel,
onBack: () -> Unit,
) {
val handler = remember(route.key) { ChatHandler() }
BotChatScreen(
route = route,
bot = bot,
sessionId = sessionId,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = chatViewModel,
onBack = onBack,
handlerFactory = ::ChatHandler,
historyLoader = { profileName, storedSessionId, mode ->
dashboardClient.getSessionMessages(
sessionId = storedSessionId,
profile = profileName,
mode = mode,
)
},
profileIconFlow = connectionViewModel::profileIconFlow,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun BotChatScreen(
route: BotGatewayRoute,
bot: BotRosterEntry,
sessionId: String,
gatewayClient: GatewayChatClient,
dashboardClient: DashboardApiClient,
chatViewModel: ChatViewModel,
onBack: () -> Unit,
handlerFactory: () -> ChatHandler,
historyLoader: BotChatHistoryLoader,
profileIconFlow: BotChatProfileIconFlow,
) {
val handler = remember(route.key) { handlerFactory() }
val context = LocalContext.current
val messages by chatViewModel.messages.collectAsState()
val isStreaming by chatViewModel.isStreaming.collectAsState()
// This route owns the handler but binds it to the ViewModel only after the
// first composition. Collecting delegated ViewModel getters here can pin
// Compose to their empty pre-bind fallback when history settles before the
// next frame. Observe the route-owned source directly so StateFlow replay
// covers fast history, live streaming, completion, and errors.
val messages by handler.messages.collectAsState()
val isStreaming by handler.isStreaming.collectAsState()
val isLoading by chatViewModel.isLoadingHistory.collectAsState()
val error by chatViewModel.error.collectAsState()
val iconPath by connectionViewModel
.profileIconFlow(route.connectionId, route.profileName)
val error by handler.error.collectAsState()
val iconPath by profileIconFlow(route.connectionId, route.profileName)
.collectAsState(initial = null)
val listState = rememberLazyListState()
var composer by remember(route.key, sessionId) { mutableStateOf("") }
@@ -101,11 +149,7 @@ fun BotChatScreen(
selected?.name == route.profileName
}
chatViewModel.setProfileMessageLoaderWithMode { _, storedSessionId, mode ->
dashboardClient.getSessionMessages(
sessionId = storedSessionId,
profile = route.profileName,
mode = mode,
)
historyLoader(route.profileName, storedSessionId, mode)
}
chatViewModel.updateApiClient(null)
chatViewModel.updateGatewayClient(gatewayClient)
@@ -265,6 +265,7 @@ import com.hermesandroid.relay.ui.components.ToolTranscriptItem
import com.hermesandroid.relay.ui.components.groupTranscriptTools
import com.hermesandroid.relay.ui.components.isVisibleForToolDisplay
import com.hermesandroid.relay.ui.components.showsImageGenerationPlaceholder
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.VoiceModeOverlay
import com.hermesandroid.relay.ui.LocalSnackbarHost
import com.hermesandroid.relay.ui.showHumanError
@@ -1228,7 +1229,7 @@ fun ChatScreen(
buildMap {
messages.forEach { message ->
val generationCount = message.toolCalls.count {
it.name.trim().equals("image_generate", ignoreCase = true)
isImageGenerationToolName(it.name)
}
if (generationCount > 0) {
put(message.uiKey, nextOrdinal + generationCount - 1)
@@ -778,7 +778,7 @@ fun ChatSettingsScreen(
serverCaps,
) {
resolveChatTransportStatus(
streamingEndpoint = streamingEndpoint,
streamingEndpoint = resolvedStreamingEndpoint,
gatewayAvailability = gatewayAvailability,
serverCapabilities = serverCaps,
)
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.SessionTransport
import com.hermesandroid.relay.data.capabilities
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.gatewayRouteUrl
@@ -83,6 +84,7 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import com.hermesandroid.relay.viewmodel.RelayUiState
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
import kotlinx.coroutines.launch
/**
@@ -476,12 +478,16 @@ private fun ActiveOverview(
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
GatewayAvailability.SignInRequired,
GatewayAvailability.Unreachable,
GatewayAvailability.Unsupported,
)
val currentRouteUrl = if (usingApiFallback) {
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
// Observe the binding as well as the saved preference so a restored
// conversation immediately presents its actual owner.
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
val usingDirectApi = resolveActiveChatTransport(
boundOwner = activeConversationTransport,
connection = connection,
preference = streamingEndpoint,
) == SessionTransport.SSE
val currentRouteUrl = if (usingDirectApi) {
activeEndpoint?.api?.url ?: connection.apiServerUrl
} else {
effectiveDashboardUrl
@@ -492,23 +498,29 @@ private fun ActiveOverview(
effectiveDashboardUrl = currentRouteUrl,
)
val routeStatus = when {
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
usingDirectApi && apiReachable ->
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
gatewayAvailability == GatewayAvailability.SignInRequired ->
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
gatewayAvailability == GatewayAvailability.Unknown ||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
gatewayAvailability == GatewayAvailability.Unsupported ->
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unsupported ->
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
}
val chatStatus = when {
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
usingDirectApi && apiReachable ->
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
gatewayAvailability == GatewayAvailability.SignInRequired ->
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unreachable ->
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
usingDirectApi && !apiReachable && apiHealth != ConnectionViewModel.HealthStatus.Probing ->
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
}
@@ -62,6 +62,7 @@ import com.hermesandroid.relay.R
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.gatewayRouteUrl
import com.hermesandroid.relay.data.isDashboardOnlyRoute
@@ -386,6 +387,12 @@ private fun ConnectionListCard(
} else {
connection.resolvedDashboardUrl
}
val selectedProfile: Profile? = if (activeConnectionViewModel != null) {
val profile by activeConnectionViewModel.selectedProfile.collectAsState()
profile
} else {
null
}
val presentedConnection = activeConnection ?: connection
val presentation = resolveGatewayCardPresentation(
connection = presentedConnection,
@@ -429,13 +436,7 @@ private fun ConnectionListCard(
modifier = Modifier
.size(10.dp)
.clip(RoundedCornerShape(50))
.background(
if (presentation.status == GatewayCardStatus.Online) {
com.hermesandroid.relay.ui.theme.RelayRefresh.Green
} else {
MaterialTheme.colorScheme.outline
},
),
.background(gatewayStatusColor(presentation.status)),
)
Icon(
imageVector = Icons.Filled.Dns,
@@ -484,6 +485,20 @@ private fun ConnectionListCard(
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (isActive) {
Text(
text = listOfNotNull(
stringResource(R.string.conn_info_profile),
selectedProfile?.name?.takeIf { it.isNotBlank() }
?: stringResource(R.string.settings_server_default),
selectedProfile?.model?.takeIf { it.isNotBlank() },
).joinToString(" · "),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
if (onSwitch != null || isSwitching || justSwitched) {
OutlinedButton(
@@ -0,0 +1,863 @@
package com.hermesandroid.relay.ui.screens
import android.content.ClipData
import android.content.Intent
import android.content.ClipboardManager
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Backspace
import androidx.compose.material.icons.filled.Dialpad
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.hermesandroid.relay.data.SupervisedParentAuthResult
import com.hermesandroid.relay.data.SupervisedParentAuthStore
import com.hermesandroid.relay.data.SupervisedParentAuthenticator
import com.hermesandroid.relay.data.SupervisedParentCredentialType
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import kotlinx.coroutines.launch
@Composable
internal fun SupervisedParentVerifyDialog(
store: SupervisedParentAuthenticator,
onDismiss: () -> Unit,
onVerified: () -> Unit,
onUseRecoveryCode: () -> Unit,
) {
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
var selectedLegacyType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
?: selectedLegacyType
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun verify(candidateText: String) {
if (busy) return
busy = true
scope.launch {
val candidate = candidateText.toCharArray()
val result = try {
store.verify(candidate)
} finally {
candidate.fill('\u0000')
}
busy = false
when (result) {
SupervisedParentAuthResult.Success -> onVerified()
else -> error = result.toUserMessage()
}
}
}
ParentAuthDialogSurface(
step = null,
onBack = if (storedType == SupervisedParentCredentialType.Legacy && inputType != null) {
{ selectedLegacyType = null; error = null }
} else {
onDismiss
},
) {
when (inputType) {
SupervisedParentCredentialType.Pin -> PinEntryScreen(
title = "Parent PIN",
subtitle = "Enter your 6-digit PIN.",
busy = busy,
error = error,
onComplete = ::verify,
onUseRecovery = onUseRecoveryCode,
)
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
busy = busy,
error = error,
onSubmit = ::verify,
onUseRecovery = onUseRecoveryCode,
)
else -> CredentialChoiceScreen(
title = "How do you enter your parent credential?",
subtitle = "This existing setup predates the PIN/password choice.",
onSelected = { selectedLegacyType = it },
)
}
}
}
@Composable
internal fun SupervisedParentSetupDialog(
store: SupervisedParentAuthenticator,
currentSecretRequired: Boolean,
onDismiss: () -> Unit,
onEnrolled: (SupervisedParentEnrollment) -> Unit,
) {
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
var stage by remember(currentSecretRequired) {
mutableStateOf(if (currentSecretRequired) SetupStage.VerifyCurrent else SetupStage.Choose)
}
var legacyInputType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var currentSecret by remember { mutableStateOf("") }
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun enroll(newSecretText: String) {
val type = credentialType ?: return
busy = true
scope.launch {
val current = currentSecret.toCharArray()
val replacement = newSecretText.toCharArray()
val result = try {
if (currentSecretRequired) store.change(current, replacement, type)
else store.enroll(replacement, type)
} finally {
current.fill('\u0000')
replacement.fill('\u0000')
}
busy = false
result.fold(onSuccess = onEnrolled, onFailure = { error = it.toUserMessage() })
}
}
fun verifyCurrent(candidateText: String) {
busy = true
scope.launch {
val candidate = candidateText.toCharArray()
val result = try { store.verify(candidate) } finally { candidate.fill('\u0000') }
busy = false
if (result == SupervisedParentAuthResult.Success) {
currentSecret = candidateText
error = null
stage = SetupStage.Choose
} else {
error = result.toUserMessage()
}
}
}
val backAction: () -> Unit = when (stage) {
SetupStage.VerifyCurrent, SetupStage.Choose -> onDismiss
SetupStage.Pin, SetupStage.Password -> {
{ stage = SetupStage.Choose; credentialType = null; error = null }
}
}
val step = when (stage) {
SetupStage.VerifyCurrent -> 1 to 3
SetupStage.Choose -> if (currentSecretRequired) 2 to 3 else 1 to 2
SetupStage.Pin, SetupStage.Password -> if (currentSecretRequired) 3 to 3 else 2 to 2
}
ParentAuthDialogSurface(step = step, onBack = backAction) {
when (stage) {
SetupStage.VerifyCurrent -> {
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
?: legacyInputType
when (inputType) {
SupervisedParentCredentialType.Pin -> PinEntryScreen(
title = "Current parent PIN",
subtitle = "Confirm before changing parent access.",
busy = busy,
error = error,
onComplete = ::verifyCurrent,
)
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
title = "Current parent password",
busy = busy,
error = error,
onSubmit = ::verifyCurrent,
)
else -> CredentialChoiceScreen(
title = "How do you enter the current credential?",
subtitle = "Choose the input that matches the existing setup.",
onSelected = { legacyInputType = it },
)
}
}
SetupStage.Choose -> CredentialChoiceScreen(
title = if (currentSecretRequired) "Choose new parent access" else "Choose parent access",
subtitle = "Pick one way to unlock parent settings. You can change it later.",
onSelected = {
credentialType = it
stage = if (it == SupervisedParentCredentialType.Pin) SetupStage.Pin else SetupStage.Password
},
)
SetupStage.Pin -> PinSetupScreen(
busy = busy,
error = error,
onComplete = ::enroll,
)
SetupStage.Password -> PasswordSetupScreen(
busy = busy,
error = error,
onComplete = ::enroll,
)
}
}
}
@Composable
internal fun SupervisedParentRecoveryDialog(
store: SupervisedParentAuthenticator,
onDismiss: () -> Unit,
onReset: (SupervisedParentEnrollment) -> Unit,
) {
var stage by remember { mutableStateOf(RecoveryStage.Phrase) }
var recoveryPhrase by remember { mutableStateOf("") }
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun reset(newSecretText: String) {
val type = credentialType ?: return
busy = true
scope.launch {
val recovery = recoveryPhrase.toCharArray()
val replacement = newSecretText.toCharArray()
val result = try {
store.resetWithRecoveryPhrase(recovery, replacement, type)
} finally {
recovery.fill('\u0000')
replacement.fill('\u0000')
}
busy = false
result.fold(onSuccess = onReset, onFailure = { error = it.toUserMessage() })
}
}
val step = when (stage) {
RecoveryStage.Phrase -> 1 to 3
RecoveryStage.Choose -> 2 to 3
RecoveryStage.Pin, RecoveryStage.Password -> 3 to 3
}
ParentAuthDialogSurface(
step = step,
onBack = when (stage) {
RecoveryStage.Phrase -> onDismiss
RecoveryStage.Choose -> ({ stage = RecoveryStage.Phrase })
RecoveryStage.Pin, RecoveryStage.Password -> ({ stage = RecoveryStage.Choose })
},
) {
when (stage) {
RecoveryStage.Phrase -> RecoveryPhraseInputScreen(
value = recoveryPhrase,
error = error,
onValueChange = { recoveryPhrase = it; error = null },
onContinue = { stage = RecoveryStage.Choose },
)
RecoveryStage.Choose -> CredentialChoiceScreen(
title = "Choose new parent access",
subtitle = "Your recovery phrase will be replaced after reset.",
onSelected = {
credentialType = it
stage = if (it == SupervisedParentCredentialType.Pin) RecoveryStage.Pin
else RecoveryStage.Password
},
)
RecoveryStage.Pin -> PinSetupScreen(busy = busy, error = error, onComplete = ::reset)
RecoveryStage.Password -> PasswordSetupScreen(busy = busy, error = error, onComplete = ::reset)
}
}
}
@Composable
internal fun SupervisedParentRecoveryCodeDialog(
enrollment: SupervisedParentEnrollment,
onDone: () -> Unit,
) {
val context = LocalContext.current
val clipboard = remember(context) {
context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager
}
ParentAuthDialogSurface(step = 3 to 3, onBack = null) {
SupervisedParentRecoveryCodeContent(
enrollment = enrollment,
onShare = {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, enrollment.recoveryPhrase)
}
context.startActivity(Intent.createChooser(intent, "Share recovery phrase"))
},
onCopy = {
clipboard.setPrimaryClip(
ClipData.newPlainText("Parent recovery phrase", enrollment.recoveryPhrase),
)
},
onDone = onDone,
)
}
}
@Composable
private fun ParentAuthDialogSurface(
step: Pair<Int, Int>?,
onBack: (() -> Unit)?,
content: @Composable () -> Unit,
) {
Dialog(
onDismissRequest = { onBack?.invoke() },
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
ParentAuthScreenSurface(step = step, onBack = onBack, content = content)
}
}
@Composable
internal fun ParentAuthScreenSurface(
step: Pair<Int, Int>?,
onBack: (() -> Unit)?,
content: @Composable () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
.imePadding()
.padding(horizontal = 24.dp),
) {
Row(
modifier = Modifier.fillMaxWidth().height(64.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (onBack != null) {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
} else {
Spacer(Modifier.size(48.dp))
}
step?.let { (current, total) ->
Row(
modifier = Modifier.weight(1f),
horizontalArrangement = Arrangement.Center,
) {
repeat(total) { index ->
Box(
Modifier
.padding(horizontal = 3.dp)
.size(width = 46.dp, height = 4.dp)
.clip(CircleShape)
.background(
if (index < current) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.outlineVariant,
),
)
}
}
Text(
"$current of $total",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} ?: Spacer(Modifier.weight(1f))
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopCenter,
) {
content()
}
}
}
}
@Composable
internal fun CredentialChoiceScreen(
title: String,
subtitle: String,
onSelected: (SupervisedParentCredentialType) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = 28.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, subtitle)
Spacer(Modifier.height(28.dp))
CredentialChoiceRow(
icon = { Icon(Icons.Filled.Dialpad, contentDescription = null) },
title = "Use a PIN",
subtitle = "Fast on this phone · 6 digits",
onClick = { onSelected(SupervisedParentCredentialType.Pin) },
)
Spacer(Modifier.height(12.dp))
CredentialChoiceRow(
icon = { Icon(Icons.Filled.Lock, contentDescription = null) },
title = "Use a password",
subtitle = "Works with password managers · 8+ characters",
onClick = { onSelected(SupervisedParentCredentialType.Password) },
)
Spacer(Modifier.height(16.dp))
Text(
"PIN and password are separate choices.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun CredentialChoiceRow(
icon: @Composable () -> Unit,
title: String,
subtitle: String,
onClick: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
Row(
modifier = Modifier.padding(horizontal = 18.dp, vertical = 18.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
modifier = Modifier.size(48.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
) {
Box(contentAlignment = Alignment.Center) { icon() }
}
Column(Modifier.weight(1f).padding(horizontal = 16.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("›", fontSize = 30.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
internal fun PinEntryScreen(
title: String,
subtitle: String,
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
onUseRecovery: (() -> Unit)? = null,
) {
var pin by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, subtitle)
Spacer(Modifier.height(28.dp))
PinDots(pin.length)
Spacer(Modifier.height(26.dp))
NumericKeypad(
enabled = !busy,
onDigit = { digit ->
if (pin.length < 6) {
val next = pin + digit
pin = next
if (next.length == 6) onComplete(next)
}
},
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
)
AuthError(error)
onUseRecovery?.let {
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
}
}
}
@Composable
internal fun PinSetupScreen(
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
) {
var firstPin by remember { mutableStateOf<String?>(null) }
var pin by remember(firstPin) { mutableStateOf("") }
var localError by remember { mutableStateOf<String?>(null) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(
if (firstPin == null) "Create a parent PIN" else "Confirm parent PIN",
if (firstPin == null) "Choose a 6-digit PIN." else "Enter the same 6 digits again.",
)
Spacer(Modifier.height(28.dp))
PinDots(pin.length)
Spacer(Modifier.height(26.dp))
NumericKeypad(
enabled = !busy,
onDigit = { digit ->
if (pin.length < 6) {
val next = pin + digit
pin = next
if (next.length == 6) {
if (firstPin == null) {
firstPin = next
} else if (firstPin == next) {
onComplete(next)
} else {
localError = "The PINs do not match. Try again."
firstPin = null
}
}
}
},
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
)
AuthError(localError ?: error)
}
}
@Composable
private fun NumericKeypad(
enabled: Boolean,
onDigit: (String) -> Unit,
onBackspace: () -> Unit,
) {
val rows = listOf(listOf("1", "2", "3"), listOf("4", "5", "6"), listOf("7", "8", "9"))
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
rows.forEach { row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
row.forEach { digit -> KeypadButton(digit, enabled) { onDigit(digit) } }
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Spacer(Modifier.size(width = 92.dp, height = 58.dp))
KeypadButton("0", enabled) { onDigit("0") }
Surface(
modifier = Modifier.size(width = 92.dp, height = 58.dp).clickable(enabled = enabled, onClick = onBackspace),
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
) {
Box(contentAlignment = Alignment.Center) {
Icon(Icons.AutoMirrored.Filled.Backspace, contentDescription = "Delete digit")
}
}
}
}
}
@Composable
private fun KeypadButton(label: String, enabled: Boolean, onClick: () -> Unit) {
Button(
onClick = onClick,
enabled = enabled,
modifier = Modifier.size(width = 92.dp, height = 58.dp),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurface,
),
) {
Text(label, style = MaterialTheme.typography.headlineSmall)
}
}
@Composable
private fun PinDots(count: Int) {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
repeat(6) { index ->
Box(
Modifier
.size(22.dp)
.clip(CircleShape)
.then(
if (index < count) Modifier.background(MaterialTheme.colorScheme.primary)
else Modifier.border(2.dp, MaterialTheme.colorScheme.outline, CircleShape),
),
)
}
}
}
@Composable
internal fun PasswordSetupScreen(
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
) {
var password by remember { mutableStateOf("") }
var confirmation by remember { mutableStateOf("") }
var reveal by remember { mutableStateOf(false) }
var localError by remember { mutableStateOf<String?>(null) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading("Create a parent password", "Use 8 or more characters.")
Spacer(Modifier.height(28.dp))
PasswordField("Password", password, { password = it; localError = null }, reveal, { reveal = !reveal })
Spacer(Modifier.height(12.dp))
PasswordField("Confirm password", confirmation, { confirmation = it; localError = null }, reveal, { reveal = !reveal }, ImeAction.Done)
AuthError(localError ?: error)
Spacer(Modifier.height(20.dp))
Button(
enabled = !busy && password.isNotEmpty() && confirmation.isNotEmpty(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = {
when {
password != confirmation -> localError = "The passwords do not match."
!SupervisedParentAuthStore.validateNewSecret(
password.toCharArray(),
SupervisedParentCredentialType.Password,
).valid -> localError = "Use a password with at least 8 characters."
else -> onComplete(password)
}
},
) { Text(if (busy) "Saving…" else "Continue") }
}
}
@Composable
internal fun PasswordVerifyScreen(
title: String = "Parent password",
busy: Boolean,
error: String?,
onSubmit: (String) -> Unit,
onUseRecovery: (() -> Unit)? = null,
) {
var password by remember { mutableStateOf("") }
var reveal by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, "Enter your password.")
Spacer(Modifier.height(28.dp))
PasswordField("Password", password, { password = it }, reveal, { reveal = !reveal }, ImeAction.Done)
AuthError(error)
Spacer(Modifier.height(20.dp))
Button(
enabled = !busy && password.isNotEmpty(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = { onSubmit(password) },
) { Text(if (busy) "Checking…" else "Unlock") }
onUseRecovery?.let {
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
}
}
}
@Composable
private fun PasswordField(
label: String,
value: String,
onValueChange: (String) -> Unit,
reveal: Boolean,
onReveal: () -> Unit,
imeAction: ImeAction = ImeAction.Next,
) {
OutlinedTextField(
value = value,
onValueChange = { if (it.length <= 64) onValueChange(it) },
modifier = Modifier.fillMaxWidth(),
label = { Text(label) },
visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),
trailingIcon = {
IconButton(onClick = onReveal) {
Icon(
if (reveal) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = if (reveal) "Hide password" else "Show password",
)
}
},
singleLine = true,
)
}
@Composable
private fun RecoveryPhraseInputScreen(
value: String,
error: String?,
onValueChange: (String) -> Unit,
onContinue: () -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading("Enter recovery phrase", "Paste or type the six words.")
Spacer(Modifier.height(28.dp))
OutlinedTextField(
value = value,
onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("Recovery phrase") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done),
minLines = 2,
)
AuthError(error)
Spacer(Modifier.height(20.dp))
Button(
enabled = value.isNotBlank(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onContinue,
) { Text("Continue") }
}
}
@Composable
internal fun SupervisedParentRecoveryCodeContent(
enrollment: SupervisedParentEnrollment,
onShare: () -> Unit = {},
onCopy: () -> Unit = {},
onDone: () -> Unit = {},
) {
val words = enrollment.recoveryPhrase.split('-')
val displayPhrase = if (words.size == 6) {
words.take(3).joinToString("-") + "\n" + words.drop(3).joinToString("-")
} else {
enrollment.recoveryPhrase
}
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(
"Save your recovery phrase",
"This is the only way to reset parent access if you forget it.",
)
Spacer(Modifier.height(28.dp))
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
SelectionContainer {
Text(
displayPhrase,
modifier = Modifier.padding(20.dp),
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.titleMedium.copy(lineHeight = 28.sp),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
)
}
}
Spacer(Modifier.height(18.dp))
Text(
"Send it somewhere parent-only, then delete the message or saved copy from this phone.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(24.dp))
Button(
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onShare,
) {
Icon(Icons.Filled.Share, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text("Share")
}
Spacer(Modifier.height(10.dp))
OutlinedButton(
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onCopy,
) { Text("Copy phrase") }
TextButton(onClick = onDone) { Text("Done") }
}
}
@Composable
private fun AuthHeading(title: String, subtitle: String) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(8.dp))
Text(
subtitle,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun AuthError(error: String?) {
error?.let {
Spacer(Modifier.height(14.dp))
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
}
private fun SupervisedParentAuthResult.toUserMessage(): String = when (this) {
SupervisedParentAuthResult.Success -> ""
is SupervisedParentAuthResult.Invalid -> if (attemptsBeforeDelay > 0) {
"Incorrect parent credential. $attemptsBeforeDelay attempts remain before a delay."
} else {
"Incorrect parent credential."
}
is SupervisedParentAuthResult.Throttled -> {
val seconds = ((retryAfterMillis + 999L) / 1_000L).coerceAtLeast(1)
"Too many attempts. Try again in $seconds seconds."
}
SupervisedParentAuthResult.Missing -> "Parent access has not been set up."
SupervisedParentAuthResult.Corrupt -> "Parent access data is unavailable. Supervised Mode remains locked."
}
private fun Throwable.toUserMessage(): String = when (this) {
is IllegalArgumentException -> message ?: "The new parent credential is not valid."
is SupervisedParentAuthStore.ParentAuthenticationException -> authResult.toUserMessage()
else -> "Parent access could not be updated. Try again."
}
private enum class SetupStage { VerifyCurrent, Choose, Pin, Password }
private enum class RecoveryStage { Phrase, Choose, Pin, Password }
@@ -1,8 +1,5 @@
package com.hermesandroid.relay.ui.screens
import android.app.Activity
import android.app.KeyguardManager
import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
@@ -52,7 +49,9 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -65,6 +64,9 @@ import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
import com.hermesandroid.relay.data.SupervisedModePolicy
import com.hermesandroid.relay.data.SupervisedParentAuthStatus
import com.hermesandroid.relay.data.SupervisedParentAuthStore
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.data.SupervisedSessionActions
import com.hermesandroid.relay.data.SupervisedVisibilityPreset
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
@@ -77,6 +79,7 @@ import com.hermesandroid.relay.ui.theme.LocalBrand
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
import com.hermesandroid.relay.ui.theme.gradientBorder
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import kotlinx.coroutines.launch
/**
* The settings surface available while supervised mode is locked.
@@ -100,28 +103,29 @@ fun SupervisedSettingsScreen(
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
val profileAlias by connectionViewModel.profileDisplayAlias.collectAsState()
val isDarkTheme = LocalBrand.current.isDark
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
initialValue = null,
key1 = parentAuthStore,
) {
parentAuthStore.statusFlow.collect { value = it }
}
var authError by remember { mutableStateOf<String?>(null) }
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
var showAbout by remember { mutableStateOf(false) }
val credentialLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
authError = null
onParentAccessGranted()
}
}
fun requestParentAccess() {
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
val intent = keyguard?.createConfirmDeviceCredentialIntent(
"Parent access",
"Unlock full Hermes settings and supervised-mode controls. Device credentials verify an enrolled device user, not a distinct parent identity.",
)
if (intent == null) {
authError = "Set a device screen lock before using parent access."
} else {
credentialLauncher.launch(intent)
when (parentAuthStatus) {
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
SupervisedParentAuthStatus.Missing -> {
authError = "This legacy supervised policy has no app-specific parent credential and stays locked. " +
"Reset this app's local data, reconnect, and configure parent access before enabling Supervised Mode again."
}
SupervisedParentAuthStatus.Corrupt -> {
authError = "Parent access data is unavailable. Supervised Mode remains locked."
}
null -> authError = "Parent access is still loading."
}
}
@@ -186,7 +190,7 @@ fun SupervisedSettingsScreen(
SupervisedNavigationRow(
icon = Icons.Filled.Lock,
title = "Parent access",
subtitle = "Unlock full settings with the device screen lock",
subtitle = "Unlock full settings with the app parent PIN or password",
onClick = ::requestParentAccess,
isDarkTheme = isDarkTheme,
)
@@ -217,6 +221,38 @@ fun SupervisedSettingsScreen(
},
)
}
when (parentAuthDialog) {
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onVerified = {
parentAuthDialog = null
authError = null
onParentAccessGranted()
},
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
)
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onReset = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
else -> Unit
}
pendingEnrollment?.let { enrollment ->
SupervisedParentRecoveryCodeDialog(
enrollment = enrollment,
onDone = {
pendingEnrollment = null
authError = null
onParentAccessGranted()
},
)
}
}
/** Restricted appearance editor backed by the supervised policy, not global theme settings. */
@@ -293,42 +329,41 @@ fun SupervisedControlsScreen(
onReturnToSupervisedView: () -> Unit,
) {
val context = LocalContext.current
val keyguardManager = remember(context) {
context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
initialValue = null,
key1 = parentAuthStore,
) {
parentAuthStore.statusFlow.collect { value = it }
}
val deviceSecure = keyguardManager?.isDeviceSecure == true
val isDarkTheme = LocalBrand.current.isDark
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
var showProfilePicker by remember { mutableStateOf(false) }
var sessionActionsExpanded by remember { mutableStateOf(false) }
var enableAuthError by remember { mutableStateOf<String?>(null) }
var enableRequested by remember { mutableStateOf(false) }
val enableCredentialLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result ->
val shouldEnable = enableRequested && mayEnableSupervisedMode(
policy = policy,
deviceSecure = deviceSecure,
deviceCredentialConfirmed = result.resultCode == Activity.RESULT_OK,
)
enableRequested = false
if (shouldEnable) {
enableAuthError = null
onPolicyChange(policy.copy(enabled = true))
}
}
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
var enableAfterEnrollment by remember { mutableStateOf(false) }
var showRemoveCredentialConfirm by remember { mutableStateOf(false) }
var removeCredentialBusy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun requestFirstEnable() {
val intent = keyguardManager?.createConfirmDeviceCredentialIntent(
"Enable supervised mode",
"Confirm with an enrolled device credential. This does not verify a distinct parent identity.",
)
if (!deviceSecure || intent == null) {
enableAuthError = "Set a secure device screen lock before enabling supervised mode."
if (!policy.isConfigured) {
enableAuthError = "Choose an agent profile before enabling Supervised Mode."
return
}
enableRequested = true
enableCredentialLauncher.launch(intent)
when (parentAuthStatus) {
SupervisedParentAuthStatus.Missing -> {
enableAfterEnrollment = true
parentAuthDialog = ParentAuthDialog.Setup
}
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
SupervisedParentAuthStatus.Corrupt -> {
enableAuthError = "Parent access data is unavailable. Reset local app data before enabling Supervised Mode."
}
null -> enableAuthError = "Parent access is still loading."
}
}
Scaffold(
@@ -360,14 +395,18 @@ fun SupervisedControlsScreen(
subtitle = when {
policy.pinnedProfileName.isNullOrBlank() ->
"Choose an agent profile before enabling"
!deviceSecure ->
"Set a device screen lock before enabling"
parentAuthStatus == SupervisedParentAuthStatus.Missing ->
"Set an app-specific parent PIN or password"
else ->
"Show only the approved Android chat surfaces"
},
checked = policy.enabled,
enabled = policy.enabled ||
(!policy.pinnedProfileName.isNullOrBlank() && deviceSecure),
(!policy.pinnedProfileName.isNullOrBlank() &&
parentAuthStatus in setOf(
SupervisedParentAuthStatus.Missing,
SupervisedParentAuthStatus.Configured,
)),
onCheckedChange = { enabled ->
if (enabled) requestFirstEnable()
else onPolicyChange(policy.copy(enabled = false))
@@ -404,7 +443,7 @@ fun SupervisedControlsScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
"Android device credentials authenticate an enrolled device user; they do not establish a separate parent identity. Use a parent-only device credential or managed-device policy where that distinction matters.",
"Parent access uses an app-specific PIN or password, separate from the supervised user's Android screen lock and biometrics.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -713,14 +752,42 @@ fun SupervisedControlsScreen(
tint = MaterialTheme.colorScheme.primary,
)
Column(Modifier.padding(start = 12.dp)) {
Text("Device authentication", style = MaterialTheme.typography.titleSmall)
Text("App parent credential", style = MaterialTheme.typography.titleSmall)
Text(
"Full features require the device screen lock. This verifies an enrolled device user, not a distinct parent identity.",
when (parentAuthStatus) {
SupervisedParentAuthStatus.Configured -> "A parent PIN or password is configured for this app."
SupervisedParentAuthStatus.Missing -> "Set a parent PIN or password before enabling Supervised Mode."
SupervisedParentAuthStatus.Corrupt -> "Parent access data is unavailable and fails closed."
null -> "Loading parent access…"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
when (parentAuthStatus) {
SupervisedParentAuthStatus.Missing -> OutlinedButton(
onClick = {
enableAfterEnrollment = false
parentAuthDialog = ParentAuthDialog.Setup
},
) { Text("Set parent PIN or password") }
SupervisedParentAuthStatus.Configured -> {
OutlinedButton(onClick = { parentAuthDialog = ParentAuthDialog.Change }) {
Text("Change parent PIN or password")
}
TextButton(onClick = { parentAuthDialog = ParentAuthDialog.Recovery }) {
Text("Reset with recovery phrase")
}
TextButton(onClick = { showRemoveCredentialConfirm = true }) {
Text(
"Remove parent credential",
color = MaterialTheme.colorScheme.error,
)
}
}
else -> Unit
}
HorizontalDivider()
SupervisedSwitchRow(
title = "Relock when the app leaves the screen",
@@ -794,6 +861,118 @@ fun SupervisedControlsScreen(
},
)
}
if (showRemoveCredentialConfirm) {
RemoveParentCredentialDialog(
busy = removeCredentialBusy,
onDismiss = { showRemoveCredentialConfirm = false },
onConfirm = {
removeCredentialBusy = true
scope.launch {
val result = parentAuthStore.clearCredentialAndDisablePolicies()
removeCredentialBusy = false
result.fold(
onSuccess = {
showRemoveCredentialConfirm = false
enableAuthError = null
onBack()
},
onFailure = {
enableAuthError = "Parent access could not be removed. Try again."
},
)
}
},
)
}
when (parentAuthDialog) {
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onVerified = {
parentAuthDialog = null
enableAuthError = null
if (mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
onPolicyChange(policy.copy(enabled = true))
}
},
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
)
ParentAuthDialog.Setup -> SupervisedParentSetupDialog(
store = parentAuthStore,
currentSecretRequired = false,
onDismiss = {
parentAuthDialog = null
enableAfterEnrollment = false
},
onEnrolled = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
ParentAuthDialog.Change -> SupervisedParentSetupDialog(
store = parentAuthStore,
currentSecretRequired = true,
onDismiss = { parentAuthDialog = null },
onEnrolled = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onReset = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
null -> Unit
}
pendingEnrollment?.let { enrollment ->
SupervisedParentRecoveryCodeDialog(
enrollment = enrollment,
onDone = {
pendingEnrollment = null
enableAuthError = null
if (enableAfterEnrollment && mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
onPolicyChange(policy.copy(enabled = true))
}
enableAfterEnrollment = false
},
)
}
}
@Composable
internal fun RemoveParentCredentialDialog(
busy: Boolean,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
title = { Text("Remove parent credential?") },
text = {
Text(
"This disables Supervised Mode on every connection and removes the app-wide " +
"PIN or password and recovery phrase. Your supervised settings and toggles are kept. " +
"Hermes sessions and server history are not deleted.",
)
},
confirmButton = {
TextButton(enabled = !busy, onClick = onConfirm) {
Text(
if (busy) "Removing…" else "Remove",
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(enabled = !busy, onClick = onDismiss) { Text("Cancel") }
},
)
}
@Composable
@@ -984,6 +1163,13 @@ private fun sessionActionsSummary(actions: SupervisedSessionActions): String = w
else -> "${actions.enabledCount} of ${SupervisedSessionActions.TOTAL} allowed"
}
private enum class ParentAuthDialog {
Verify,
Setup,
Change,
Recovery,
}
@Composable
private fun SessionActionSwitch(
title: String,
@@ -28,25 +28,26 @@ sealed interface ChatRuntimeStatus {
}
/**
* Resolve chat health in product priority order:
* Gateway primary, API/SSE fallback, pending connection, then unavailable.
* Resolve chat health for the active conversation owner only. A reachable
* sibling endpoint cannot make a signed-out or unreachable conversation look
* connected.
*/
fun resolveChatRuntimeStatus(
gateway: ChatTransportReadiness,
apiSse: ChatTransportReadiness,
): ChatRuntimeStatus = when {
gateway == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
transport = ChatTransportPath.Gateway,
fallback = false,
)
apiSse == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
transport = ChatTransportPath.ApiSse,
fallback = true,
)
gateway == ChatTransportReadiness.Connecting ||
apiSse == ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
else -> ChatRuntimeStatus.Unavailable
owner: ChatTransportPath = ChatTransportPath.Gateway,
): ChatRuntimeStatus {
val readiness = when (owner) {
ChatTransportPath.Gateway -> gateway
ChatTransportPath.ApiSse -> apiSse
}
return when (readiness) {
ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
transport = owner,
fallback = false,
)
ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
ChatTransportReadiness.NotConfigured,
ChatTransportReadiness.Unavailable -> ChatRuntimeStatus.Unavailable
}
}
@@ -126,6 +126,7 @@ import com.hermesandroid.relay.notifications.InteractionRequestNotifier
import com.hermesandroid.relay.reliability.ReliabilityCenter
import com.hermesandroid.relay.reliability.SessionResetEvidence
import com.hermesandroid.relay.ui.components.ServerImageResult
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.SlashCommand
import com.hermesandroid.relay.voice.RealtimeTurnSyncBuilder
import com.hermesandroid.relay.voice.VoiceIntentSyncBuilder
@@ -290,7 +291,7 @@ internal data class ResolvedGatewayActiveSessions(
val ambiguousForCurrent: Boolean,
)
/** Resolve process-wide runtime rows without ever inventing a profile owner. */
/** Resolve process-wide runtime rows without ever inventing an ambiguous profile owner. */
internal fun resolveGatewayActiveSessions(
sessions: List<GatewayActiveSession>,
directory: Set<SessionActivityOwner>,
@@ -315,6 +316,8 @@ internal fun resolveGatewayActiveSessions(
currentRuntimeId == row.runtimeSessionId &&
currentOwner.storedSessionId == row.storedSessionId -> currentOwner
explicitProfile != null && candidates.size == 1 -> candidates.single()
explicitProfile == null && currentOwner != null && candidates.singleOrNull() == currentOwner ->
currentOwner
else -> null
}
if (owner == null) {
@@ -2120,9 +2123,12 @@ class ChatViewModel : ViewModel() {
* RelayApp pushes the resolved value) prefers an EventSource-compatible
* OpenAI chat path instead of assuming `/v1/runs` is an SSE stream.
*/
private var resolvedStreamingEndpoint: String = "completions"
var streamingEndpoint: String = "completions"
set(value) {
field = value
resolvedStreamingEndpoint = value
field = endpointForConversationOwner(value)
// Only the gateway transport auto-names sessions server-side
// (tui_gateway runs the turn in a HermesCLI child that calls
// agent.title_generator.maybe_auto_title). The api_server SSE/runs/
@@ -2137,12 +2143,19 @@ class ChatViewModel : ViewModel() {
}
/**
* SSE endpoint used when a "gateway" turn can't run (gateway unreachable,
* sign-in expired, attachments present). Wired from RelayApp alongside
* [streamingEndpoint] as the capability-resolved SSE preference; never
* "auto" or "gateway".
* Capability-resolved endpoint for an explicitly API-owned compatibility
* conversation. It never acts as a fallback for a Gateway-owned chat.
*/
var sseFallbackEndpoint: String = "completions"
set(value) {
field = value
if (
conversationBinding.value.transport == SessionTransport.SSE &&
resolvedStreamingEndpoint == "gateway"
) {
streamingEndpoint = resolvedStreamingEndpoint
}
}
/**
* Gateway chat transport (dashboard `/api/ws` — live thinking). Owned and
@@ -3183,6 +3196,7 @@ class ChatViewModel : ViewModel() {
) {
val handler = chatHandler ?: return
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) return
val contextKey = activeProfileContextKey
gatewayHistoryReconcileJob?.cancel()
gatewayHistoryReconcileJob = viewModelScope.launch {
val expected = expectedAssistantText?.trim()?.takeIf { it.isNotEmpty() }
@@ -3215,7 +3229,28 @@ class ChatViewModel : ViewModel() {
}
val transcriptSnapshot = handler.messages.value
val serverMessages = loadGatewaySessionHistory(storedSessionId)
val serverMessages = try {
loadGatewaySessionHistory(
sessionId = storedSessionId,
requireProfileScope = true,
)
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
// A live completion is already visible and settled locally.
// History auth loss must retain that transcript and promote
// the existing sign-in recovery instead of escaping this
// Main-scope coroutine and crashing the app.
if (
chatHandler === handler &&
activeProfileContextKey == contextKey &&
handler.currentSessionId.value == storedSessionId
) {
publishHistoryLoadFailure(storedSessionId, e)
}
gatewayHistoryReconcileJob = null
return@launch
}
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) {
return@launch
}
@@ -3727,6 +3762,17 @@ class ChatViewModel : ViewModel() {
private val bindingDisplayProfile: Profile?
get() = conversationBinding.value.displayProfile
private fun endpointForConversationOwner(candidate: String): String =
when (conversationBinding.value.transport) {
SessionTransport.GATEWAY -> "gateway"
SessionTransport.SSE -> if (candidate == "gateway") sseFallbackEndpoint else candidate
null -> candidate
}
private fun reapplyConversationTransportAffinity() {
streamingEndpoint = resolvedStreamingEndpoint
}
/**
* Profile namespace owned by the conversation currently on screen. Opening a
* row from the global All Profiles browser binds this state first; the UI
@@ -3739,6 +3785,7 @@ class ChatViewModel : ViewModel() {
private fun clearOpenedSessionOwner() {
conversationBindingController.releaseExplicitOwner()
reapplyConversationTransportAffinity()
}
/** Process ownership is profile+session scoped; stored IDs alone are not globally unique. */
@@ -3848,6 +3895,12 @@ class ChatViewModel : ViewModel() {
profileSessionPageLister = lister
}
private var dashboardSignInRequiredHandler: (() -> Unit)? = null
fun setDashboardSignInRequiredHandler(handler: () -> Unit) {
dashboardSignInRequiredHandler = handler
}
/**
* Deletes a session scoped to the active profile on gateway connections
* (dashboard `DELETE /api/sessions/{id}?profile=`). The write twin of
@@ -4236,7 +4289,19 @@ class ChatViewModel : ViewModel() {
}
private fun publishHistoryLoadFailure(sessionId: String, error: Throwable) {
if (error.isDashboardSignInRequiredFailure()) return
if (error.isDashboardSignInRequiredFailure()) {
dashboardSignInRequiredHandler?.invoke()
DiagnosticsLog.record(
category = DiagnosticCategory.Auth,
severity = DiagnosticSeverity.Warning,
title = "Dashboard sign-in required for chat history",
detail = "stored_session=$sessionId; dashboard_auth=required",
operation = "load chat history",
endpointRole = "gateway",
suggestion = "Sign in to Dashboard on the active route, then retry this conversation.",
)
return
}
val rawError = error.message?.takeIf { it.isNotBlank() }
?: "The active profile's conversation history could not be reached."
_chatFailure.value = ChatFailureNotice(
@@ -4637,6 +4702,7 @@ class ChatViewModel : ViewModel() {
lastSessionRefreshSuccessNanos = 0L
_sessionListUnavailable.value = false
conversationBindingController.reset()
reapplyConversationTransportAffinity()
exitProvisionalThread()
relayCapabilityGeneration.incrementAndGet()
relayReasoningCapabilities.value = emptyMap()
@@ -4799,6 +4865,8 @@ class ChatViewModel : ViewModel() {
} else {
sessionProfileNameProvider()
}
val targetTransport = sessionId?.let(SessionTransport::forSessionId)
?: SessionTransport.forEndpoint(resolvedStreamingEndpoint)
if (explicitBinding) {
val accepted = conversationBindingController.openExplicit(
contextKey = contextKey,
@@ -4806,6 +4874,7 @@ class ChatViewModel : ViewModel() {
sessionId = sessionId,
displayProfile = explicitDisplayProfile,
lockedProfileToken = lockedProfileNameProvider(),
transport = targetTransport,
)
if (!accepted) return
} else if (reconciliation) {
@@ -4813,6 +4882,7 @@ class ChatViewModel : ViewModel() {
contextKey = contextKey,
profileName = targetProfileName,
sessionId = sessionId,
transport = targetTransport,
)
if (!accepted) {
_initialChatSettled.value = true
@@ -4823,8 +4893,10 @@ class ChatViewModel : ViewModel() {
contextKey = contextKey,
profileName = targetProfileName,
sessionId = sessionId,
transport = targetTransport,
)
}
reapplyConversationTransportAffinity()
activateSessionActivityScope()
handler.activeAgentName = currentAgentDisplayName()
if (
@@ -5382,6 +5454,7 @@ class ChatViewModel : ViewModel() {
// recovery state. Preserve cached history and
// mark the directory unavailable without also
// emitting a generic turn/error toast.
dashboardSignInRequiredHandler?.invoke()
} else if (scoped != null) {
// The shared API list belongs to the launch/default
// database. Preserve the current profile's rows and
@@ -5404,7 +5477,9 @@ class ChatViewModel : ViewModel() {
)
retryUnavailable = true
retryReadiness = retryReadiness || !e.isSessionReadTimeout()
if (!e.isDashboardSignInRequiredFailure()) {
if (e.isDashboardSignInRequiredFailure()) {
dashboardSignInRequiredHandler?.invoke()
} else {
emitError(
e,
context = if (profileSessionLister != null) {
@@ -5581,7 +5656,10 @@ class ChatViewModel : ViewModel() {
// profile/context so an All Profiles conversation becomes a fresh
// draft for that same owner instead of falling back to the globally
// restored default profile.
conversationBindingController.startFreshDraft()
conversationBindingController.startFreshDraft(
SessionTransport.forEndpoint(resolvedStreamingEndpoint),
)
reapplyConversationTransportAffinity()
exitProvisionalThread()
// Gateway turns continue as detached siblings; SSE remains exclusive.
@@ -5840,6 +5918,7 @@ class ChatViewModel : ViewModel() {
val contextKey = activeProfileContextKey
val profileName = currentSessionProfileName()
conversationBindingController.switchSession(sessionId)
reapplyConversationTransportAffinity()
handler.setSessionId(sessionId)
publishQueuedMessages()
@@ -5956,6 +6035,7 @@ class ChatViewModel : ViewModel() {
}
if (handler.currentSessionId.value == null) {
conversationBindingController.switchSession(null)
reapplyConversationTransportAffinity()
onSessionChanged?.invoke(null)
}
@@ -6182,10 +6262,10 @@ class ChatViewModel : ViewModel() {
val client = apiClient
if (
(streamingEndpoint != "gateway" && client == null) ||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
(streamingEndpoint == "gateway" && gatewayClient == null)
) {
val message = if (streamingEndpoint == "gateway") {
"Gateway is unavailable and no API fallback is configured for this connection."
"This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry."
} else {
"API fallback is not configured for this connection."
}
@@ -6293,9 +6373,15 @@ class ChatViewModel : ViewModel() {
?: return VoiceMessageSubmissionResult.Rejected("Hermes chat is not ready.")
val client = apiClient
if ((streamingEndpoint != "gateway" && client == null) ||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
(streamingEndpoint == "gateway" && gatewayClient == null)
) {
return VoiceMessageSubmissionResult.Rejected("Hermes is not connected.")
return VoiceMessageSubmissionResult.Rejected(
if (streamingEndpoint == "gateway") {
"This chat needs the Hermes Dashboard. Sign in or reconnect, then retry."
} else {
"The direct API connection is unavailable."
},
)
}
if (activeStream != null || streamRecovery != null || handler.isStreaming.value) {
return VoiceMessageSubmissionResult.Rejected(
@@ -7823,13 +7909,39 @@ class ChatViewModel : ViewModel() {
if (!queuedSuccessorPending.get()) {
val expectedSessionId = checkpoint.sessionId
viewModelScope.launch {
val history = loadSessionHistory(expectedSessionId)
if (handler.currentSessionId.value == expectedSessionId && history.isNotEmpty()) {
handler.loadMessageHistory(history)
refreshSessions()
scheduleTitleReconcile(expectedSessionId)
try {
val history = loadSessionHistory(expectedSessionId)
if (
handler.currentSessionId.value == expectedSessionId &&
history.isNotEmpty()
) {
handler.loadMessageHistory(history)
clearMatchingHistoryLoadFailure(expectedSessionId)
}
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
// Recovery completion has already settled the
// local turn. Keep it visible and route an
// expired Dashboard session to sign-in.
if (
chatHandler === handler &&
activeProfileContextKey == checkpoint.contextKey &&
handler.currentSessionId.value == expectedSessionId
) {
publishHistoryLoadFailure(expectedSessionId, e)
}
} finally {
if (
chatHandler === handler &&
activeProfileContextKey == checkpoint.contextKey &&
handler.currentSessionId.value == expectedSessionId
) {
refreshSessions()
scheduleTitleReconcile(expectedSessionId)
}
drainQueue()
}
drainQueue()
}
}
}
@@ -9566,7 +9678,7 @@ class ChatViewModel : ViewModel() {
ensurePostInterimMessage()
streamDeltas.flushNow()
val alreadyObserved =
toolName == "image_generate" &&
isImageGenerationToolName(toolName) &&
observedImageToolStates.putIfAbsent(toolCallId, "running") != null
if (!alreadyObserved) {
handler.onToolCallStart(currentMessageId, toolCallId, toolName, argsPreview)
@@ -9693,6 +9805,7 @@ class ChatViewModel : ViewModel() {
// tool.complete. The structured reload recovers those calls without ever
// parsing assistant prose and retains the profile-aware history boundary.
val sid = handler.currentSessionId.value
val historyContextKey = activeProfileContextKey
// A turn that ended in an error (gateway ❌ lifecycle → "Error" badge)
// has NO assistant message persisted server-side, so reconciling the
// server transcript would WIPE the just-shown error bubble (the user
@@ -9711,34 +9824,54 @@ class ChatViewModel : ViewModel() {
)
}
viewModelScope.launch {
if (!turnErrored && !gatewayHistoryReconcileRequired) {
// Profile-aware read: a gateway turn on a non-default profile
// persists into THAT profile's own state.db, so the bare
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
// → a silent wipe of the just-finished turn. loadSessionHistory
// prefers the `?profile=` dashboard loader on gateway connections.
val serverMessages = loadSessionHistory(sid)
val missingPersistedToolActivity =
completedTransport == "gateway" &&
handler.hasMissingPersistedToolActivity(serverMessages)
if (shouldReloadHistoryAfterSuccessfulTurn(
actualTransport = completedTransport,
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
missingPersistedToolActivity = missingPersistedToolActivity,
)
) {
handler.loadMessageHistory(serverMessages)
try {
if (!turnErrored && !gatewayHistoryReconcileRequired) {
// Profile-aware read: a gateway turn on a non-default profile
// persists into THAT profile's own state.db, so the bare
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
// → a silent wipe of the just-finished turn. loadSessionHistory
// prefers the `?profile=` dashboard loader on gateway connections.
val serverMessages = loadSessionHistory(sid)
val missingPersistedToolActivity =
completedTransport == "gateway" &&
handler.hasMissingPersistedToolActivity(serverMessages)
if (shouldReloadHistoryAfterSuccessfulTurn(
actualTransport = completedTransport,
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
missingPersistedToolActivity = missingPersistedToolActivity,
)
) {
handler.loadMessageHistory(serverMessages)
clearMatchingHistoryLoadFailure(sid)
}
}
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
if (
chatHandler === handler &&
activeProfileContextKey == historyContextKey &&
handler.currentSessionId.value == sid
) {
publishHistoryLoadFailure(sid, e)
}
} finally {
// Re-sync the drawer now that the turn is persisted server-side.
// The only other auto-refresh fires ~160ms after session creation
// (RelayApp) — mid-stream, BEFORE the new session's first message
// is persisted, so a brand-new chat would otherwise stay missing
// from the drawer (carried only by the optimistic row) until a
// manual reload. By message.complete the dashboard list includes it.
if (
chatHandler === handler &&
activeProfileContextKey == historyContextKey &&
handler.currentSessionId.value == sid
) {
refreshSessions()
scheduleTitleReconcile(sid)
}
drainQueue()
}
// Re-sync the drawer now that the turn is persisted server-side.
// The only other auto-refresh fires ~160ms after session creation
// (RelayApp) — mid-stream, BEFORE the new session's first message
// is persisted, so a brand-new chat would otherwise stay missing
// from the drawer (carried only by the optimistic row) until a
// manual reload. By message.complete the dashboard list includes it.
refreshSessions()
scheduleTitleReconcile(sid)
drainQueue()
}
Unit
} else {
@@ -10015,12 +10148,11 @@ class ChatViewModel : ViewModel() {
)
}
// SSE dispatch shared by the three HTTP endpoints AND the gateway
// branch's per-turn fallback (gateway unreachable / not the resolved
// transport). Warns once per dispatch about any attachment it can't carry.
// SSE dispatch shared by the three explicit API compatibility endpoints.
// Warns once per dispatch about any attachment it can't carry.
fun dispatchSse(endpoint: String): ActiveTurnHandle? {
val sseClient = client ?: run {
onErrorCb("Gateway unavailable and no API fallback is configured.")
onErrorCb("The direct API connection is unavailable.")
return null
}
val prepared = prepareTextTransportAttachments(message, attachments.orEmpty())
@@ -10165,13 +10297,13 @@ class ChatViewModel : ViewModel() {
activeStream = when {
effectiveEndpoint != "gateway" -> dispatchSse(effectiveEndpoint)
// Gateway turns upload ALL attachments via their typed upstream
// RPC (image.attach_bytes / pdf.attach / file.attach), matching the
// desktop client. Only a missing gateway client forces the per-turn
// SSE fallback (where non-image attachments are not upstream-
// recognized and would be dropped — graceful degradation).
gateway == null ->
dispatchSse(resolveSseFallback(handler))
// The conversation owner is immutable. Losing Gateway preserves
// the local transcript/draft and exposes Retry; it never dispatches
// the turn into the API server's different session database.
gateway == null -> {
onErrorCb("This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry.")
null
}
else -> {
startImageActivityBridge()
@@ -10343,11 +10475,14 @@ class ChatViewModel : ViewModel() {
activeStream = null
settleSessionActivity(handler.currentSessionId.value)
} else {
// Nothing started server-side — rerun this turn on
// the SSE fallback. Callbacks land on the main
// thread, so swapping activeStream here is safe.
// The fallback turn is not steerable.
activeStream = dispatchSse(resolveSseFallback(handler))
// Nothing started server-side. Keep this turn bound
// to Gateway and settle it as retryable local state;
// API sessions are a different owner/database.
onPreflightErrorCb(
IllegalStateException(
"Hermes Dashboard chat is unavailable. Sign in or reconnect, then retry.",
),
)
}
},
)
@@ -10371,8 +10506,8 @@ class ChatViewModel : ViewModel() {
// configured transport: a gateway-configured turn forced onto SSE
// (voice interface context, trace drain) did carry the synthetic
// messages, and skipping the mark there re-sent them every turn.
// The async gateway preflight-failure fallback stays conservative:
// its traces are marked on the NEXT turn (at-least-once delivery).
// A failed Gateway preflight leaves these traces unsynced; retrying the
// same owner retains at-least-once delivery without crossing stores.
if (voiceIntentMessages != null && effectiveEndpoint != "gateway") {
if (hasVoiceIntents) handler.markVoiceIntentsSynced()
if (hasCardDispatches) handler.markCardDispatchesSynced()
@@ -10384,18 +10519,6 @@ class ChatViewModel : ViewModel() {
private fun EventSource.asTurnHandle(): ActiveTurnHandle =
ActiveTurnHandle { this.cancel() }
/**
* SSE endpoint for a turn that was meant for the gateway. The sessions
* endpoint needs an existing server session — without one, use the
* stateless completions path instead of failing the turn.
*/
private fun resolveSseFallback(handler: ChatHandler): String =
if (sseFallbackEndpoint == "sessions" && handler.currentSessionId.value == null) {
"completions"
} else {
sseFallbackEndpoint
}
private fun currentAgentDisplayName(
effectiveProfileOverride: Profile? = null,
): String? {
@@ -55,6 +55,8 @@ import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.data.routeAuthority
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.capabilities
import com.hermesandroid.relay.data.automaticChatTransport
import com.hermesandroid.relay.data.chatTransportForPreference
import com.hermesandroid.relay.data.ConnectionSecurity
import com.hermesandroid.relay.data.ConnectionStore
import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
@@ -348,16 +350,16 @@ internal fun resolveChatConnectState(
ready: Boolean,
gatewayAvailability: GatewayAvailability,
apiHealth: ConnectionViewModel.HealthStatus,
chatOwner: SessionTransport = connection?.automaticChatTransport ?: SessionTransport.GATEWAY,
): ChatConnectState {
if (ready) return ChatConnectState.Ready
if (!hydrated) return ChatConnectState.Connecting
val active = connection ?: return ChatConnectState.NeedsConnection
val gatewayStillSettling = active.capabilities.dashboardGatewayConfigured &&
if (connection == null) return ChatConnectState.NeedsConnection
val gatewayStillSettling = chatOwner == SessionTransport.GATEWAY &&
gatewayAvailability in setOf(
GatewayAvailability.Unknown,
GatewayAvailability.SignInRequired,
)
val apiStillSettling = active.capabilities.apiServerConfigured &&
val apiStillSettling = chatOwner == SessionTransport.SSE &&
apiHealth in setOf(
ConnectionViewModel.HealthStatus.Unknown,
ConnectionViewModel.HealthStatus.Probing,
@@ -374,9 +376,20 @@ internal fun isChatTransportReady(
apiClientPresent: Boolean,
apiReachable: Boolean,
gatewayAvailability: GatewayAvailability,
chatOwner: SessionTransport = SessionTransport.GATEWAY,
): Boolean =
gatewayAvailability == GatewayAvailability.Ready ||
(apiClientPresent && apiReachable)
when (chatOwner) {
SessionTransport.GATEWAY -> gatewayAvailability == GatewayAvailability.Ready
SessionTransport.SSE -> apiClientPresent && apiReachable
}
internal fun resolveActiveChatTransport(
boundOwner: SessionTransport?,
connection: Connection?,
preference: String,
): SessionTransport = boundOwner
?: connection?.chatTransportForPreference(preference)
?: SessionTransport.GATEWAY
/** Startup transport timeouts are retryable evidence, not an offline verdict. */
internal fun isTransientDashboardTransportFailure(error: Throwable?): Boolean =
@@ -1325,7 +1338,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
upstreamTransport.dashboardSessionClientFor(cid, url)
},
streamingEndpointProvider = { streamingEndpoint.value },
gatewayAvailabilityProvider = { upstreamTransport.gatewayAvailability.value },
automaticTransportProvider = {
activeConnection.value?.automaticChatTransport ?: SessionTransport.GATEWAY
},
setLastSessionId = { _lastSessionId.value = it },
legacyDefaultSessionId = {
getApplication<Application>().relayDataStore.data.first()[KEY_LAST_SESSION_ID]
@@ -1667,10 +1682,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
private val _chatApiClient = MutableStateFlow<HermesApiClient?>(null)
val chatApiClient: StateFlow<HermesApiClient?> = _chatApiClient.asStateFlow()
private val _activeConversationTransport = MutableStateFlow<SessionTransport?>(null)
val activeConversationTransport: StateFlow<SessionTransport?> =
_activeConversationTransport.asStateFlow()
private var profileChatApiClient: HermesApiClient? = null
private var profileChatApiClientUrl: String? = null
private var profileChatApiClientKey: String? = null
fun setActiveConversationTransport(transport: SessionTransport?) {
_activeConversationTransport.value = transport
}
// Chat mode + per-endpoint capability snapshot — owned by
// [upstreamTransport]; getters delegate. `rebuildApiClient()` pushes the
// freshly-probed snapshot via `setCapabilitiesAndMode`.
@@ -1863,16 +1885,24 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
return upstreamTransport.dashboardClientFor(connectionId, dashboardUrl).getConfig()
}
// Gateway/Dashboard is the standard path; API remains an optional fallback.
private val streamingEndpointPreference: StateFlow<String> =
application.relayDataStore.data
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
// Readiness follows the active conversation owner, not any reachable sibling route.
val chatReady: StateFlow<Boolean> = combine(
_chatApiClient,
_apiServerReachable,
combine(_chatApiClient, _apiServerReachable) { client, reachable -> client to reachable },
upstreamTransport.gatewayAvailability,
) { client, apiReachable, gateway ->
activeConnection,
streamingEndpointPreference,
activeConversationTransport,
) { (client, apiReachable), gateway, connection, preference, boundOwner ->
isChatTransportReady(
apiClientPresent = client != null,
apiReachable = apiReachable,
gatewayAvailability = gateway,
chatOwner = resolveActiveChatTransport(boundOwner, connection, preference),
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
@@ -1892,13 +1922,22 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
* before any flow emits — is the neutral state, not the CTA.
*/
val chatConnectState: StateFlow<ChatConnectState> = combine(
connectionStore.isHydrated,
activeConnection,
chatReady,
combine(connectionStore.isHydrated, activeConnection, chatReady) { hydrated, active, ready ->
Triple(hydrated, active, ready)
},
upstreamTransport.gatewayAvailability,
_apiServerHealth,
) { hydrated, active, ready, gateway, apiHealth ->
resolveChatConnectState(hydrated, active, ready, gateway, apiHealth)
streamingEndpointPreference,
activeConversationTransport,
) { (hydrated, active, ready), gateway, apiHealth, preference, boundOwner ->
resolveChatConnectState(
hydrated,
active,
ready,
gateway,
apiHealth,
resolveActiveChatTransport(boundOwner, active, preference),
)
}.stateIn(viewModelScope, SharingStarted.Eagerly, ChatConnectState.Connecting)
// NOTE: [relayReady] / [voiceReady] are declared below the [_relayUrl]
// MutableStateFlow,
@@ -2749,9 +2788,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
//
// Existing users keep whatever they previously chose. Only fresh installs
// (no value persisted yet) get the new "auto" default.
val streamingEndpoint: StateFlow<String> = application.relayDataStore.data
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
val streamingEndpoint: StateFlow<String> = streamingEndpointPreference
fun setStreamingEndpoint(endpoint: String) {
viewModelScope.launch {
@@ -2833,14 +2870,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
*/
fun resolveStreamingEndpoint(preference: String): String =
upstreamTransport.resolveStreamingEndpoint(preference)
upstreamTransport.resolveStreamingEndpoint(
preference = preference,
gatewayOwned = activeConnection.value
?.chatTransportForPreference(preference) == SessionTransport.GATEWAY,
)
/**
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
* [ChatViewModel.sseFallbackEndpoint] for per-turn gateway fallbacks.
* [ChatViewModel.sseFallbackEndpoint] only for an API-owned compatibility
* binding.
*/
fun resolveSseStreamingEndpoint(): String = upstreamTransport.resolveSseStreamingEndpoint()
fun resolveActiveStreamingEndpoint(preference: String): String =
when (activeConversationTransport.value) {
SessionTransport.GATEWAY -> "gateway"
SessionTransport.SSE -> resolveStreamingEndpoint(preference)
.takeUnless { it == "gateway" }
?: resolveSseStreamingEndpoint()
null -> resolveStreamingEndpoint(preference)
}
// Parse tool annotations from text markers toggle
val parseToolAnnotations: StateFlow<Boolean> = application.relayDataStore.data
.map { it[KEY_PARSE_TOOL_ANNOTATIONS] ?: false }
@@ -3674,11 +3725,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
val dashboardConfigured = activeConnection?.capabilities?.dashboardGatewayConfigured == true
val apiConfigured = activeConnection?.capabilities?.apiServerConfigured == true
// This helper runs from an eager StateFlow during construction. Read
// the earlier-declared backing preference, not its later public alias.
val chatOwner = resolveActiveChatTransport(
boundOwner = activeConversationTransport.value,
connection = activeConnection,
preference = streamingEndpointPreference.value,
)
if (
dashboardConfigured &&
gatewayAvailability == GatewayAvailability.SignInRequired &&
(!apiConfigured || apiHealth != HealthStatus.Reachable)
chatOwner == SessionTransport.GATEWAY &&
gatewayAvailability == GatewayAvailability.SignInRequired
) {
return ConnectionStatusSnapshot(
title = ctx.getString(R.string.cw_dashboard_sign_in_required),
@@ -3695,8 +3753,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
if (
dashboardConfigured &&
gatewayAvailability == GatewayAvailability.Unreachable &&
(!apiConfigured || apiHealth != HealthStatus.Reachable)
chatOwner == SessionTransport.GATEWAY &&
gatewayAvailability == GatewayAvailability.Unreachable
) {
return ConnectionStatusSnapshot(
title = ctx.getString(R.string.cw_dashboard_not_reachable),
@@ -3712,7 +3770,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
return when {
apiConfigured &&
chatOwner == SessionTransport.SSE &&
apiConfigured &&
apiHealth == HealthStatus.Unreachable &&
gatewayAvailability != GatewayAvailability.Ready -> {
// Diagnose, don't just report: for a single-route connection
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.SessionTransport
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -23,6 +24,7 @@ internal data class ConversationBinding(
val contextKey: String? = null,
val profileName: String? = null,
val sessionId: String? = null,
val transport: SessionTransport? = null,
val displayProfile: Profile? = null,
val origin: ConversationBindingOrigin = ConversationBindingOrigin.GlobalSelection,
val revision: Long = 0L,
@@ -46,6 +48,7 @@ internal class ConversationBindingController {
sessionId: String?,
displayProfile: Profile?,
lockedProfileToken: String?,
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
): Boolean {
if (!profileAllowed(profileName, lockedProfileToken)) return false
reduce(
@@ -54,6 +57,7 @@ internal class ConversationBindingController {
sessionId = sessionId,
displayProfile = displayProfile,
origin = ConversationBindingOrigin.ExplicitSession,
transport = transport,
)
return true
}
@@ -63,6 +67,7 @@ internal class ConversationBindingController {
profileName: String?,
sessionId: String?,
displayProfile: Profile? = null,
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
) {
reduce(
contextKey = contextKey,
@@ -70,6 +75,7 @@ internal class ConversationBindingController {
sessionId = sessionId,
displayProfile = displayProfile,
origin = ConversationBindingOrigin.GlobalSelection,
transport = transport,
)
}
@@ -79,6 +85,7 @@ internal class ConversationBindingController {
profileName: String?,
sessionId: String?,
displayProfile: Profile? = null,
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
): Boolean {
val current = _state.value
if (
@@ -89,7 +96,7 @@ internal class ConversationBindingController {
current.sessionId != sessionId
)
) return false
forceGlobal(contextKey, profileName, sessionId, displayProfile)
forceGlobal(contextKey, profileName, sessionId, displayProfile, transport)
return true
}
@@ -98,17 +105,19 @@ internal class ConversationBindingController {
if (current.sessionId == sessionId) return
_state.value = current.copy(
sessionId = sessionId,
transport = sessionId?.let(SessionTransport::forSessionId) ?: current.transport,
revision = current.revision + 1,
)
}
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
fun startFreshDraft() {
fun startFreshDraft(transport: SessionTransport? = _state.value.transport) {
val current = _state.value
if (!current.isBound) return
if (current.sessionId == null && current.hasExplicitOwner) return
_state.value = current.copy(
sessionId = null,
transport = transport,
origin = ConversationBindingOrigin.ExplicitSession,
revision = current.revision + 1,
)
@@ -130,6 +139,7 @@ internal class ConversationBindingController {
sessionId: String?,
displayProfile: Profile?,
origin: ConversationBindingOrigin,
transport: SessionTransport?,
) {
val current = _state.value
val next = ConversationBinding(
@@ -138,6 +148,7 @@ internal class ConversationBindingController {
sessionId = sessionId,
displayProfile = displayProfile,
origin = origin,
transport = transport,
revision = current.revision + 1,
)
if (current.copy(revision = next.revision) != next) {
@@ -130,8 +130,8 @@ class ProfileController(
private val dashboardClientFactory: (connectionId: String, dashboardUrl: String) -> DashboardApiClient,
/** Current `streamingEndpoint` preference (for [activeSessionTransport]). */
private val streamingEndpointProvider: () -> String,
/** Current gateway availability tier (for [activeSessionTransport]). */
private val gatewayAvailabilityProvider: () -> GatewayAvailability,
/** Stable Auto owner for the active saved connection. */
private val automaticTransportProvider: () -> SessionTransport,
/** Writes `ConnectionViewModel._lastSessionId`. */
private val setLastSessionId: (String?) -> Unit,
/** Legacy default (untransported) session id for the server-default profile. */
@@ -1517,19 +1517,14 @@ class ProfileController(
/**
* Which transport's session slot to restore right now — or `null` when the
* decision is still pending (the gateway probe hasn't landed). A manual
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
* remains Gateway-owned because the transport resolver also chooses Gateway
* until a definitive fallback verdict exists.
* decision is still pending. A manual streaming-endpoint override resolves
* immediately; under `"auto"`, the saved connection contract owns the
* choice, never a transient reachability or authentication verdict.
*/
fun activeSessionTransport(): SessionTransport? {
val preference = streamingEndpointProvider()
if (preference != "auto") return SessionTransport.forEndpoint(preference)
return when (gatewayAvailabilityProvider()) {
GatewayAvailability.Ready -> SessionTransport.GATEWAY
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
else -> SessionTransport.SSE
}
return automaticTransportProvider()
}
/**
@@ -667,17 +667,21 @@ class UpstreamTransportController(
* - "sessions" / "completions" / "runs" pass through unchanged (manual override wins).
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
*/
fun resolveStreamingEndpoint(preference: String): String =
fun resolveStreamingEndpoint(
preference: String,
gatewayOwned: Boolean,
): String =
resolveStreamingEndpointPreference(
preference = preference,
gateway = _gatewayAvailability.value,
capabilities = _serverCapabilities.value,
gatewayOwned = gatewayOwned,
)
/**
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
* [com.hermesandroid.relay.viewmodel.ChatViewModel.sseFallbackEndpoint] for
* per-turn gateway fallbacks.
* explicit API-owned compatibility conversations.
*/
fun resolveSseStreamingEndpoint(): String =
_serverCapabilities.value.preferredChatEndpoint()
+19 -10
View File
@@ -288,7 +288,7 @@
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
<string name="cw_server_vps_title">Gateway remoto</string>
<string name="cw_server_vps_subtitle">Informe o endereço do Dashboard</string>
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e fallback da API são opcionais.</string>
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e API direta são opcionais.</string>
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
<string name="cw_cloud_agent_name">Endereço do agente</string>
@@ -373,7 +373,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 ou http://your-server:8642</string>
<string name="cw_api_url_supporting">API do Hermes usada pelo Chat e pelas sessões — a porta 8642 da API e http:// são presumidos para hosts sem esquema (a porta 9119 do painel é determinada separadamente)</string>
<string name="cw_scan_message">Procurando o painel/a API do Hermes nesta LAN…</string>
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas no fallback opcional pela API direta.</string>
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas em conexões explícitas pela API direta.</string>
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
<string name="cw_pair_relay_section_desc">O plugin do Relay já está em execução? Faça o pareamento aqui para ativar Terminal, Bridge e permissões de canais.</string>
<string name="cw_pair_relay_url_label">URL do Relay</string>
@@ -584,6 +584,11 @@
<string name="changelog_state_collapsed">Recolhido</string>
<string name="changelog_installed">Instalado</string>
<string name="changelog_also_improved">Também melhorado</string>
<string name="changelog_highlights">Destaques</string>
<string name="changelog_added">Adicionado</string>
<string name="changelog_improved">Melhorado</string>
<string name="changelog_fixed">Corrigido</string>
<string name="changelog_compatibility">Compatibilidade</string>
<string name="changelog_toast_also">Também: %1$s</string>
<string name="changelog_view_all">Ver tudo</string>
<plurals name="changelog_additional_feature_count">
@@ -594,6 +599,10 @@
<item quantity="one">%1$d correção</item>
<item quantity="other">%1$d correções</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d melhoria</item>
<item quantity="other">%1$d melhorias</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnóstico</string>
<string name="diag_back">Voltar</string>
@@ -656,7 +665,7 @@
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
<string name="settings_hermes_management_desc">Recursos do painel: habilidades, cron, MCP, perfis e modelos</string>
<string name="settings_chat">Chat</string>
<string name="settings_chat_desc">Comportamento do chat, Gateway, fallback da API, exibição de ferramentas e tamanho das mensagens</string>
<string name="settings_chat_desc">Comportamento do chat, Gateway, API direta, exibição de ferramentas e tamanho das mensagens</string>
<string name="settings_voice_mode">Modo de voz</string>
<string name="settings_voice_mode_desc">Voz do painel, opções de relay em tempo real e provedores</string>
<string name="settings_threads">Threads</string>
@@ -766,11 +775,11 @@
<string name="chat_settings_debug">Depuração</string>
<string name="chat_settings_show_system_messages_desc">Mostre os marcadores ocultos \"[System: …]\" do servidor (alterações de modelo/personalidade). Desativado corresponde ao desktop/TUI.</string>
<string name="chat_settings_streaming_endpoint">Endpoint de streaming</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: escolhe o melhor caminho com base no que seu servidor oferece. Em uso no momento: </string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: conexões padrão usam o Gateway; conexões somente API usam a API direta. Em uso no momento: </string>
<string name="chat_settings_gateway_suffix"> (pensamento ao vivo pelo WebSocket do painel)</string>
<string name="chat_settings_chat_completions_suffix"> (chat por /v1/chat/completions)</string>
<string name="chat_settings_runs_suffix"> (chat transmitido explicitamente por /v1/runs)</string>
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, usa SSE como alternativa em cada turno.</string>
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, este chat permanece no Gateway e oferece login ou nova tentativa.</string>
<string name="chat_settings_sessions_desc">Sessões: fluxo nativo do Hermes em /api/sessions/{id}/chat/stream.</string>
<string name="chat_settings_chat_desc">Chat: SSE compatível com OpenAI por /v1/chat/completions.</string>
<string name="chat_settings_runs_desc">Runs: use somente quando seu servidor transmitir /v1/runs diretamente.</string>
@@ -3239,7 +3248,7 @@
<string name="whats_new_full_history">Ver histórico completo</string>
<string name="whats_new_no_notes">Nenhuma nota de versão disponível</string>
<string name="whats_new_title">Novidades</string>
<string name="whats_new_subtitle">Destaques da versão mais recente</string>
<string name="whats_new_subtitle">Destaques e detalhes completos da versão</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Acesso temporário à tela expirou</string>
<string name="bridge_notification_auto_disabled_body">Inspeção e controle da tela foram desativados após ociosidade. As outras permissões não mudaram.</string>
@@ -3330,7 +3339,7 @@
<string name="active_section_dashboard_unreachable">Inacessível</string>
<string name="active_section_no_fallback_routes">Ainda não há rotas alternativas</string>
<string name="active_section_no_fallback_routes_desc">Adicione uma rota de API opcional para chat direto alternativo e troca de rede.</string>
<string name="active_section_add_api_fallback">Adicionar rota alternativa</string>
<string name="active_section_add_api_fallback">Adicionar rota de API direta</string>
<string name="active_section_security_authentication">Autenticação</string>
<string name="active_section_dashboard_session">Sessão do Dashboard</string>
<string name="active_section_credential_storage">Armazenamento de credenciais</string>
@@ -3355,7 +3364,7 @@
<string name="cw_timeline_authenticated">Autenticação verificada</string>
<string name="cw_timeline_ready">Conexão pronta</string>
<string name="cw_timeline_ready_detail">Chat, Manage e Voice podem usar este Dashboard</string>
<string name="active_section_optional_api_fallback">Fallback opcional pela API direta</string>
<string name="active_section_optional_api_fallback">API direta opcional</string>
<string name="active_section_api_not_required">Não é necessário quando esta conexão usa o Hermes Dashboard.</string>
<string name="active_section_where_api_key">Onde obtenho essa chave?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY é criada no seu servidor Hermes; este aplicativo não fornece a chave. Configure-a somente ao ativar o servidor de API opcional, que exige uma chave utilizável, e insira aqui o mesmo valor.</string>
@@ -4369,7 +4378,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">API direta</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">Defina o endereço do Dashboard e do Gateway que este telefone deve usar. Rotas privadas de LAN e Tailscale podem usar HTTP ou HTTPS; rotas públicas exigem HTTPS.</string>
<string name="dashboard_address_editor_title">Endereço do gateway</string>
@@ -4386,7 +4395,7 @@
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
<string name="network_routes_empty">No additional network routes</string>
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. O fallback da API e as extensões Relay são opcionais.</string>
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. A API direta e as extensões Relay são opcionais.</string>
<string name="network_routes_title">Network routes</string>
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
+17 -9
View File
@@ -141,7 +141,7 @@
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
<string name="chat_failure_copy_details">复制详情</string>
<string name="chat_failure_route_gateway">网关</string>
<string name="chat_failure_route_api">API 回退</string>
<string name="chat_failure_route_api">Direct API</string>
<string name="chat_open_settings">打开设置</string>
<string name="chat_connect_hermes">连接 Hermes</string>
<string name="chat_try_demo">体验演示</string>
@@ -396,7 +396,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 或 http://你的服务器:8642</string>
<string name="cw_api_url_supporting">聊天和会话使用的 Hermes API——裸主机名默认使用 API 端口 8642 和 http://(仪表盘的 9119 端口单独推导)</string>
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于可选的直接 API 回退。</string>
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
<string name="cw_pair_relay_for">为 %1$s 配对 Relay</string>
<string name="cw_pair_relay_scoped_desc">为这个已保存的 Hermes 连接添加可选的 Relay 扩展。这不会添加或替换服务器。</string>
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">已收起</string>
<string name="changelog_installed">已安装</string>
<string name="changelog_also_improved">其他改进</string>
<string name="changelog_highlights">亮点</string>
<string name="changelog_added">新增</string>
<string name="changelog_improved">改进</string>
<string name="changelog_fixed">修复</string>
<string name="changelog_compatibility">兼容性</string>
<string name="changelog_toast_also">另外:%1$s</string>
<string name="changelog_view_all">查看全部</string>
<plurals name="changelog_additional_feature_count">
@@ -629,6 +634,9 @@
<plurals name="changelog_fix_count">
<item quantity="other">%1$d 项修复</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="other">%1$d 项改进</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">诊断</string>
@@ -695,7 +703,7 @@
<string name="settings_hermes_management">Hermes 管理</string>
<string name="settings_hermes_management_desc">仪表盘功能:技能、定时任务、MCP、配置文件、模型</string>
<string name="settings_chat">聊天</string>
<string name="settings_chat_desc">聊天行为、Gateway、API 回退、工具显示、消息长度</string>
<string name="settings_chat_desc">聊天行为、Gateway、Direct API、工具显示、消息长度</string>
<string name="settings_voice_mode">语音模式</string>
<string name="settings_voice_mode_desc">仪表盘语音、实时 Relay 选项、提供商</string>
<string name="settings_threads">话题</string>
@@ -806,11 +814,11 @@
<string name="chat_settings_debug">调试</string>
<string name="chat_settings_show_system_messages_desc">显示服务器隐藏的 \"[System: …]\" 标记(模型/人格更改)。关闭则与桌面/TUI 一致。</string>
<string name="chat_settings_streaming_endpoint">流式端点</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:根据服务器暴露的内容选择最佳路径。当前使用:</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:标准连接使用网关;仅 API 连接使用直接 API。当前使用:</string>
<string name="chat_settings_gateway_suffix">(通过仪表盘 WebSocket 实时思考)</string>
<string name="chat_settings_chat_completions_suffix">(通过 /v1/chat/completions 聊天)</string>
<string name="chat_settings_runs_suffix">(通过显式流式 /v1/runs 聊天)</string>
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)实时思考+丰富工具事件——桌面应用使用的方式。需要管理登录;不可用时每轮回退到 SSE。</string>
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)提供实时思考和丰富工具事件——桌面应用也使用此路径。需要“管理”登录;不可用时,此聊天仍保留在网关,并提示登录或重试。</string>
<string name="chat_settings_sessions_desc">会话:Hermes 原生 /api/sessions/{id}/chat/stream。</string>
<string name="chat_settings_chat_desc">聊天:通过 /v1/chat/completions 的 OpenAI 兼容 SSE。</string>
<string name="chat_settings_runs_desc">Runs:仅在服务器直接流式传输 /v1/runs 时使用。</string>
@@ -3339,7 +3347,7 @@
<string name="whats_new_full_history">查看完整历史记录</string>
<string name="whats_new_no_notes">无可用的发布说明</string>
<string name="whats_new_title">更新内容</string>
<string name="whats_new_subtitle">最新版本亮点</string>
<string name="whats_new_subtitle">亮点和完整版本详情</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">限时屏幕访问已到期</string>
<string name="bridge_notification_auto_disabled_body">空闲后,屏幕检查和控制已关闭。其他授权保持不变。</string>
@@ -3442,7 +3450,7 @@
<string name="active_section_dashboard_unreachable">无法访问</string>
<string name="active_section_no_fallback_routes">尚无备用路由</string>
<string name="active_section_no_fallback_routes_desc">可添加 API 路由,用于直接聊天回退和网络切换。</string>
<string name="active_section_add_api_fallback">添加备用路由</string>
<string name="active_section_add_api_fallback">添加 Direct API 路由</string>
<string name="active_section_security_authentication">身份验证</string>
<string name="active_section_dashboard_session">Dashboard 会话</string>
<string name="active_section_credential_storage">凭据存储</string>
@@ -3508,7 +3516,7 @@
<string name="cw_timeline_authenticated">身份验证已确认</string>
<string name="cw_timeline_ready">连接已就绪</string>
<string name="cw_timeline_ready_detail">Chat、Manage 和 Voice 可以使用此 Dashboard</string>
<string name="active_section_optional_api_fallback">可选的直接 API 回退</string>
<string name="active_section_optional_api_fallback">可选 Direct API</string>
<string name="active_section_api_not_required">此连接使用 Hermes Dashboard 时不需要配置。</string>
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
@@ -4451,7 +4459,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">直接 API</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">设置此手机使用的 Dashboard 和 Gateway 地址。私有 LAN 与 Tailscale 路由可使用 HTTP 或 HTTPS;公共路由必须使用 HTTPS。</string>
<string name="dashboard_address_editor_title">网关地址</string>
+20 -11
View File
@@ -141,7 +141,7 @@
<string name="chat_failure_details_guidance">Hermes hat diesen Fehler gemeldet. Die App wechselt Routen oder Modelle nicht automatisch.</string>
<string name="chat_failure_copy_details">Details kopieren</string>
<string name="chat_failure_route_gateway">Gateway</string>
<string name="chat_failure_route_api">API-Fallback</string>
<string name="chat_failure_route_api">Direct API</string>
<string name="chat_open_settings">Einstellungen öffnen</string>
<string name="chat_connect_hermes">Hermes verbinden</string>
<string name="chat_try_demo">Demo ausprobieren</string>
@@ -309,7 +309,7 @@
<string name="cw_cloud_subtitle">Mit deinem gehosteten Agenten verbinden</string>
<string name="cw_server_vps_title">Remote-Gateway</string>
<string name="cw_server_vps_subtitle">Dashboard-Adresse eingeben</string>
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und API-Fallback sind optional.</string>
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und Direct API sind optional.</string>
<string name="cw_cloud_entry_title">Mit von Nous gehostetem Hermes verbinden</string>
<string name="cw_cloud_entry_description">Gib die im Nous Portal angezeigte Agentenadresse ein. Nach dem Auffinden von Hermes meldest du dich sicher an.</string>
<string name="cw_cloud_agent_name">Agentenadresse</string>
@@ -396,7 +396,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 oder http://dein-server:8642</string>
<string name="cw_api_url_supporting">Von Chat und Sitzungen verwendete Hermes-API — bei reinen Hosts werden API-Port 8642 und http:// angenommen (Dashboard-Port 9119 wird separat abgeleitet)</string>
<string name="cw_scan_message">Dieses LAN wird nach Hermes-Dashboard/API durchsucht…</string>
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für den optionalen direkten API-Fallback.</string>
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für eine explizite Direct-API-Verbindung.</string>
<string name="cw_pair_relay_section">Relay koppeln (optional)</string>
<string name="cw_pair_relay_for">Relay mit %1$s koppeln</string>
<string name="cw_pair_relay_scoped_desc">Füge dieser gespeicherten Hermes-Verbindung die optionale Relay-Erweiterung hinzu. Dadurch wird kein Server hinzugefügt oder ersetzt.</string>
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">Eingeklappt</string>
<string name="changelog_installed">Installiert</string>
<string name="changelog_also_improved">Außerdem verbessert</string>
<string name="changelog_highlights">Highlights</string>
<string name="changelog_added">Hinzugefügt</string>
<string name="changelog_improved">Verbessert</string>
<string name="changelog_fixed">Behoben</string>
<string name="changelog_compatibility">Kompatibilität</string>
<string name="changelog_toast_also">Außerdem: %1$s</string>
<string name="changelog_view_all">Alle anzeigen</string>
<plurals name="changelog_additional_feature_count">
@@ -631,6 +636,10 @@
<item quantity="one">%1$d Fehlerbehebung</item>
<item quantity="other">%1$d Fehlerbehebungen</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d Verbesserung</item>
<item quantity="other">%1$d Verbesserungen</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnose</string>
@@ -697,7 +706,7 @@
<string name="settings_hermes_management">Hermes-Verwaltung</string>
<string name="settings_hermes_management_desc">Dashboard-Funktionen: Skills, Cron, MCP, Profile, Modelle</string>
<string name="settings_chat">Chat</string>
<string name="settings_chat_desc">Chatverhalten, Gateway, API-Fallback, Werkzeuganzeige, Nachrichtenlänge</string>
<string name="settings_chat_desc">Chatverhalten, Gateway, Direct API, Werkzeuganzeige, Nachrichtenlänge</string>
<string name="settings_voice_mode">Sprachmodus</string>
<string name="settings_voice_mode_desc">Dashboard-Sprache, Echtzeit-Relay-Optionen, Anbieter</string>
<string name="settings_threads">Threads</string>
@@ -808,11 +817,11 @@
<string name="chat_settings_debug">Debug</string>
<string name="chat_settings_show_system_messages_desc">Verborgene \"[System: …]\"-Markierungen des Servers anzeigen (Modell-/Personawechsel). Aus entspricht Desktop/TUI.</string>
<string name="chat_settings_streaming_endpoint">Streaming-Endpunkt</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: wählt anhand der Serverfunktionen den besten Pfad. Derzeit verwendet: </string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: Standardverbindungen verwenden Gateway; reine API-Verbindungen verwenden Direct API. Derzeit verwendet: </string>
<string name="chat_settings_gateway_suffix"> (Live-Denken über den Dashboard-WebSocket)</string>
<string name="chat_settings_chat_completions_suffix"> (Chat über /v1/chat/completions)</string>
<string name="chat_settings_runs_suffix"> (Chat über ausdrücklich gestreamte /v1/runs)</string>
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; weicht bei Nichtverfügbarkeit pro Durchlauf auf SSE aus.</string>
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; bei Nichtverfügbarkeit bleibt dieser Chat auf Gateway und bietet Anmeldung oder Wiederholen an.</string>
<string name="chat_settings_sessions_desc">Sitzungen: Hermes-eigener Endpunkt /api/sessions/{id}/chat/stream.</string>
<string name="chat_settings_chat_desc">Chat: OpenAI-kompatibles SSE über /v1/chat/completions.</string>
<string name="chat_settings_runs_desc">Durchläufe: nur verwenden, wenn dein Server /v1/runs direkt streamt.</string>
@@ -3407,7 +3416,7 @@
<string name="whats_new_full_history">Vollständigen Verlauf anzeigen</string>
<string name="whats_new_no_notes">Keine Versionshinweise verfügbar</string>
<string name="whats_new_title">Neuigkeiten</string>
<string name="whats_new_subtitle">Highlights der neuesten Version</string>
<string name="whats_new_subtitle">Highlights und vollständige Versionsdetails</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Zeitgesteuerter Bildschirmzugriff abgelaufen</string>
<string name="bridge_notification_auto_disabled_body">Bildschirmprüfung und -steuerung sind nach Inaktivität aus. Andere Berechtigungen bleiben unverändert.</string>
@@ -3511,7 +3520,7 @@
<string name="active_section_dashboard_unreachable">Nicht erreichbar</string>
<string name="active_section_no_fallback_routes">Noch keine Ausweichrouten</string>
<string name="active_section_no_fallback_routes_desc">Füge optional eine API-Route für direkten Chat-Ausweichbetrieb und Netzwerkwechsel hinzu.</string>
<string name="active_section_add_api_fallback">Ausweichroute hinzufügen</string>
<string name="active_section_add_api_fallback">Direct-API-Route hinzufügen</string>
<string name="active_section_security_authentication">Authentifizierung</string>
<string name="active_section_dashboard_session">Dashboard-Sitzung</string>
<string name="active_section_credential_storage">Anmeldedatenspeicher</string>
@@ -3575,7 +3584,7 @@
<string name="cw_timeline_authenticated">Authentifizierung bestätigt</string>
<string name="cw_timeline_ready">Verbindung bereit</string>
<string name="cw_timeline_ready_detail">Chat, Manage und Voice können dieses Dashboard verwenden</string>
<string name="active_section_optional_api_fallback">Optionaler direkter API-Fallback</string>
<string name="active_section_optional_api_fallback">Optionale Direct API</string>
<string name="active_section_api_not_required">Nicht erforderlich, wenn diese Verbindung das Hermes Dashboard verwendet.</string>
<string name="active_section_where_api_key">Wo erhalte ich diesen Schlüssel?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY wird auf deinem Hermes-Server erstellt und nicht von dieser App bereitgestellt. Konfiguriere ihn nur für den optionalen API-Server, der einen verwendbaren Schlüssel verlangt, und gib hier denselben Wert ein.</string>
@@ -4526,7 +4535,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">Direct API</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">Lege die Dashboard- und Gateway-Adresse für dieses Telefon fest. Private LAN- und Tailscale-Routen dürfen HTTP oder HTTPS verwenden; öffentliche Routen erfordern HTTPS.</string>
<string name="dashboard_address_editor_title">Gateway-Adresse</string>
@@ -4543,7 +4552,7 @@
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
<string name="network_routes_empty">No additional network routes</string>
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. API-Fallback und Relay-Erweiterungen sind optional.</string>
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. Direct API und Relay-Erweiterungen sind optional.</string>
<string name="network_routes_title">Network routes</string>
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
+13 -4
View File
@@ -556,6 +556,11 @@
<string name="changelog_state_collapsed">Contraído</string>
<string name="changelog_installed">Instalada</string>
<string name="changelog_also_improved">También mejorado</string>
<string name="changelog_highlights">Destacados</string>
<string name="changelog_added">Añadido</string>
<string name="changelog_improved">Mejorado</string>
<string name="changelog_fixed">Corregido</string>
<string name="changelog_compatibility">Compatibilidad</string>
<string name="changelog_toast_also">También: %1$s</string>
<string name="changelog_view_all">Ver todo</string>
<plurals name="changelog_additional_feature_count">
@@ -566,6 +571,10 @@
<item quantity="one">%1$d corrección</item>
<item quantity="other">%1$d correcciones</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d mejora</item>
<item quantity="other">%1$d mejoras</item>
</plurals>
<string name="diag_title">Diagnóstico</string>
<string name="diag_back">Atrás</string>
<string name="diag_status">Estado</string>
@@ -733,11 +742,11 @@
<string name="chat_settings_debug">Depurar</string>
<string name="chat_settings_show_system_messages_desc">Mostrar los marcadores \" ocultos del servidor [Sistema: …]\" (cambios de modelo / personalidad). Off coincide con el escritorio/TUI.</string>
<string name="chat_settings_streaming_endpoint">Punto final de transmisión</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: elige la mejor ruta según lo que expone su servidor. Actualmente usando: </string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: las conexiones estándar usan Gateway; las conexiones solo API usan API directa. En uso: </string>
<string name="chat_settings_gateway_suffix"> (pensamiento en vivo a través del tablero WebSocket)</string>
<string name="chat_settings_chat_completions_suffix"> (chatear vía /v1/chat/completions)</string>
<string name="chat_settings_runs_suffix"> (chatear a través de /v1/runs transmitido explícitamente)</string>
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos en el panel WebSocket (/api/ws): lo que utiliza la aplicación de escritorio. Requiere el inicio de sesión en Administrar; vuelve a SSE por turno cuando no está disponible.</string>
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos por el WebSocket del panel (/api/ws), como en la aplicación de escritorio. Requiere iniciar sesión en Administrar; si no está disponible, este chat permanece en Gateway y ofrece iniciar sesión o reintentar.</string>
<string name="chat_settings_sessions_desc">Sesiones: Hermes-nativo /api/sessions/{id}/chat/stream.</string>
<string name="chat_settings_chat_desc">Chat: SSE compatible con OpenAI a través de /v1/chat/completions.</string>
<string name="chat_settings_runs_desc">Ejecuciones: utilícelo solo cuando su servidor transmita /v1/runs directamente.</string>
@@ -3071,7 +3080,7 @@
<string name="whats_new_full_history">Ver historial completo</string>
<string name="whats_new_no_notes">No hay notas de versión disponibles</string>
<string name="whats_new_title">¿Qué hay de nuevo?</string>
<string name="whats_new_subtitle">Novedades de la última versión</string>
<string name="whats_new_subtitle">Destacados y detalles completos de la versión</string>
<string name="bridge_notification_auto_disabled_title">Acceso de pantalla temporizado vencido</string>
<string name="bridge_notification_auto_disabled_body">La inspección y el control de pantalla están desactivados tras la inactividad. Los demás permisos no cambian.</string>
<string name="bridge_notification_control_title">El agente Hermes tiene control del dispositivo.</string>
@@ -4217,7 +4226,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">API directa</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">Define la dirección del Dashboard y Gateway que usará este teléfono. Las rutas privadas LAN y Tailscale pueden usar HTTP o HTTPS; las rutas públicas requieren HTTPS.</string>
<string name="dashboard_address_editor_title">Dirección del gateway</string>
+19 -11
View File
@@ -141,7 +141,7 @@
<string name="chat_failure_details_guidance">Hermes からこのエラーが報告されました。アプリがルートやモデルを自動的に切り替えることはありません。</string>
<string name="chat_failure_copy_details">詳細をコピー</string>
<string name="chat_failure_route_gateway">ゲートウェイ</string>
<string name="chat_failure_route_api">API フォールバック</string>
<string name="chat_failure_route_api">Direct API</string>
<string name="chat_open_settings">設定を開く</string>
<string name="chat_connect_hermes">Hermesを接続してください</string>
<string name="chat_try_demo">デモを試してみる</string>
@@ -309,7 +309,7 @@
<string name="cw_cloud_subtitle">ホスト済みエージェントに接続します</string>
<string name="cw_server_vps_title">リモートゲートウェイ</string>
<string name="cw_server_vps_subtitle">Dashboard アドレスを入力</string>
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と API フォールバックは任意です。</string>
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と Direct API は任意です。</string>
<string name="cw_cloud_entry_title">Nous ホスト版 Hermes に接続</string>
<string name="cw_cloud_entry_description">Nous Portal に表示されるエージェントのアドレスを入力してください。Hermes が見つかった後、安全にサインインします。</string>
<string name="cw_cloud_agent_name">エージェントのアドレス</string>
@@ -396,7 +396,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 または http://your-server:8642</string>
<string name="cw_api_url_supporting">Hermes API チャットとセッションで使用されます — API ポート 8642 および http:// はベア ホストとして想定されます (ダッシュボードの 9119 は個別に派生します)</string>
<string name="cw_scan_message">この LAN をスキャンして Hermes ダッシュボード/API を探しています…</string>
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは任意の直接 API フォールバックでのみ使います。</string>
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは明示的な Direct API 接続でのみ使います。</string>
<string name="cw_pair_relay_section">Relay のペア (オプション)</string>
<string name="cw_pair_relay_section_desc">すでに Relay プラグインを実行していますか?ここでペアリングすると、ターミナル、Bridge、およびチャネル許可が有効になります。</string>
<string name="cw_pair_relay_url_label">Relay URL</string>
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">折りたたみ済み</string>
<string name="changelog_installed">インストール済み</string>
<string name="changelog_also_improved">その他の改善</string>
<string name="changelog_highlights">ハイライト</string>
<string name="changelog_added">追加</string>
<string name="changelog_improved">改善</string>
<string name="changelog_fixed">修正</string>
<string name="changelog_compatibility">互換性</string>
<string name="changelog_toast_also">その他: %1$s</string>
<string name="changelog_view_all">すべて表示</string>
<plurals name="changelog_additional_feature_count">
@@ -629,6 +634,9 @@
<plurals name="changelog_fix_count">
<item quantity="other">%1$d 件の修正</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="other">%1$d 件の改善</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">診断</string>
@@ -695,7 +703,7 @@
<string name="settings_hermes_management">Hermes 管理</string>
<string name="settings_hermes_management_desc">ダッシュボードの機能: スキル、cron、MCP、プロファイル、モデル</string>
<string name="settings_chat">チャット</string>
<string name="settings_chat_desc">チャット動作、Gateway、API フォールバック、ツール表示、メッセージ長</string>
<string name="settings_chat_desc">チャット動作、Gateway、Direct API、ツール表示、メッセージ長</string>
<string name="settings_voice_mode">ボイスモード</string>
<string name="settings_voice_mode_desc">ダッシュボード音声、リアルタイムRelayオプション、プロバイダー</string>
<string name="settings_threads">Threads</string>
@@ -806,11 +814,11 @@
<string name="chat_settings_debug">デバッグ</string>
<string name="chat_settings_show_system_messages_desc">サーバーの非表示の「[システム: …]」マーカーを表示します (モデル/パーソナリティの変更)。 Off はデスクトップ/TUI に一致します。</string>
<string name="chat_settings_streaming_endpoint">ストリーミングエンドポイント</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: サーバーが公開しているものに基づいて最適なパスを選択します。現在使用しているもの:</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: 標準接続は Gateway、API 専用接続は Direct API を使用します。現在使用中: </string>
<string name="chat_settings_gateway_suffix">(ダッシュボード WebSocket を介したライブ思考)</string>
<string name="chat_settings_chat_completions_suffix">(/v1/chat/completions 経由でチャット)</string>
<string name="chat_settings_runs_suffix">(明示的にストリーミングされた /v1/runs を介してチャットします)</string>
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード上のライブ思考 + 豊富なツール イベント WebSocket (/api/ws) — デスクトップ アプリが使用するもの。管理サインインが必要です。利用できない場合はターンごとに SSE に戻ります。</string>
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード WebSocket(/api/ws)経由のライブ思考と豊富なツールイベント — デスクトップアプリと同じ経路です。管理へのサインインが必要です。利用できない場合もこのチャットは Gateway のまま、サインインまたは再試行を案内します。</string>
<string name="chat_settings_sessions_desc">セッション: Hermes-native /api/sessions/{id}/chat/stream。</string>
<string name="chat_settings_chat_desc">チャット: /v1/chat/completions 経由の OpenAI 互換の SSE。</string>
<string name="chat_settings_runs_desc">実行: サーバーが /v1/runs を直接ストリーミングする場合にのみ使用します。</string>
@@ -3415,7 +3423,7 @@
<string name="whats_new_full_history">全履歴を表示</string>
<string name="whats_new_no_notes">リリースノートはありません</string>
<string name="whats_new_title">新機能</string>
<string name="whats_new_subtitle">最新リリースのハイライト</string>
<string name="whats_new_subtitle">ハイライトと完全なリリース詳細</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">時間制限付き画面アクセスの期限切れ</string>
<string name="bridge_notification_auto_disabled_body">操作がなかったため、画面の検査と操作をオフにしました。他の許可は変更されません。</string>
@@ -3506,7 +3514,7 @@
<string name="active_section_dashboard_unreachable">接続できません</string>
<string name="active_section_no_fallback_routes">フォールバックルートはまだありません</string>
<string name="active_section_no_fallback_routes_desc">直接チャットのフォールバックやネットワーク切り替え用に、任意の API ルートを追加できます。</string>
<string name="active_section_add_api_fallback">フォールバックルートを追加</string>
<string name="active_section_add_api_fallback">Direct API ルートを追加</string>
<string name="active_section_security_authentication">認証</string>
<string name="active_section_dashboard_session">Dashboard セッション</string>
<string name="active_section_credential_storage">認証情報ストレージ</string>
@@ -3572,7 +3580,7 @@
<string name="cw_timeline_authenticated">認証を確認済み</string>
<string name="cw_timeline_ready">接続準備完了</string>
<string name="cw_timeline_ready_detail">Chat、Manage、Voice でこの Dashboard を使用できます</string>
<string name="active_section_optional_api_fallback">任意の直接 API フォールバック</string>
<string name="active_section_optional_api_fallback">任意の Direct API</string>
<string name="active_section_api_not_required">この接続が Hermes Dashboard を使用する場合は必要ありません。</string>
<string name="active_section_where_api_key">このキーはどこで入手しますか?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY は Hermes サーバー上で作成します。このアプリからは発行されません。任意の API サーバーを有効にする場合のみ設定します。このサーバーには使用可能なキーが必要です。同じ値をここに入力してください。</string>
@@ -4522,7 +4530,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">Direct API</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">この端末で使う Dashboard と Gateway のアドレスを設定します。プライベート LAN と Tailscale ルートは HTTP または HTTPS を使用でき、公開ルートには HTTPS が必要です。</string>
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
@@ -4539,7 +4547,7 @@
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
<string name="network_routes_empty">No additional network routes</string>
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。API フォールバックと Relay 拡張は任意です。</string>
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。Direct API と Relay 拡張は任意です。</string>
<string name="network_routes_title">Network routes</string>
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
+20 -9
View File
@@ -292,7 +292,7 @@
<string name="cw_cloud_subtitle">Подключитесь к своему размещённому агенту</string>
<string name="cw_server_vps_title">Удалённый шлюз</string>
<string name="cw_server_vps_subtitle">Введите адрес Dashboard</string>
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и резервный API необязательны.</string>
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и Direct API необязательны.</string>
<string name="cw_cloud_entry_title">Подключиться к Hermes на хостинге Nous</string>
<string name="cw_cloud_entry_description">Введите адрес агента, указанный в Nous Portal. После обнаружения Hermes вы безопасно войдёте в систему.</string>
<string name="cw_cloud_agent_name">Адрес агента</string>
@@ -392,7 +392,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 или http://your-server:8642</string>
<string name="cw_api_url_supporting">API Гермеса, используемый Чатом и сеансами — порт API 8642 и http:// предполагаются для голых хостов (порт 9119 панели управления выводится отдельно)</string>
<string name="cw_scan_message">Сканирование этой локальной сети на предмет панели управления/API Гермеса…</string>
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для необязательного резервного копирования прямого API.</string>
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для явно настроенного Direct API.</string>
<string name="cw_pair_relay_section">Сопряжение Relay (необязательно)</string>
<string name="cw_pair_relay_for">Сопряжение Relay с %1$s</string>
<string name="cw_pair_relay_scoped_desc">Добавьте необязательное расширение Relay к этому сохранённому подключению Гермеса. Это не добавляет и не заменяет сервер.</string>
@@ -599,6 +599,11 @@
<string name="changelog_state_collapsed">Свернуто</string>
<string name="changelog_installed">Установлено</string>
<string name="changelog_also_improved">Также улучшено</string>
<string name="changelog_highlights">Основное</string>
<string name="changelog_added">Добавлено</string>
<string name="changelog_improved">Улучшено</string>
<string name="changelog_fixed">Исправлено</string>
<string name="changelog_compatibility">Совместимость</string>
<string name="changelog_toast_also">Также: %1$s</string>
<string name="changelog_view_all">Показать все</string>
<plurals name="changelog_additional_feature_count">
@@ -613,6 +618,12 @@
<item quantity="many">%1$d исправлений</item>
<item quantity="other">%1$d исправления</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d улучшение</item>
<item quantity="few">%1$d улучшения</item>
<item quantity="many">%1$d улучшений</item>
<item quantity="other">%1$d улучшения</item>
</plurals>
<string name="diag_title">Диагностика</string>
<string name="diag_back">Назад</string>
<string name="diag_status">Статус</string>
@@ -671,7 +682,7 @@
<string name="settings_hermes_management">Управление Гермесом</string>
<string name="settings_hermes_management_desc">Функции панели управления: навыки, cron, MCP, профили, модели</string>
<string name="settings_chat">Чат</string>
<string name="settings_chat_desc">Поведение чата, Gateway, резервный API, отображение инструментов, длина сообщения</string>
<string name="settings_chat_desc">Поведение чата, Gateway, Direct API, отображение инструментов, длина сообщения</string>
<string name="settings_voice_mode">Режим голоса</string>
<string name="settings_voice_mode_desc">Голос панели управления, опции Relay в реальном времени, поставщики</string>
<string name="settings_threads">Потоки</string>
@@ -780,11 +791,11 @@
<string name="chat_settings_debug">Отладка</string>
<string name="chat_settings_show_system_messages_desc">Показывать скрытые сервером маркеры \&quot;[Система: …]\&quot; (изменения модели / личности). Выключено соответствует рабочему столу/TUI.</string>
<string name="chat_settings_streaming_endpoint">Потоковая конечная точка</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: выбирает лучший путь на основе того, что ваш сервер предоставляет. В настоящее время используется:</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: стандартные подключения используют Gateway; подключения только к API используют Direct API. Сейчас используется: </string>
<string name="chat_settings_gateway_suffix">(живое мышление через WebSocket панели управления)</string>
<string name="chat_settings_chat_completions_suffix">(чат через /v1/chat/completions)</string>
<string name="chat_settings_runs_suffix">(чат через явно потоковые /v1/runs)</string>
<string name="chat_settings_gateway_desc">Шлюз: живое мышление + богатые события инструментов через WebSocket панели управления (/api/ws) — что использует настольное приложение. Требует входа в систему Manage; возвращается к SSE на каждый ход, когда недоступен.</string>
<string name="chat_settings_gateway_desc">Gateway: живое мышление и расширенные события инструментов через WebSocket панели управления (/api/ws), как в настольном приложении. Требует входа в Manage; если Gateway недоступен, чат остается на нем и предлагает войти или повторить попытку.</string>
<string name="chat_settings_sessions_desc">Сессии: Hermes-native /api/sessions/{id}/chat/stream.</string>
<string name="chat_settings_chat_desc">Чат: совместимый с OpenAI SSE через /v1/chat/completions.</string>
<string name="chat_settings_runs_desc">Запуски: используйте только когда ваш сервер напрямую потоковые /v1/runs.</string>
@@ -916,7 +927,7 @@
<string name="active_section_dashboard_unreachable">Недоступно</string>
<string name="active_section_no_fallback_routes">Нет резервных маршрутов</string>
<string name="active_section_no_fallback_routes_desc">Добавьте локальный адрес, Tailscale или публичный адрес, чтобы сохранить это соединение доступным при изменении сетей.</string>
<string name="active_section_add_api_fallback">Добавить резервный маршрут</string>
<string name="active_section_add_api_fallback">Добавить маршрут Direct API</string>
<string name="active_section_security_authentication">Аутентификация</string>
<string name="active_section_dashboard_session">Сессия панели управления</string>
<string name="active_section_credential_storage">Хранение учетных данных</string>
@@ -931,7 +942,7 @@
<string name="active_section_route_selection">Выбор маршрута</string>
<string name="active_section_automatic">Автоматически</string>
<string name="active_section_api_access">Доступ к API</string>
<string name="active_section_optional_api_fallback">Дополнительный прямой резерв API</string>
<string name="active_section_optional_api_fallback">Необязательный Direct API</string>
<string name="active_section_api_not_required">Не требуется, если это соединение использует панель управления Гермесом.</string>
<string name="active_section_where_api_key">Где взять это?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY создается на вашем сервере Гермеса; он не предоставляется этим приложением. Настройте его только при включении дополнительного сервера API, который требует рабочего ключа, затем введите то же значение здесь.</string>
@@ -3275,7 +3286,7 @@
<string name="whats_new_full_history">Просмотреть полную историю</string>
<string name="whats_new_no_notes">Примечания к выпуску недоступны</string>
<string name="whats_new_title">Что нового</string>
<string name="whats_new_subtitle">Последние обновления</string>
<string name="whats_new_subtitle">Основное и полный список изменений</string>
<string name="bridge_notification_auto_disabled_title">Временный доступ к экрану истек</string>
<string name="bridge_notification_auto_disabled_body">Просмотр и управление экраном отключены после бездействия. Другие разрешения не изменены.</string>
<string name="bridge_notification_control_title">Агент Гермес имеет управление устройством</string>
@@ -4263,7 +4274,7 @@
<string name="active_section_not_checked_separately">Not checked separately</string>
<string name="active_section_protection_unavailable">Protection unavailable</string>
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">Direct API</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="dashboard_address_editor_body">Укажите адрес Dashboard и Gateway для этого телефона. Частные маршруты LAN и Tailscale могут использовать HTTP или HTTPS; публичным маршрутам требуется HTTPS.</string>
<string name="dashboard_address_editor_title">Адрес шлюза</string>
+22 -13
View File
@@ -145,7 +145,7 @@
<string name="chat_failure_details_guidance">Hermes reported this error. The app won’t switch routes or models automatically.</string>
<string name="chat_failure_copy_details">Copy details</string>
<string name="chat_failure_route_gateway">Gateway</string>
<string name="chat_failure_route_api">API fallback</string>
<string name="chat_failure_route_api">Direct API</string>
<string name="chat_open_settings">Open Settings</string>
<string name="chat_connect_hermes">Connect Hermes</string>
<string name="chat_try_demo">Try the demo</string>
@@ -315,7 +315,7 @@
<string name="cw_cloud_subtitle">Connect to your hosted agent</string>
<string name="cw_server_vps_title">Remote gateway</string>
<string name="cw_server_vps_subtitle">Enter its Dashboard address</string>
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and API fallback are optional.</string>
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and Direct API are optional.</string>
<string name="cw_cloud_entry_title">Connect to Nous-hosted Hermes</string>
<string name="cw_cloud_entry_description">Enter the agent address shown in Nous Portal. You’ll sign in securely after Hermes is found.</string>
<string name="cw_cloud_agent_name">Agent address</string>
@@ -387,7 +387,7 @@
<string name="cw_back">Back</string>
<string name="cw_connect_button">Connect</string>
<string name="cw_hermes_label">Hermes</string>
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the preferred upstream auth path; the API key remains the Android Chat fallback.</string>
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the standard upstream auth path; an API key is only for explicit Direct API connections.</string>
<string name="cw_api_url_label">API server URL or host</string>
<string name="cw_api_key_label">API key</string>
<string name="cw_api_key_placeholder">Value from API_SERVER_KEY</string>
@@ -419,7 +419,7 @@
<string name="cw_api_url_placeholder">192.168.1.10 or http://your-server:8642</string>
<string name="cw_api_url_supporting">Hermes API used by Chat and sessions — API port 8642 and http:// assumed for bare hosts (the dashboard\'s 9119 is derived separately)</string>
<string name="cw_scan_message">Scanning this LAN for Hermes dashboard/API…</string>
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for the optional direct API fallback.</string>
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for optional Direct API compatibility.</string>
<string name="cw_pair_relay_section">Pair Relay (optional)</string>
<string name="cw_pair_relay_for">Pair Relay with %1$s</string>
<string name="cw_pair_relay_scoped_desc">Add the optional Relay extension to this saved Hermes connection. This does not add or replace a server.</string>
@@ -666,6 +666,11 @@
<string name="changelog_state_collapsed">Collapsed</string>
<string name="changelog_installed">Installed</string>
<string name="changelog_also_improved">Also improved</string>
<string name="changelog_highlights">Highlights</string>
<string name="changelog_added">Added</string>
<string name="changelog_improved">Improved</string>
<string name="changelog_fixed">Fixed</string>
<string name="changelog_compatibility">Compatibility</string>
<string name="changelog_toast_also">Also: %1$s</string>
<string name="changelog_view_all">View all</string>
<plurals name="changelog_additional_feature_count">
@@ -676,6 +681,10 @@
<item quantity="one">%1$d fix</item>
<item quantity="other">%1$d fixes</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d improvement</item>
<item quantity="other">%1$d improvements</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnostics</string>
@@ -742,7 +751,7 @@
<string name="settings_hermes_management">Hermes management</string>
<string name="settings_hermes_management_desc">Dashboard features: skills, cron, MCP, profiles, models</string>
<string name="settings_chat">Chat</string>
<string name="settings_chat_desc">Chat behavior, Gateway, API fallback, tool display, message length</string>
<string name="settings_chat_desc">Chat behavior, Gateway, Direct API, tool display, message length</string>
<string name="settings_voice_mode">Voice mode</string>
<string name="settings_voice_mode_desc">Dashboard voice, realtime relay options, providers</string>
<string name="settings_threads">Threads</string>
@@ -863,11 +872,11 @@
<string name="chat_settings_debug">Debug</string>
<string name="chat_settings_show_system_messages_desc">Show the server\'s hidden \"[System: …]\" markers (model / personality changes). Off matches the desktop/TUI.</string>
<string name="chat_settings_streaming_endpoint">Streaming endpoint</string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: picks the best path based on what your server exposes. Currently using: </string>
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: standard connections use Gateway; API-only connections use Direct API. Currently using: </string>
<string name="chat_settings_gateway_suffix"> (live thinking via the dashboard WebSocket)</string>
<string name="chat_settings_chat_completions_suffix"> (chat via /v1/chat/completions)</string>
<string name="chat_settings_runs_suffix"> (chat via explicitly streamed /v1/runs)</string>
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; falls back to SSE per turn when unavailable.</string>
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; when unavailable, this chat stays on Gateway and offers sign-in or retry.</string>
<string name="chat_settings_sessions_desc">Sessions: Hermes-native /api/sessions/{id}/chat/stream.</string>
<string name="chat_settings_chat_desc">Chat: OpenAI-compatible SSE via /v1/chat/completions.</string>
<string name="chat_settings_runs_desc">Runs: use only when your server streams /v1/runs directly.</string>
@@ -1018,14 +1027,14 @@
<string name="active_section_primary_dashboard">Primary Dashboard</string>
<string name="dashboard_gateway_title">Dashboard &amp; Gateway</string>
<string name="current_surface_paths_title">Current paths</string>
<string name="api_fallback_title">API fallback</string>
<string name="api_fallback_title">Direct API</string>
<string name="active_section_in_use">In use</string>
<string name="active_section_available_fallback">Available fallback</string>
<string name="dashboard_gateway_configured">Configured address</string>
<string name="dashboard_gateway_secure_origin">Authenticated Dashboard address</string>
<string name="dashboard_gateway_oidc_explainer">The configured route may be LAN, Tailscale, or public. Hermes owns the OIDC callback; Android does not require a second sign-in address.</string>
<string name="network_routes_title">Network routes</string>
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. API fallback and Relay extensions are optional.</string>
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. Direct API and Relay extensions are optional.</string>
<string name="network_routes_empty">No additional network routes</string>
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
<string name="active_section_using_now">Using now</string>
@@ -1045,7 +1054,7 @@
<string name="active_section_dashboard_unreachable">Not reachable</string>
<string name="active_section_no_fallback_routes">No fallback routes yet</string>
<string name="active_section_no_fallback_routes_desc">Add a LAN, Tailscale, or public address to keep this connection available when networks change.</string>
<string name="active_section_add_api_fallback">Add fallback route</string>
<string name="active_section_add_api_fallback">Add Direct API route</string>
<string name="active_section_security_authentication">Authentication</string>
<string name="active_section_dashboard_session">Dashboard session</string>
<string name="active_section_credential_storage">Credential storage</string>
@@ -1060,7 +1069,7 @@
<string name="active_section_route_selection">Route selection</string>
<string name="active_section_automatic">Automatic</string>
<string name="active_section_api_access">API access</string>
<string name="active_section_optional_api_fallback">Optional direct API fallback</string>
<string name="active_section_optional_api_fallback">Optional Direct API</string>
<string name="active_section_api_not_required">Not required when this connection uses the Hermes Dashboard.</string>
<string name="active_section_where_api_key">Where do I get this?</string>
<string name="active_section_api_key_explainer">API_SERVER_KEY is created on your Hermes server; it is not supplied by this app. Configure it only when you enable the optional API server, which requires a usable key, then enter the same value here.</string>
@@ -3781,7 +3790,7 @@
<string name="whats_new_full_history">View full history</string>
<string name="whats_new_no_notes">No release notes available</string>
<string name="whats_new_title">What\u0027s new</string>
<string name="whats_new_subtitle">Latest release highlights</string>
<string name="whats_new_subtitle">Highlights and complete release details</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Timed screen access expired</string>
<string name="bridge_notification_auto_disabled_body">Screen inspection and control are off after being idle. Other grants are unchanged.</string>
@@ -4246,7 +4255,7 @@
<string name="voice_overlay_notification_body">Microphone access remains available while Hermes is over another app.</string>
<string name="voice_overlay_notification_stop">Stop voice</string>
<string name="conn_info_profile_api_key_title">Profile API key</string>
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex API fallback. Stored encrypted; the connection key is never reused.</string>
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex Direct API route. Stored encrypted; the connection key is never reused.</string>
<string name="conn_info_profile_api_key_stored">A key is stored</string>
<string name="conn_info_profile_api_key_not_stored">No key stored</string>
<string name="conn_info_profile_api_key_save">Save key</string>
@@ -38,6 +38,7 @@ class ConnectionCapabilitiesTest {
assertTrue(connection.capabilities.dashboardGatewayConfigured)
assertTrue(connection.capabilities.apiServerConfigured)
assertTrue(connection.capabilities.relayConfigured)
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
}
@Test
@@ -53,6 +54,20 @@ class ConnectionCapabilitiesTest {
assertTrue(connection.capabilities.dashboardGatewayConfigured)
assertTrue(connection.capabilities.apiChatFallbackAvailable)
assertFalse(connection.capabilities.relayFeaturesAvailable)
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
}
@Test
fun persistedDashboardOwnsAutoChatEvenWhenApiIsAlsoConfigured() {
val connection = connection(
dashboardUrl = "https://hermes.example.com",
apiServerUrl = "https://api.example.com",
relayUrl = "",
)
assertEquals(SessionTransport.GATEWAY, connection.automaticChatTransport)
assertEquals(SessionTransport.GATEWAY, connection.chatTransportForPreference("auto"))
assertEquals(SessionTransport.SSE, connection.chatTransportForPreference("sessions"))
}
@Test
@@ -184,7 +184,7 @@ class ConnectionSecurityTest {
assertEquals(ConnectionSecurityLevel.Tls, result.level)
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "API fallback" }.useState)
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "Direct API" }.useState)
}
@Test
@@ -203,7 +203,7 @@ class ConnectionSecurityTest {
assertEquals(ConnectionSecurityLevel.Plain, result.level)
assertEquals(SurfaceUseState.Unavailable, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "API fallback" }.useState)
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Direct API" }.useState)
}
@Test
@@ -0,0 +1,260 @@
package com.hermesandroid.relay.data
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import java.util.concurrent.atomic.AtomicLong
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class SupervisedParentAuthStoreTest {
@Test
fun `new credential policy accepts strong pins and passwords`() {
assertFalse(SupervisedParentAuthStore.validateNewSecret("12345".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertTrue(SupervisedParentAuthStore.validateNewSecret("123456".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("1234567".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("short".toCharArray(), SupervisedParentCredentialType.Password).valid)
assertTrue(SupervisedParentAuthStore.validateNewSecret("long passphrase".toCharArray(), SupervisedParentCredentialType.Password).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret(" ".repeat(8).toCharArray(), SupervisedParentCredentialType.Password).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("x".repeat(65).toCharArray(), SupervisedParentCredentialType.Password).valid)
}
@Test
fun `enrollment stores only salted PBKDF2 verifiers and returns six word recovery phrase`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
val enrollment = store.enroll(
"correct horse".toCharArray(),
SupervisedParentCredentialType.Password,
).getOrThrow()
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
assertEquals(6, enrollment.recoveryPhrase.split('-').size)
assertEquals(6, enrollment.recoveryPhrase.split('-').distinct().size)
assertTrue(raw.contains("PBKDF2WithHmacSHA256"))
assertTrue(raw.contains("\"iterations\":1"))
assertFalse(raw.contains("correct horse"))
assertFalse(raw.contains(enrollment.recoveryPhrase))
assertTrue(raw.contains("\"credentialType\":\"Password\""))
assertTrue(raw.contains("\"recoveryFormat\":\"WordPhrase\""))
val salts = Regex("\"(?:parentSalt|recoverySalt)\":\"([^\"]+)\"")
.findAll(raw).map { it.groupValues[1] }.toList()
assertEquals(2, salts.size)
assertNotEquals(salts[0], salts[1])
}
@Test
fun `production enrollment records 310000 rounds`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = SupervisedParentAuthStore.forTesting(
dataStore = dataStore,
iterations = 310_000,
)
store.enroll("production-strength".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(
dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting]
.orEmpty().contains("\"iterations\":310000"),
)
}
@Test
fun `verification is fail closed when missing or corrupt`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
assertEquals(SupervisedParentAuthStatus.Missing, store.statusFlow.first())
assertEquals(SupervisedParentAuthResult.Missing, store.verify("anything".toCharArray()))
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "not-json" }
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
assertEquals(SupervisedParentAuthResult.Corrupt, store.verify("anything".toCharArray()))
}
@Test
fun `unsupported or weakened records fail closed`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
dataStore.edit {
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"version\":1", "\"version\":2")
}
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
dataStore.edit {
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"iterations\":1", "\"iterations\":0")
}
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
}
@Test
fun `records created before credential type selection remain verifiable`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val current = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
val legacy = current
.replace(Regex(",\"credentialType\":\"Password\""), "")
.replace(Regex(",\"recoveryFormat\":\"WordPhrase\""), "")
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = legacy }
assertEquals(SupervisedParentCredentialType.Legacy, store.credentialTypeFlow.first())
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
}
@Test
fun `enroll cannot replace an existing or corrupt credential`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("first password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
assertEquals(SupervisedParentAuthResult.Success, store.verify("first password".toCharArray()))
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "corrupt" }
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
}
@Test
fun `authenticated clear removes credential and disables policies without losing settings`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val authStore = fastStore(dataStore)
val policyStore = SupervisedModeStore.forTesting(dataStore)
authStore.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
policyStore.setPolicy(
"connection-a",
SupervisedModePolicy(
enabled = true,
pinnedProfileName = "willow",
capabilities = SupervisedCapabilities(attachments = false, voice = true),
),
)
policyStore.setPolicy(
"connection-b",
SupervisedModePolicy(
enabled = true,
pinnedProfileName = "coder",
visibility = SupervisedVisibility(showTimestamps = true),
),
)
val beforeA = policyStore.policyFlow("connection-a").first()
val beforeB = policyStore.policyFlow("connection-b").first()
authStore.clearCredentialAndDisablePolicies().getOrThrow()
assertEquals(SupervisedParentAuthStatus.Missing, authStore.statusFlow.first())
assertEquals(beforeA.copy(enabled = false), policyStore.policyFlow("connection-a").first())
assertEquals(beforeB.copy(enabled = false), policyStore.policyFlow("connection-b").first())
}
@Test
fun `failed attempts persist across store recreation and backoff expires by clock`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val clock = AtomicLong(1_000L)
var store = fastStore(dataStore, clock)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
repeat(4) {
assertTrue(store.verify("wrong password".toCharArray()) is SupervisedParentAuthResult.Invalid)
}
val fifth = store.verify("wrong password".toCharArray())
assertEquals(SupervisedParentAuthResult.Throttled(30_000L), fifth)
store = fastStore(dataStore, clock)
assertEquals(
SupervisedParentAuthResult.Throttled(30_000L),
store.verify("parent password".toCharArray()),
)
clock.addAndGet(30_001L)
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
}
@Test
fun `concurrent store instances preserve the capped failure sequence`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val stores = List(5) { fastStore(dataStore) }
stores.first().enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val results = stores.map { store -> async { store.verify("wrong password".toCharArray()) } }.awaitAll()
assertEquals(4, results.count { it is SupervisedParentAuthResult.Invalid })
assertEquals(1, results.count { it == SupervisedParentAuthResult.Throttled(30_000L) })
}
@Test
fun `change requires the current credential and rotates recovery`() = runTest {
val store = fastStore(InMemoryParentAuthDataStore())
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(store.change("wrong".toCharArray(), "new password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
assertEquals(SupervisedParentAuthResult.Success, store.verify("old password".toCharArray()))
val replacement = store.change(
"old password".toCharArray(),
"654321".toCharArray(),
SupervisedParentCredentialType.Pin,
).getOrThrow()
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
assertTrue(store.verify("old password".toCharArray()) is SupervisedParentAuthResult.Invalid)
assertEquals(SupervisedParentAuthResult.Success, store.verify("654321".toCharArray()))
assertEquals(SupervisedParentCredentialType.Pin, store.credentialTypeFlow.first())
}
@Test
fun `recovery is normalized one time and rotates both secrets`() = runTest {
val store = fastStore(InMemoryParentAuthDataStore())
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val lowerSpaced = original.recoveryPhrase.uppercase().replace("-", " ").toCharArray()
val replacement = store.resetWithRecoveryPhrase(
lowerSpaced,
"new password".toCharArray(),
SupervisedParentCredentialType.Password,
).getOrThrow()
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
assertEquals(SupervisedParentAuthResult.Success, store.verify("new password".toCharArray()))
assertTrue(
store.resetWithRecoveryPhrase(
original.recoveryPhrase.toCharArray(),
"another password".toCharArray(),
SupervisedParentCredentialType.Password,
)
.isFailure,
)
}
private fun fastStore(
dataStore: DataStore<Preferences>,
clock: AtomicLong = AtomicLong(1_000L),
): SupervisedParentAuthStore = SupervisedParentAuthStore.forTesting(
dataStore = dataStore,
iterations = 1,
minimumAcceptedIterations = 1,
nowMillis = clock::get,
)
}
private class InMemoryParentAuthDataStore : DataStore<Preferences> {
private val state = MutableStateFlow(emptyPreferences())
override val data: Flow<Preferences> = state
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
val updated = transform(state.value)
state.value = updated
return updated
}
}
@@ -1530,6 +1530,86 @@ class ChatHandlerTest {
assertTrue(handler.messages.value.single().attachments.isEmpty())
}
@Test
fun loadMessageHistory_preservesCompletedGeneratedImageUntilMarkerPersists() {
handler.addPlaceholderMessage(
ChatMessage(
id = "assistant-live-image",
role = MessageRole.ASSISTANT,
content = "Here is the generated image.",
timestamp = 1L,
attachments = listOf(
Attachment(
contentType = "image/png",
content = "",
fileName = "generated.png",
relayToken = "/tmp/generated.png",
state = AttachmentState.LOADED,
),
),
toolCalls = listOf(
ToolCall(
id = "image-call",
name = "willow_create_image",
args = null,
result = "success",
success = true,
isComplete = true,
),
),
),
)
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-server-image",
role = "assistant",
content = JsonPrimitive("Here is the generated image."),
),
),
)
val message = handler.messages.value.single()
assertEquals("assistant-server-image", message.id)
assertEquals("assistant-live-image", message.uiKey)
assertEquals(1, message.attachments.size)
assertEquals("generated.png", message.attachments.single().fileName)
}
@Test
fun loadMessageHistory_doesNotCarryUnownedAssistantInboundImage() {
handler.addPlaceholderMessage(
ChatMessage(
id = "assistant-live-generic",
role = MessageRole.ASSISTANT,
content = "A generic fetched image.",
timestamp = 1L,
attachments = listOf(
Attachment(
contentType = "image/png",
content = "",
fileName = "generic.png",
relayToken = "generic-token",
state = AttachmentState.LOADED,
),
),
),
)
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-server-generic",
role = "assistant",
content = JsonPrimitive("A generic fetched image."),
),
),
)
assertTrue(handler.messages.value.single().attachments.isEmpty())
}
@Test
fun loadMessageHistory_consumesOutboundAttachmentOncePerDuplicateContent() {
// Two identical-text sends, only the first with an attachment: the
@@ -562,17 +562,24 @@ class DashboardApiClientTest {
}
@Test
fun signInRequiredClassifierAcceptsNoCookieButRejectsForbidden() {
fun signInRequiredClassifierAcceptsEveryUnauthorizedShapeButRejectsForbidden() {
val noCookie = DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"no_cookie\",\"detail\":\"Unauthorized\"}",
)
val expired = DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"session_expired\",\"detail\":\"invalid_or_expired_session\"}",
)
val generic = DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized")
val forbidden = DashboardHttpException(
403,
"Session failed - HTTP 403: forbidden",
)
assertTrue(noCookie.isDashboardSignInRequiredFailure())
assertTrue(expired.isDashboardSignInRequiredFailure())
assertTrue(generic.isDashboardSignInRequiredFailure())
assertFalse(forbidden.isDashboardSignInRequiredFailure())
}
@@ -803,6 +803,7 @@ class GatewayChatClientTest {
rpcTimeoutMs: Long = 15_000L,
promptSubmitTimeoutMs: Long = 1_800_000L,
turnIdleTimeoutMs: Long = 180_000L,
compactingTimeoutMs: Long = 600_000L,
callbackDispatcher: (block: () -> Unit) -> Unit = { it() },
ticketTimeoutMs: Long = 8_000L,
) = GatewayChatClient(
@@ -824,6 +825,7 @@ class GatewayChatClientTest {
rpcTimeoutMs = rpcTimeoutMs,
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
turnIdleTimeoutMs = turnIdleTimeoutMs,
compactingTimeoutMs = compactingTimeoutMs,
)
private fun awaitCondition(
@@ -846,6 +848,7 @@ class GatewayChatClientTest {
rpcTimeoutMs: Long = 15_000L,
promptSubmitTimeoutMs: Long = 1_800_000L,
turnIdleTimeoutMs: Long = 180_000L,
compactingTimeoutMs: Long = 600_000L,
ticketTimeoutMs: Long = 8_000L,
) {
client.shutdown()
@@ -854,6 +857,7 @@ class GatewayChatClientTest {
rpcTimeoutMs = rpcTimeoutMs,
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
turnIdleTimeoutMs = turnIdleTimeoutMs,
compactingTimeoutMs = compactingTimeoutMs,
ticketTimeoutMs = ticketTimeoutMs,
)
}
@@ -4738,6 +4742,85 @@ class GatewayChatClientTest {
)
}
@Test
fun `compacting status extends watchdog until a later completion`() {
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 1_000L)
val r = Recorder()
client.sendTurn(null, "compact once", null, r.callbacks) { r.preflightFailures += it }
val serverWs = harness.awaitServerSocket()
harness.awaitRpc("prompt.submit")
serverWs.send(
harness.eventFrame(
"status.update",
buildJsonObject { put("kind", "compacting") },
"live-1",
),
)
Thread.sleep(500)
assertTrue("normal idle watchdog fired during compaction: ${r.errors}", r.errors.isEmpty())
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
serverWs.send(
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
)
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
assertTrue(r.errors.isEmpty())
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `compacting heartbeats rearm watchdog beyond one compaction lease`() {
rebuildClient(turnIdleTimeoutMs = 200L, compactingTimeoutMs = 500L)
val r = Recorder()
client.sendTurn(null, "compact with heartbeats", null, r.callbacks) { r.preflightFailures += it }
val serverWs = harness.awaitServerSocket()
harness.awaitRpc("prompt.submit")
repeat(3) {
serverWs.send(
harness.eventFrame(
"status.update",
buildJsonObject { put("kind", "compacting") },
"live-1",
),
)
Thread.sleep(300)
}
assertTrue("compaction lease was not rearmed: ${r.errors}", r.errors.isEmpty())
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
serverWs.send(
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
)
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
assertTrue(r.errors.isEmpty())
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `non compacting status keeps the ordinary watchdog`() {
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 2_000L)
val r = Recorder()
client.sendTurn(null, "ordinary status", null, r.callbacks) { r.preflightFailures += it }
val serverWs = harness.awaitServerSocket()
harness.awaitRpc("prompt.submit")
serverWs.send(
harness.eventFrame(
"status.update",
buildJsonObject { put("kind", "process") },
"live-1",
),
)
assertTrue("ordinary watchdog never fired", r.completeLatch.await(5, TimeUnit.SECONDS))
assertTrue("expected a stream error from the watchdog", r.errors.isNotEmpty())
assertTrue(r.preflightFailures.isEmpty())
harness.awaitRpc("session.interrupt")
}
@Test
fun `idle watchdog fires when events stop flowing`() {
rebuildClient(turnIdleTimeoutMs = 500L)
@@ -5,9 +5,8 @@ import org.junit.Test
/**
* Resolution matrix for [resolveStreamingEndpointPreference] — the gateway
* tier sits above the capability-preferred SSE endpoint for "auto". An
* unresolved cold-start probe remains on Gateway until it produces a
* definitive fallback verdict.
* tier is a stable owner for standard "auto" conversations. API capability
* ordering applies only to true API-only compatibility connections.
*/
class GatewayEndpointResolutionTest {
@@ -44,28 +43,63 @@ class GatewayEndpointResolutionTest {
}
@Test
fun `auto falls back after a definitive non-ready verdict`() {
fun `standard auto remains gateway owned after auth expiry or outage`() {
listOf(
GatewayAvailability.SignInRequired,
GatewayAvailability.Unreachable,
GatewayAvailability.Unsupported,
).forEach { availability ->
assertEquals(
"expected SSE fallback for $availability",
"sessions",
"expected Gateway affinity for $availability",
"gateway",
resolveStreamingEndpointPreference("auto", availability, fullCaps),
)
}
}
@Test
fun `auto fallback respects capability ordering`() {
fun `API-only auto respects capability ordering`() {
assertEquals(
"sessions",
resolveStreamingEndpointPreference(
"auto",
GatewayAvailability.SignInRequired,
fullCaps,
gatewayOwned = false,
),
)
assertEquals(
"completions",
resolveStreamingEndpointPreference(
"auto",
GatewayAvailability.SignInRequired,
portableOnlyCaps,
gatewayOwned = false,
),
)
}
@Test
fun `standard auto does not consult API health when gateway is unavailable`() {
assertEquals(
"gateway",
resolveStreamingEndpointPreference(
"auto",
GatewayAvailability.Unreachable,
ServerCapabilities.DISCONNECTED,
gatewayOwned = true,
),
)
}
@Test
fun `manual API selection remains explicit compatibility mode`() {
assertEquals(
"sessions",
resolveStreamingEndpointPreference(
"sessions",
GatewayAvailability.SignInRequired,
fullCaps,
),
)
}
@@ -19,13 +19,17 @@ import org.robolectric.annotation.GraphicsMode
class ChangelogHistoryScreenshotTest {
@get:Rule val compose = createComposeRule()
@Test fun latestReleaseIsCuratedAndInstalled() {
@Test fun latestReleaseShowsHighlightsAndCompleteDetails() {
compose.setContent {
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
ChangelogScreen(onClose = {})
}
}
compose.onNodeWithText("Supervised Mode").assertExists()
compose.onNodeWithText("v1.14.0 — Connections, delegated work, Git, and voice").assertExists()
compose.onNodeWithText("Highlights").assertExists()
compose.onNodeWithText("Fixed").assertExists()
compose.onNodeWithText("Wake-word detection starts reliably").assertExists()
compose.onNodeWithText("Compatibility").assertExists()
compose.onNodeWithText("Installed").assertExists()
compose.onRoot().captureRoboImage("build/ui-regression/changelog-history.png")
}
@@ -0,0 +1,75 @@
package com.hermesandroid.relay.screenshots
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.takahirom.roborazzi.captureRoboImage
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.ui.screens.CredentialChoiceScreen
import com.hermesandroid.relay.ui.screens.ParentAuthScreenSurface
import com.hermesandroid.relay.ui.screens.PasswordSetupScreen
import com.hermesandroid.relay.ui.screens.PinSetupScreen
import com.hermesandroid.relay.ui.screens.SupervisedParentRecoveryCodeContent
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(qualifiers = "w400dp-h900dp-432dpi")
class SupervisedParentAuthFlowScreenshotTest {
@get:Rule
val compose = createComposeRule()
@Test
fun credentialChoice() {
render("build/visual-qa/supervised-parent-choice.png", 1 to 2) {
CredentialChoiceScreen(
title = "Choose parent access",
subtitle = "Pick one way to unlock parent settings. You can change it later.",
onSelected = {},
)
}
}
@Test
fun pinSetup() {
render("build/visual-qa/supervised-parent-pin.png", 2 to 2) {
PinSetupScreen(busy = false, error = null, onComplete = {})
}
}
@Test
fun passwordSetup() {
render("build/visual-qa/supervised-parent-password.png", 2 to 2) {
PasswordSetupScreen(busy = false, error = null, onComplete = {})
}
}
@Test
fun recoveryPhrase() {
render("build/visual-qa/supervised-parent-recovery.png", 3 to 3) {
SupervisedParentRecoveryCodeContent(
enrollment = SupervisedParentEnrollment(
"maple-river-lantern-copper-sparrow-moon",
),
)
}
}
private fun render(
path: String,
step: Pair<Int, Int>,
content: @androidx.compose.runtime.Composable () -> Unit,
) {
compose.setContent {
HermesRelayTheme(themePreference = "dark") {
ParentAuthScreenSurface(step = step, onBack = {}, content = content)
}
}
compose.onRoot().captureRoboImage(path)
}
}
@@ -61,9 +61,11 @@ class WhatsNewToastScreenshotTest {
}
}
}
compose.onNodeWithText("Supervised Mode").assertExists()
compose.onNodeWithText("Also: 2 fixes").assertExists()
compose.onNodeWithText("Accurate activity, safer return…").assertExists()
compose.onNodeWithText("Connections, delegated work, Git, and voice").assertExists()
compose.onNodeWithText("Also: 2 improvements · 10 fixes").assertExists()
compose.onNodeWithText(
"Release notes stay out of your way, Chat uses one consistent presentation…",
).assertExists()
compose.onNodeWithText("View all").assertExists()
compose.onNodeWithContentDescription("Close").assertExists()
compose.onRoot().captureRoboImage("build/ui-regression/whats-new-toast-large-text.png")
@@ -84,7 +86,7 @@ class WhatsNewToastScreenshotTest {
}
}
compose.onNodeWithText("Supervised Mode").performClick()
compose.onNodeWithText("Connections, delegated work, Git, and voice").performClick()
expanded = false
compose.onNodeWithText("View all").performClick()
compose.onNodeWithContentDescription("Close").performClick()
@@ -106,7 +108,8 @@ class WhatsNewToastScreenshotTest {
}
}
compose.mainClock.advanceTimeBy(300L)
compose.onNodeWithText("Supervised Mode").performTouchInput { swipeLeft(durationMillis = 300L) }
compose.onNodeWithText("Connections, delegated work, Git, and voice")
.performTouchInput { swipeLeft(durationMillis = 300L) }
compose.mainClock.advanceTimeBy(300L)
assertTrue(dismissed)
@@ -196,6 +196,39 @@ class RelayAppStatusTest {
assertEquals(ChatRuntimeStatus.Connecting, status)
}
@Test
fun `dashboard sign-out is not masked by a reachable sibling API`() {
val status = resolveAppChatRuntimeStatus(
connection = connection(
dashboardUrl = "https://host.ts.net:9119",
apiServerUrl = "https://host.ts.net:8642",
),
gatewayAvailability = GatewayAvailability.SignInRequired,
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
streamingEndpoint = "sessions",
conversationOwner = com.hermesandroid.relay.data.SessionTransport.GATEWAY,
)
assertEquals(ChatRuntimeStatus.Unavailable, status)
}
@Test
fun `legacy API-only connection remains connected compatibility chat`() {
val status = resolveAppChatRuntimeStatus(
connection = connection(
dashboardUrl = null,
apiServerUrl = "https://host.ts.net:8642",
),
gatewayAvailability = GatewayAvailability.Unreachable,
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
)
assertEquals(
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
status,
)
}
@Test
fun `committed pair target stays ready while public inventory catches up`() {
assertTrue(
@@ -392,7 +425,7 @@ class RelayAppStatusTest {
}
private fun connected(path: ChatTransportPath) =
ChatRuntimeStatus.Connected(transport = path, fallback = path == ChatTransportPath.ApiSse)
ChatRuntimeStatus.Connected(transport = path, fallback = false)
private fun connection(
dashboardUrl: String? = null,
@@ -40,32 +40,50 @@ class SupervisedNavigationPolicyTest {
@Test fun `parent access or ordinary mode permits add gateway`() {
assertTrue(mayStartAddConnection(supervisedEnabled = true, parentAccessUnlocked = true))
assertTrue(mayStartAddConnection(supervisedEnabled = false, parentAccessUnlocked = false))
assertFalse(
mayStartAddConnection(
supervisedEnabled = false,
parentAccessUnlocked = true,
activeTargetId = "already-started",
),
)
}
@Test fun `locked add gateway action has no side effects`() {
var navigated = false
var prepared = false
val started = runAddConnectionAction(
@Test fun `locked add gateway action performs no allocation or side effects`() {
val actions = mutableListOf<String>()
val target = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = false,
navigateToPair = { navigated = true },
prepareConnection = { prepared = true },
)
assertFalse(started)
assertFalse(navigated)
assertFalse(prepared)
}
@Test fun `allowed add gateway action navigates before preparation`() {
val actions = mutableListOf<String>()
val started = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = true,
activeTargetId = null,
allocateTarget = { actions += "allocate"; "target" },
recordTarget = { actions += "record" },
navigateToPair = { actions += "navigate" },
prepareConnection = { actions += "prepare" },
)
assertTrue(started)
assertTrue(actions == listOf("navigate", "prepare"))
assertTrue(target == null)
assertTrue(actions.isEmpty())
}
@Test fun `allowed add gateway action records target before navigation and preparation`() {
val actions = mutableListOf<String>()
val target = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = true,
activeTargetId = null,
allocateTarget = { actions += "allocate"; "target" },
recordTarget = { actions += "record:$it" },
navigateToPair = { actions += "navigate:$it" },
prepareConnection = { actions += "prepare:$it" },
)
assertTrue(target == "target")
assertTrue(
actions == listOf(
"allocate",
"record:target",
"navigate:target",
"prepare:target",
),
)
}
@Test fun `supervised redirect waits until the navigation graph has a route`() {
@@ -75,6 +93,7 @@ class SupervisedNavigationPolicyTest {
assertTrue(isSupervisedRouteContentAllowed(true, false, Screen.Chat.route))
assertTrue(shouldRedirectSupervisedRoute(true, false, Screen.AdvancedSettings.route))
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.AdvancedSettings.route))
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.ConnectionsSettings.route))
assertFalse(shouldRedirectSupervisedRoute(true, true, Screen.AdvancedSettings.route))
assertTrue(isSupervisedRouteContentAllowed(true, true, Screen.AdvancedSettings.route))
}
@@ -153,25 +172,23 @@ class SupervisedNavigationPolicyTest {
)
}
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
@Test fun `first enable requires configured policy and successful app parent credential`() {
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
assertFalse(
mayEnableSupervisedMode(
configured,
deviceSecure = false,
deviceCredentialConfirmed = true,
parentCredentialConfirmed = false,
),
)
assertFalse(
mayEnableSupervisedMode(
configured,
deviceSecure = true,
deviceCredentialConfirmed = false,
parentCredentialConfirmed = false,
),
)
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
assertTrue(mayEnableSupervisedMode(configured, true, true))
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true))
assertTrue(mayEnableSupervisedMode(configured, true))
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true))
}
}
@@ -37,26 +37,25 @@ class ChangelogParserTest {
}
@Test
fun parsesCuratedHighlightAndImprovements() {
fun parsesCompleteReleaseAndDerivesToastDigest() {
val raw = """
{
"schema": 2,
"schema": 3,
"versions": [
{
"version": "1.2.0",
"title": "A useful release",
"date": "2026-06-20",
"highlight": {
"title": "The main reason to care",
"summary": "A plain-language explanation.",
"bullets": ["a", "b", "c"]
},
"improvements": ["d", "e"],
"toastDigest": {
"additionalFeatureCount": 1,
"fixCount": 2,
"preview": ["Secondary feature", "Important fix"]
},
"summary": "A plain-language explanation.",
"changes": [
{"id": "new-one", "kind": "added", "title": "New one",
"summary": "Use the new thing.", "highlight": true},
{"id": "better-one", "kind": "improved", "title": "Better one",
"summary": "The old thing is easier."},
{"id": "fixed-one", "kind": "fixed", "title": "Fixed one",
"summary": "The broken thing works."}
],
"compatibility": ["Existing connections keep working."],
"playNotes": "Concise Play copy."
}
]
@@ -64,17 +63,41 @@ class ChangelogParserTest {
""".trimIndent()
val entry = ChangelogStore.parse(raw).versions.single()
val digest = entry.resolvedToastDigest()
assertEquals("The main reason to care", entry.highlight?.title)
assertEquals("A plain-language explanation.", entry.highlight?.summary)
assertEquals(listOf("a", "b", "c"), entry.highlight?.bullets)
assertEquals(listOf("d", "e"), entry.improvements)
assertEquals(1, entry.toastDigest?.additionalFeatureCount)
assertEquals(2, entry.toastDigest?.fixCount)
assertEquals(listOf("Secondary feature", "Important fix"), entry.toastDigest?.preview)
assertEquals("A plain-language explanation.", entry.summary)
assertEquals(listOf("New one"), entry.highlightedChanges().map { it.title })
assertEquals(0, digest?.additionalFeatureCount)
assertEquals(1, digest?.improvementCount)
assertEquals(1, digest?.fixCount)
assertEquals(listOf("Better one", "Fixed one"), digest?.preview)
assertEquals(listOf("Existing connections keep working."), entry.compatibility)
assertEquals("Concise Play copy.", entry.playNotes)
assertEquals("v1.2.0 · 2026-06-20", entry.versionLine())
assertEquals(listOf("The main reason to care", "Also improved"), entry.toGroups().map { it.header })
assertEquals(
listOf("Highlights", "Improved", "Fixed", "Compatibility"),
entry.toGroups().map { it.header },
)
assertEquals(3, entry.toGroups().sumOf { it.bullets.size } - entry.compatibility.size)
}
@Test
fun completeReleaseRendersEveryChangeOnce() {
val entry = ChangelogVersion(
version = "1.2.0",
title = "Complete notes",
summary = "Everything users need to know.",
changes = listOf(
ChangelogChange("a", CHANGE_KIND_ADDED, "First", "First detail", highlight = true),
ChangelogChange("b", CHANGE_KIND_FIXED, "Second", "Second detail"),
),
)
val rendered = entry.toGroups().flatMap { it.bullets }
assertEquals(2, rendered.size)
assertEquals(1, rendered.count { it.startsWith("First") })
assertEquals(1, rendered.count { it.startsWith("Second") })
}
@Test
@@ -26,6 +26,7 @@ class ImageGenerationPlaceholderTest {
)
assertTrue(active.showsImageGenerationPlaceholder())
assertTrue(active.copy(name = "willow_create_image").showsImageGenerationPlaceholder())
assertFalse(active.copy(isComplete = true, success = true).showsImageGenerationPlaceholder())
assertFalse(active.copy(name = "video_generate").showsImageGenerationPlaceholder())
}
@@ -28,6 +28,7 @@ class ToolActivityRunTest {
val standalone = listOf(
call("risk", "read_file").copy(outputRisk = "high"),
call("image", "image_generate"),
call("profile-image", "willow_create_image"),
call("approval", "request_user_input"),
call("delegate", "delegate_task"),
)
@@ -0,0 +1,233 @@
package com.hermesandroid.relay.ui.screens
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.BotGatewayRoute
import com.hermesandroid.relay.data.BotGatewayRouteKey
import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.viewmodel.ChatViewModel
import java.util.concurrent.CopyOnWriteArrayList
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.JsonPrimitive
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(sdk = [35], qualifiers = "w390dp-h844dp-432dpi")
class BotChatScreenBindingTest {
@get:Rule
val compose = createComposeRule()
private val resources = CopyOnWriteArrayList<ScreenResources>()
@After
fun tearDown() {
resources.forEach(ScreenResources::close)
}
@Test
fun fastHistoryPublishedDuringInitialBindRendersWithoutNavigation() {
val screen = resources("research")
val handler = ChatHandler()
compose.mainClock.autoAdvance = false
compose.setContent {
MaterialTheme {
screen.content(
handler = handler,
historyLoader = { _, _, _ ->
Result.success(history(screen.sessionId, FAST_HISTORY))
},
)
}
}
compose.mainClock.advanceTimeByFrame()
compose.waitUntil(5_000) { handler.messages.value.singleOrNull()?.content == FAST_HISTORY }
compose.mainClock.autoAdvance = true
compose.waitForIdle()
compose.onNodeWithText(FAST_HISTORY).assertIsDisplayed()
compose.runOnIdle { handler.onTextDelta("live-tail", LIVE_TAIL) }
compose.onNodeWithText(LIVE_TAIL).assertIsDisplayed()
compose.runOnIdle { handler.onStreamError(HANDLER_ERROR) }
compose.onNodeWithText(HANDLER_ERROR).assertIsDisplayed()
}
@Test
fun delayedHistoryAfterCompositionRendersFromTheSameHandler() {
val screen = resources("builder")
val handler = ChatHandler()
val releaseHistory = CompletableDeferred<Unit>()
compose.setContent {
MaterialTheme {
screen.content(
handler = handler,
historyLoader = { _, _, _ ->
releaseHistory.await()
Result.success(history(screen.sessionId, DELAYED_HISTORY))
},
)
}
}
compose.waitUntil(5_000) { screen.viewModel.isLoadingHistory.value }
compose.onNodeWithText(DELAYED_HISTORY).assertDoesNotExist()
releaseHistory.complete(Unit)
compose.waitUntil(5_000) { handler.messages.value.isNotEmpty() }
compose.onNodeWithText(DELAYED_HISTORY).assertIsDisplayed()
}
@Test
fun replacementHandlerRejectsLateHistoryAndOldHandlerPublications() {
val screen = resources("operator")
val firstHandler = ChatHandler()
val secondHandler = ChatHandler()
val releaseFirstHistory = CompletableDeferred<Unit>()
val target = mutableStateOf(
Target(
revision = 0,
handler = firstHandler,
loader = { _, _, _ ->
releaseFirstHistory.await()
Result.success(history(screen.sessionId, OLD_HISTORY))
},
),
)
compose.setContent {
val current = target.value
key(current.revision) {
MaterialTheme {
screen.content(current.handler, current.loader)
}
}
}
compose.waitUntil(5_000) { screen.viewModel.isLoadingHistory.value }
compose.runOnIdle {
target.value = Target(
revision = 1,
handler = secondHandler,
loader = { _, _, _ -> Result.success(history(screen.sessionId, NEW_HISTORY)) },
)
}
compose.waitForIdle()
compose.runOnIdle { assertSame(secondHandler, screen.viewModel.boundHandler) }
compose.waitUntil(5_000) { secondHandler.messages.value.singleOrNull()?.content == NEW_HISTORY }
compose.onNodeWithText(NEW_HISTORY).assertIsDisplayed()
releaseFirstHistory.complete(Unit)
compose.waitForIdle()
assertEquals(emptyList<String>(), firstHandler.messages.value.map { it.content })
compose.runOnIdle { firstHandler.onTextDelta("old-tail", OLD_TAIL) }
compose.waitForIdle()
compose.onNodeWithText(OLD_HISTORY).assertDoesNotExist()
compose.onNodeWithText(OLD_TAIL).assertDoesNotExist()
assertEquals(listOf(OLD_TAIL), firstHandler.messages.value.map { it.content })
assertEquals(listOf(NEW_HISTORY), secondHandler.messages.value.map { it.content })
}
private fun resources(profileName: String): ScreenResources = ScreenResources(profileName).also {
resources += it
}
private fun history(sessionId: String, text: String) = listOf(
MessageItem(
id = "history-$sessionId",
sessionId = sessionId,
role = "assistant",
content = JsonPrimitive(text),
timestamp = 1.0,
finishReason = "stop",
),
)
private inner class ScreenResources(profileName: String) {
val route = BotGatewayRoute(
key = BotGatewayRouteKey("gateway-$profileName", profileName),
connectionLabel = "Fixture gateway",
)
val bot = BotRosterEntry(
profile = Profile(
name = profileName,
model = "fixture-model",
description = "Fixture profile",
),
displayName = profileName.replaceFirstChar(Char::uppercase),
route = route,
)
val sessionId = "fixture-$profileName-session"
val viewModel = ChatViewModel()
private val gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val dashboardClient = DashboardApiClient("http://127.0.0.1:1")
private val gatewayClient = GatewayChatClient(
initialDashboardClient = dashboardClient,
fixedSessionProfile = profileName,
scope = gatewayScope,
reconnectJitterUnit = { 0.0 },
)
@androidx.compose.runtime.Composable
fun content(handler: ChatHandler, historyLoader: BotChatHistoryLoader) {
BotChatScreen(
route = route,
bot = bot,
sessionId = sessionId,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = viewModel,
onBack = {},
handlerFactory = { handler },
historyLoader = historyLoader,
profileIconFlow = { _, _ -> MutableStateFlow(null) },
)
}
fun close() {
viewModel.updateGatewayClient(null)
gatewayClient.shutdown()
gatewayScope.cancel()
dashboardClient.shutdown()
}
}
private data class Target(
val revision: Int,
val handler: ChatHandler,
val loader: BotChatHistoryLoader,
)
private companion object {
const val FAST_HISTORY = "History loaded before the next frame."
const val DELAYED_HISTORY = "History loaded after composition."
const val LIVE_TAIL = "Live tail from the owned handler."
const val HANDLER_ERROR = "Owned handler error"
const val OLD_HISTORY = "Late history from the old route."
const val OLD_TAIL = "Old handler live tail."
const val NEW_HISTORY = "History from the replacement route."
}
}
@@ -0,0 +1,94 @@
package com.hermesandroid.relay.ui.screens
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.SupervisedParentCredentialType
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(qualifiers = "w400dp-h900dp-432dpi")
class SupervisedParentAuthDialogsTest {
@get:Rule
val compose = createComposeRule()
@Test
fun `choice presents mutually exclusive pin and password routes`() {
var selected: SupervisedParentCredentialType? = null
compose.setContent {
HermesRelayTheme {
CredentialChoiceScreen("Choose parent access", "Pick one.") { selected = it }
}
}
compose.onNodeWithText("Use a PIN").assertIsDisplayed().performClick()
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Pin, selected) }
compose.onNodeWithText("Use a password").assertIsDisplayed().performClick()
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Password, selected) }
}
@Test
fun `pin auth uses six positions and a dedicated numeric keypad`() {
var submitted: String? = null
compose.setContent {
HermesRelayTheme {
PinEntryScreen("Parent PIN", "Enter your 6-digit PIN.", false, null, { submitted = it })
}
}
(0..9).forEach { compose.onNodeWithText(it.toString()).assertIsDisplayed() }
compose.onNodeWithContentDescription("Delete digit").assertIsDisplayed()
(1..6).forEach { compose.onNodeWithText(it.toString()).performClick() }
compose.runOnIdle { assertEquals("123456", submitted) }
}
@Test
fun `password setup uses distinct password fields and visibility controls`() {
compose.setContent {
HermesRelayTheme { PasswordSetupScreen(false, null, {}) }
}
compose.onNodeWithText("Create a parent password").assertIsDisplayed()
compose.onNodeWithText("Password").assertIsDisplayed()
compose.onNodeWithText("Confirm password").assertIsDisplayed()
compose.onAllNodesWithContentDescription("Show password").assertCountEquals(2)
}
@Test
fun `recovery phrase handoff exposes sharing copy and cleanup guidance`() {
var shares = 0
var copies = 0
compose.setContent {
HermesRelayTheme {
SupervisedParentRecoveryCodeContent(
SupervisedParentEnrollment("maple-river-lantern-copper-sparrow-moon"),
onShare = { shares += 1 },
onCopy = { copies += 1 },
)
}
}
compose.onNodeWithText("maple-river-lantern", substring = true).assertIsDisplayed()
compose.onNodeWithText("copper-sparrow-moon", substring = true).assertIsDisplayed()
compose.onNodeWithText("Share").assertIsDisplayed()
compose.onNodeWithText("Copy phrase").assertIsDisplayed()
compose.onNodeWithText("delete the message or saved copy", substring = true).assertIsDisplayed()
compose.onNodeWithText("Share").performClick()
compose.onNodeWithText("Copy phrase").performClick()
compose.runOnIdle {
assertEquals(1, shares)
assertEquals(1, copies)
}
}
}
@@ -1,7 +1,9 @@
package com.hermesandroid.relay.viewmodel
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.SessionTransport
import com.hermesandroid.relay.network.upstream.GatewayAvailability
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -38,12 +40,54 @@ class ChatReadinessTest {
}
@Test
fun `ready with reachable API when Gateway is unavailable`() {
fun `ready with reachable API for API-only owner`() {
assertTrue(
isChatTransportReady(
apiClientPresent = true,
apiReachable = true,
gatewayAvailability = GatewayAvailability.Unreachable,
chatOwner = SessionTransport.SSE,
),
)
}
@Test
fun `reachable API cannot make a Gateway-owned chat ready`() {
assertFalse(
isChatTransportReady(
apiClientPresent = true,
apiReachable = true,
gatewayAvailability = GatewayAvailability.SignInRequired,
chatOwner = SessionTransport.GATEWAY,
),
)
}
@Test
fun `eager status owner resolves from backing preference before public alias`() {
val connection = Connection(
id = "dashboard-owner",
label = "Dashboard",
apiServerUrl = "https://hermes.example.com:8642",
relayUrl = "",
tokenStoreKey = "test-key",
dashboardUrl = "https://hermes.example.com:9119",
)
assertEquals(
SessionTransport.GATEWAY,
resolveActiveChatTransport(
boundOwner = null,
connection = connection,
preference = "auto",
),
)
assertEquals(
SessionTransport.SSE,
resolveActiveChatTransport(
boundOwner = SessionTransport.SSE,
connection = connection,
preference = "auto",
),
)
}
@@ -28,23 +28,25 @@ class ChatRuntimeStatusTest {
}
@Test
fun `API SSE ready is healthy fallback when gateway is unavailable`() {
fun `API SSE ready is healthy only for an API-owned conversation`() {
assertEquals(
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
resolveChatRuntimeStatus(
gateway = ChatTransportReadiness.Unavailable,
apiSse = ChatTransportReadiness.Ready,
owner = ChatTransportPath.ApiSse,
),
)
}
@Test
fun `ready API fallback wins while gateway is still connecting`() {
fun `ready sibling API cannot mask gateway auth expiry`() {
assertEquals(
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
ChatRuntimeStatus.Unavailable,
resolveChatRuntimeStatus(
gateway = ChatTransportReadiness.Connecting,
gateway = ChatTransportReadiness.Unavailable,
apiSse = ChatTransportReadiness.Ready,
owner = ChatTransportPath.Gateway,
),
)
}
@@ -63,6 +65,7 @@ class ChatRuntimeStatusTest {
resolveChatRuntimeStatus(
gateway = ChatTransportReadiness.Unavailable,
apiSse = ChatTransportReadiness.Connecting,
owner = ChatTransportPath.ApiSse,
),
)
}
@@ -195,7 +195,7 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals(STORED_SESSION_ID, failure?.sessionId)
assertEquals(ChatFailureRoute.GATEWAY, failure?.route)
assertTrue(failure?.recoverable == true)
assertTrue(failure?.rawError.orEmpty().contains("no API fallback"))
assertTrue(failure?.rawError.orEmpty().contains("belongs to the Hermes Dashboard"))
assertEquals("Retry this after reconnect", handler.lastSentMessage.value)
assertTrue(handler.messages.value.isEmpty())
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Session), 1).single()
@@ -238,6 +238,63 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals("gateway", diagnostic.endpointRole)
}
@Test
fun normalCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
DiagnosticsLog.clear()
apiMessageRequestCount.set(0)
val owner = Profile(name = "owner", model = "model-a", description = "Owner")
val requestedProfiles = mutableListOf<String?>()
val sessionRefreshes = AtomicInteger(0)
val signInRequests = AtomicInteger(0)
viewModel.setSelectedProfileProvider { owner }
viewModel.setSessionProfileNameProvider { owner.name }
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
requestedProfiles += profileName
assertEquals(STORED_SESSION_ID, sessionId)
Result.failure(
DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized"),
)
}
viewModel.setProfileSessionLister { profileName ->
assertEquals(owner.name, profileName)
sessionRefreshes.incrementAndGet()
Result.success(emptyList())
}
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
viewModel.sendMessage("Keep this local prompt")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"message.delta",
buildJsonObject { put("text", "Keep this local answer") },
"live-resumed",
),
)
serverWs.send(
gatewayHarness.eventFrame(
"message.complete",
buildJsonObject { put("text", "Keep this local answer") },
"live-resumed",
),
)
awaitCondition {
!handler.isStreaming.value &&
signInRequests.get() == 1 &&
sessionRefreshes.get() >= 1
}
assertTrue(handler.messages.value.any { it.content == "Keep this local prompt" })
assertTrue(handler.messages.value.any { it.content == "Keep this local answer" })
assertEquals(listOf(owner.name), requestedProfiles)
assertEquals(0, apiMessageRequestCount.get())
assertFalse(viewModel.steerableTurn.value)
assertNull(viewModel.chatFailure.value)
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
assertTrue(diagnostic.suggestion.orEmpty().contains("Sign in to Dashboard"))
}
@Test
fun missingRequiredProfileHistoryLoaderFailsClosedWithoutApiRead() {
DiagnosticsLog.clear()
@@ -1593,6 +1650,39 @@ class ChatViewModelGatewayInboundTurnTest {
assertTrue(gatewayClient.hasActiveTurn())
}
@Test
fun gatewayOwnedConversationDoesNotDispatchToReachableApiWhenGatewayIsMissing() {
viewModel.streamingEndpoint = "gateway"
viewModel.updateGatewayClient(null)
val apiRequestsBefore = apiCompletionsRequestCount.get()
viewModel.sendMessage("Keep this turn on Victor")
shadowOf(Looper.getMainLooper()).idle()
assertEquals(apiRequestsBefore, apiCompletionsRequestCount.get())
assertTrue(handler.messages.value.none { it.role == MessageRole.ASSISTANT })
assertEquals(
ChatFailureRoute.GATEWAY,
viewModel.chatFailure.value?.route,
)
assertEquals(STORED_SESSION_ID, handler.currentSessionId.value)
}
@Test
fun boundGatewaySessionRejectsAResolverTransportFlipUntilExplicitNewChat() {
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
viewModel.streamingEndpoint = "sessions"
assertEquals("gateway", viewModel.streamingEndpoint)
assertEquals(SessionTransport.GATEWAY, viewModel.conversationBinding.value.transport)
viewModel.createNewChat()
assertEquals("sessions", viewModel.streamingEndpoint)
assertEquals(SessionTransport.SSE, viewModel.conversationBinding.value.transport)
}
@Test
fun gatewayRichCardActionStaysOnGatewayInsteadOfDrainingThroughSessionsApi() {
viewModel.sseFallbackEndpoint = "sessions"
@@ -2746,6 +2836,92 @@ class ChatViewModelGatewayInboundTurnTest {
)
}
@Test
fun recoveredCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
DiagnosticsLog.clear()
apiMessageRequestCount.set(0)
val checkpointStore = MemoryCheckpointStore(
ChatTurnCheckpoint(
contextKey = PROFILE_CONTEXT,
sessionId = STORED_SESSION_ID,
liveSessionId = "live-resumed",
transport = "gateway",
user = ChatTurnUserCheckpoint("prior-user", "Recovered prompt", 1L),
assistant = ChatTurnAssistantCheckpoint(
id = "prior-assistant",
content = "Recovered partial",
timestamp = 2L,
),
priorUserMessageCount = 0,
baselineAssistantCount = 0,
startedAt = 2L,
updatedAt = System.currentTimeMillis(),
),
)
val requestedProfiles = mutableListOf<String?>()
val sessionRefreshes = AtomicInteger(0)
val signInRequests = AtomicInteger(0)
var failHistory = false
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
requestedProfiles += profileName
assertEquals(STORED_SESSION_ID, sessionId)
if (failHistory) {
Result.failure(
DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"session_expired\"}",
),
)
} else {
Result.success(emptyList())
}
}
viewModel.setProfileSessionLister { profileName ->
assertNull(profileName)
sessionRefreshes.incrementAndGet()
Result.success(emptyList())
}
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
gatewayHarness.recoveryRunning = true
gatewayHarness.recoveryAssistant = "Recovered partial"
viewModel.setChatTurnCheckpointStore(checkpointStore)
handler.setSessionId(null)
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
viewModel.prewarmGateway()
gatewayHarness.awaitRpc("session.activate")
awaitCondition {
handler.messages.value.any { it.id == "prior-assistant" && it.isStreaming }
}
failHistory = true
serverWs.send(
gatewayHarness.eventFrame(
"message.complete",
buildJsonObject { put("text", "Recovered answer") },
"live-resumed",
),
)
awaitCondition {
!handler.isStreaming.value &&
signInRequests.get() == 1 &&
sessionRefreshes.get() >= 1
}
assertTrue(handler.messages.value.any {
it.id == "prior-assistant" &&
it.content.contains("Recovered answer") &&
!it.isStreaming
})
assertTrue(requestedProfiles.isNotEmpty())
assertTrue(requestedProfiles.all { it == null })
assertEquals(0, apiMessageRequestCount.get())
assertFalse(viewModel.steerableTurn.value)
awaitCondition { checkpointStore.checkpoint == null }
assertNull(viewModel.chatFailure.value)
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
}
@Test
fun lateCanceledCompletionDrainsBeforeImmediateNextTurn() {
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
@@ -3596,6 +3772,16 @@ class ChatViewModelGatewayInboundTurnTest {
awaitCondition {
gatewayHarness.rpcLog.count { it.first == "session.active_list" } > baselineActiveList
}
awaitCondition {
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
SessionActivityState.Working
}
gatewayHarness.activeSessionListPayload = activeSessionPayload("waiting")
viewModel.requestSessionActivityRefresh()
awaitCondition {
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
SessionActivityState.NeedsInput
}
persistedHistory = listOf(
MessageItem(
id = "desktop-answer",
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.SessionTransport
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -112,4 +113,40 @@ class ConversationBindingControllerTest {
assertEquals("alpha", controller.state.value.profileName)
assertEquals("a1", controller.state.value.sessionId)
}
@Test
fun gatewayOwnerSurvivesSessionClearAndLifecycleReconciliation() {
controller.forceGlobal(
contextKey = "c::victor",
profileName = "victor",
sessionId = "20260831_120000_deadbeef",
transport = SessionTransport.GATEWAY,
)
controller.startFreshDraft()
controller.reconcileGlobal(
contextKey = "c::victor",
profileName = "victor",
sessionId = null,
transport = SessionTransport.GATEWAY,
)
assertEquals(SessionTransport.GATEWAY, controller.state.value.transport)
assertNull(controller.state.value.sessionId)
}
@Test
fun explicitApiSessionKeepsItsCompatibilityOwner() {
controller.openExplicit(
contextKey = "c::default",
profileName = null,
sessionId = "api_1788192000_deadbeef",
displayProfile = null,
lockedProfileToken = null,
)
assertEquals(SessionTransport.SSE, controller.state.value.transport)
controller.switchSession(null)
assertEquals(SessionTransport.SSE, controller.state.value.transport)
}
}
@@ -5,6 +5,7 @@ import com.hermesandroid.relay.data.SessionLiveStatus
import com.hermesandroid.relay.network.upstream.GatewayActiveSession
import com.hermesandroid.relay.network.upstream.GatewayActiveSessionStatus
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -40,14 +41,35 @@ class SessionActivityResolutionTest {
}
@Test
fun `unscoped stored id stays unresolved even when bounded directory looks unique`() {
fun `unique selected passive owner resolves without a runtime binding`() {
val unique = SessionActivityOwner.of("connection", "beta", "unique")
val result = resolveGatewayActiveSessions(
sessions = listOf(
GatewayActiveSession(
runtimeSessionId = "runtime",
storedSessionId = "unique",
status = GatewayActiveSessionStatus.Starting,
status = GatewayActiveSessionStatus.Waiting,
lastActiveEpochSeconds = 1.0,
),
),
directory = setOf(alpha, unique),
currentOwner = unique,
)
assertEquals(unique, result.runtimes.single().owner)
assertEquals(SessionLiveStatus.Waiting, result.runtimes.single().status)
assertFalse(result.ambiguous)
}
@Test
fun `unique passive owner for a nonselected session stays unresolved`() {
val unique = SessionActivityOwner.of("connection", "beta", "unique")
val result = resolveGatewayActiveSessions(
sessions = listOf(
GatewayActiveSession(
runtimeSessionId = "runtime",
storedSessionId = "unique",
status = GatewayActiveSessionStatus.Working,
lastActiveEpochSeconds = 1.0,
),
),
@@ -118,7 +118,7 @@ class ProfileControllerLockTest {
// (no gateway probe gating) — keeps refreshLastSessionForProfile from
// bailing early on Unknown.
streamingEndpointProvider = { streamingEndpoint },
gatewayAvailabilityProvider = { gatewayAvailability },
automaticTransportProvider = { SessionTransport.GATEWAY },
setLastSessionId = { lastSessionIds += it },
legacyDefaultSessionId = { null },
rebuildChatApiClient = { },
@@ -208,13 +208,16 @@ class ProfileControllerLockTest {
}
@Test
fun autoUnknownRestoresGatewayBucketUntilDefinitiveFallback() {
fun autoGatewayOwnerDoesNotChangeRestoreBucketAfterOutage() {
streamingEndpoint = "auto"
gatewayAvailability = GatewayAvailability.Unknown
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
gatewayAvailability = GatewayAvailability.Unreachable
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
streamingEndpoint = "sessions"
assertEquals(SessionTransport.SSE, controller.activeSessionTransport())
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@hermes-relay/cli",
"version": "0.4.0-beta.5",
"version": "0.4.0-beta.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@hermes-relay/cli",
"version": "0.4.0-beta.5",
"version": "0.4.0-beta.6",
"license": "MIT",
"bin": {
"hermes-relay": "bin/hermes-relay.js"

Some files were not shown because too many files have changed in this diff Show More