Compare commits

...
Author SHA1 Message Date
Bailey Dixon 889c2fb316 Merge pull request #390 from Codename-11/dev
release(android): android-v1.11.0
2026-08-20 20:56:04 -04:00
Bailey Dixon 260c21737c merge: prepare Android 1.11.0 release 2026-08-20 20:12:40 -04:00
Bailey Dixon 7036219f90 release(android): android-v1.11.0 2026-08-20 20:12:06 -04:00
Bailey Dixon d741acab27 merge: clear Android release verification blockers 2026-08-20 19:53:04 -04:00
Bailey Dixon 8d9970449c test(android): align localized route diagnostics 2026-08-20 19:52:38 -04:00
Bailey Dixon be50f9a726 fix(android): preserve stopped recovery placeholders 2026-08-20 19:52:37 -04:00
Bailey Dixon f21923d39b merge: resync remote dev after website hotfix 2026-08-20 17:31:51 -04:00
Bailey Dixon 27970d4020 Merge pull request #389 from Codename-11/chore/backmerge-website-remote-access-link
chore: back-merge website link hotfix
2026-08-20 17:27:59 -04:00
Bailey Dixon 94992ff37f chore: back-merge website link hotfix 2026-08-20 17:27:01 -04:00
Bailey Dixon a25de7fe31 Merge pull request #388 from Codename-11/fix/website-remote-access-link
fix(website): repair remote access links
2026-08-20 17:24:45 -04:00
Bailey Dixon 2006d552e2 fix(website): repair remote access links 2026-08-20 17:22:23 -04:00
Bailey Dixon ab532d0696 merge: sync remote dev before release 2026-08-20 17:11:47 -04:00
Bailey Dixon 66971cb0e2 Merge pull request #383 from ophirhan/fix/soft-keyboard-newline
fix(android): only physical Enter sends; let IME return key insert newline
2026-08-20 14:20:47 -04:00
Bailey Dixon 9ae8de2c9d merge: fully expand Android Bridge screen access sheet 2026-08-20 13:17:59 -04:00
Bailey Dixon b5174d6279 fix(android): fully expand screen access sheet 2026-08-20 13:17:41 -04:00
Bailey Dixon 7ac5a48e18 merge: clarify Android Bridge access controls 2026-08-20 13:01:43 -04:00
Bailey Dixon ea6cb5a6a7 fix(android): clarify bridge access controls 2026-08-20 13:01:29 -04:00
Bailey Dixon d5cccd664a merge: preserve unlimited Android Bridge state 2026-08-20 12:40:14 -04:00
Bailey Dixon a48349e3cf fix(android): preserve unlimited bridge access state 2026-08-20 12:39:54 -04:00
Bailey Dixon d476704c3f merge: allow unlimited Android Bridge screen access 2026-08-20 11:53:15 -04:00
Bailey Dixon f7a070ecfe feat(android): allow unlimited bridge screen access 2026-08-20 11:52:52 -04:00
Bailey Dixon 37084566a0 merge: clarify Android Bridge access setup 2026-08-20 11:05:47 -04:00
Bailey Dixon c43f22f18d feat(android): clarify bridge access setup 2026-08-20 11:04:59 -04:00
Bailey Dixon 6244ab3781 merge: surface Android stored session resume failures 2026-08-20 09:14:08 -04:00
Bailey Dixon 9b1852a986 merge: reconcile current dev for Android resume failure fix
# Conflicts:
#	CHANGELOG.md
2026-08-20 08:54:52 -04:00
Bailey Dixon 99f853c98e fix(android): surface stored session resume failures 2026-08-20 08:53:49 -04:00
ophirhan 39782a5ff1 fix(android): only physical Enter sends; let IME return key insert newline
The #318 keyboard handling made any KEYCODE_ENTER key event submit the
message when physicalEnterSends is enabled. Some IMEs dispatch the soft
keyboard return key as a synthesized KEYCODE_ENTER key event (deviceId
-1), so on those keyboards the return key sent the message instead of
inserting a newline - leaving no way to type multi-line prompts from
the touchscreen.

Gate the submit path on physical keys (deviceId != -1) so IME-dispatched
Enter falls through to the default newline insertion while hardware Enter
keeps the send behavior. Adds a regression test for the IME key-event path.

Closes #367
2026-08-20 14:18:56 +03:00
Bailey Dixon 0d660c0e41 merge: add granular Android Bridge capability grants 2026-08-19 21:10:05 -04:00
Bailey Dixon 6b14ac0e0e Merge branch 'dev' into feature/android-bridge-capability-grants 2026-08-19 21:01:31 -04:00
Bailey Dixon 59b5424c49 Merge branch 'fix/android-power-audit-377' into dev 2026-08-19 20:58:24 -04:00
Bailey Dixon 0f83af76f6 fix(android): bound power-sensitive runtime work 2026-08-19 20:08:15 -04:00
Bailey Dixon 6a39e8dc1a feat(android): add granular bridge capability grants 2026-08-19 19:43:04 -04:00
Bailey Dixon e8473e14c8 Merge pull request #376 from Codename-11/chore/backmerge-android-1.10.0
chore: back-merge Android 1.10.0 release
2026-08-18 22:23:49 -04:00
Bailey Dixon e05018bd0b chore: back-merge Android 1.10.0 release 2026-08-18 22:22:49 -04:00
Bailey Dixon 97231eb291 Merge pull request #375 from Codename-11/dev
release(android): android-v1.10.0
2026-08-18 22:02:10 -04:00
Bailey Dixon f7c707be03 release(android): android-v1.10.0 2026-08-18 21:32:09 -04:00
Bailey Dixon 331fad0827 merge: fix Android completion bubble layout 2026-08-18 20:50:24 -04:00
Bailey Dixon f131fa08cc fix(android): keep completion bubble layout stable 2026-08-18 20:50:18 -04:00
Bailey Dixon cbc81513bd merge: fix Android completion scroll anchor 2026-08-18 19:56:48 -04:00
Bailey Dixon 3ad5ad8dc7 fix(android): preserve stream completion scroll anchor 2026-08-18 19:56:39 -04:00
Bailey Dixon d695553c0b merge: integrate native streaming Markdown renderer 2026-08-18 19:32:42 -04:00
Bailey Dixon 6b324fa822 fix(android): keep streaming markdown renderer stable 2026-08-18 19:32:28 -04:00
Bailey Dixon 52ee97f2b5 merge: fix Android streaming scroll settlement 2026-08-17 19:57:56 -04:00
Bailey Dixon 76bfe97c78 fix(android): stop streaming markdown scroll bounce 2026-08-17 19:57:47 -04:00
Bailey Dixon c8a3072704 merge: integrate Android streaming Markdown follow
# Conflicts:
#	app/src/main/kotlin/com/hermesandroid/relay/ui/screens/ChatScreen.kt
2026-08-17 18:43:50 -04:00
Bailey Dixon a7612d7f05 chore(android): reconcile localization catalog hash 2026-08-17 18:25:32 -04:00
Bailey Dixon e82ed47573 merge: integrate Android composer continuity 2026-08-17 18:18:34 -04:00
Bailey Dixon c6e4a2877d merge: fix Android reconnect and credential safety 2026-08-17 09:48:42 -04:00
Bailey Dixon 79335fea16 feat(android): persist composer drafts and attach large pastes 2026-08-17 09:40:07 -04:00
Bailey Dixon 9c8b6c30bf fix(android): recover chat sessions and reject malformed credentials 2026-08-17 09:11:21 -04:00
Bailey Dixon 4cf89df627 feat(android): stabilize streaming markdown follow 2026-08-17 09:10:53 -04:00
Bailey Dixon ad98ca9486 fix(android): expose newline on software keyboard 2026-08-17 08:38:50 -04:00
dependabot[bot] 9d50f401ad chore(deps): bump com.github.triplet.play from 4.0.0 to 4.1.1 (#373)
Bumps com.github.triplet.play from 4.0.0 to 4.1.1.

---
updated-dependencies:
- dependency-name: com.github.triplet.play
  dependency-version: 4.1.1
  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-17 11:57:58 +00:00
dependabot[bot] 2bc62c84e0 chore(deps): bump androidx.appcompat:appcompat from 1.7.1 to 1.8.0 (#372)
Bumps androidx.appcompat:appcompat from 1.7.1 to 1.8.0.

---
updated-dependencies:
- dependency-name: androidx.appcompat:appcompat
  dependency-version: 1.8.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-17 11:57:08 +00:00
dependabot[bot] c3011e286c chore(deps): bump com.microsoft.onnxruntime:onnxruntime-android (#371)
Bumps [com.microsoft.onnxruntime:onnxruntime-android](https://github.com/microsoft/onnxruntime) from 1.28.0 to 1.29.0.
- [Release notes](https://github.com/microsoft/onnxruntime/releases)
- [Changelog](https://github.com/microsoft/onnxruntime/blob/main/docs/ReleaseNotesWorkflow.md)
- [Commits](https://github.com/microsoft/onnxruntime/compare/v1.28.0...v1.29.0)

---
updated-dependencies:
- dependency-name: com.microsoft.onnxruntime:onnxruntime-android
  dependency-version: 1.29.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-17 11:56:34 +00:00
dependabot[bot] 9458fea4f7 chore(deps): bump the testing group with 2 updates (#370)
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.71.0 to 1.72.0
- [Release notes](https://github.com/takahirom/roborazzi/releases)
- [Commits](https://github.com/takahirom/roborazzi/compare/1.71.0...1.72.0)

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

---
updated-dependencies:
- dependency-name: io.github.takahirom.roborazzi:roborazzi
  dependency-version: 1.72.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.72.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-17 11:55:21 +00:00
dependabot[bot] 94b29c4a01 chore(deps): bump androidx.compose:compose-bom in the compose group (#369)
Bumps the compose group with 1 update: androidx.compose:compose-bom.


Updates `androidx.compose:compose-bom` from 2026.06.01 to 2026.08.00

---
updated-dependencies:
- dependency-name: androidx.compose:compose-bom
  dependency-version: 2026.08.00
  dependency-type: direct:production
  dependency-group: compose
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-17 11:54:39 +00:00
Bailey Dixon 3d11cfb5f2 Merge pull request #366 from Codename-11/dev
release(android): android-v1.9.1
2026-08-16 17:09:20 -04:00
Bailey Dixon 0f589d030f release(android): android-v1.9.1 2026-08-16 16:38:38 -04:00
Bailey Dixon af96579e06 merge: sync main into dev after desktop release 2026-08-16 16:20:04 -04:00
Bailey Dixon f0167ee00f fix(android): persist shared profile avatars 2026-08-16 15:29:43 -04:00
Bailey Dixon a5798e5e6c merge: integrate upstream animated profile pets 2026-08-16 15:04:18 -04:00
Bailey Dixon 479d788967 feat(android): sync upstream animated profile pets 2026-08-16 11:04:24 -04:00
Bailey Dixon 3f6723da6f merge: fix Nous callback authentication 2026-08-16 10:01:10 -04:00
Bailey Dixon c1cd376d8b fix(android): align Nous callback authentication 2026-08-16 10:01:02 -04:00
Bailey Dixon 87e2fb710d feat(android): add phone-only animated profile icons 2026-08-16 09:46:52 -04:00
Bailey Dixon 5a617f9482 merge: integrate Hermes profile contracts 2026-08-15 22:57:33 -04:00
Bailey Dixon 13152a4fab feat(android): adopt Hermes profile contracts 2026-08-15 22:56:30 -04:00
Bailey Dixon 7f31c88f46 merge: integrate high-value Android and Relay enhancements 2026-08-15 21:39:14 -04:00
Bailey Dixon 3e857b54a2 test(android): align hardened gateway contracts 2026-08-15 21:36:50 -04:00
Bailey Dixon 163e3341da fix(android): verify draft profile ownership 2026-08-15 21:36:49 -04:00
Bailey Dixon a5419df579 fix(android): guard draft model selection 2026-08-15 21:36:49 -04:00
Bailey Dixon e834c603d0 fix(android): clear rejected recovery events 2026-08-15 21:36:49 -04:00
Bailey Dixon a31d715569 feat(android): surface resource and model risk 2026-08-15 21:36:49 -04:00
Bailey Dixon c6b8d891ac fix(android): harden attachment delivery 2026-08-15 21:35:38 -04:00
Bailey Dixon 8996f34347 feat(android): add bounded cron and reset evidence 2026-08-15 21:35:38 -04:00
Bailey Dixon f5f1a4c7d4 fix(android): enforce profile ownership 2026-08-15 21:34:36 -04:00
Bailey Dixon 31eccc631e fix(android): fail closed on ambiguous rewinds 2026-08-15 21:34:35 -04:00
Bailey Dixon 64ba979816 Merge pull request #364 from Codename-11/feature/proactive-away-summary
feat(threads): surface messages received while away
2026-08-15 21:24:04 -04:00
Bailey Dixon 5be0979d74 chore(android): refresh localization catalog status 2026-08-15 21:13:05 -04:00
Bailey Dixon 80b1a3b6df Merge remote-tracking branch 'origin/dev' into feature/proactive-away-summary 2026-08-15 21:08:57 -04:00
Bailey Dixon 257a11ffa2 feat(threads): surface messages received while away 2026-08-15 21:08:50 -04:00
Bailey Dixon 62f3572e11 Merge pull request #363 from Codename-11/fix/android-media-download-state
fix(android): settle media download states
2026-08-15 21:03:40 -04:00
Bailey Dixon 621e526c7d fix(android): settle media download states 2026-08-15 20:52:40 -04:00
Bailey Dixon a5afec36d9 Merge pull request #234 from Codename-11/dependabot/github_actions/dev/actions/setup-python-7
chore(deps): bump actions/setup-python from 6 to 7
2026-08-15 20:11:58 -04:00
Bailey Dixon 29bf9a08ac Merge branch 'dev' into dependabot/github_actions/dev/actions/setup-python-7 2026-08-15 20:10:46 -04:00
Bailey Dixon 342e977594 Merge pull request #233 from Codename-11/dependabot/github_actions/dev/actions/setup-node-7
chore(deps): bump actions/setup-node from 4 to 7
2026-08-15 20:10:39 -04:00
Bailey Dixon 24e767e7ae Merge branch 'dev' into dependabot/github_actions/dev/actions/setup-node-7 2026-08-15 20:09:21 -04:00
Bailey Dixon fdf210ec2b Merge pull request #361 from Codename-11/dev
release(desktop): desktop-v0.4.0-beta.4
2026-08-15 13:49:30 -04:00
Bailey Dixon d05ab31296 release(desktop): desktop-v0.4.0-beta.4 2026-08-15 13:42:14 -04:00
Bailey Dixon 0e0cc16f47 Merge branch 'fix/desktop-daemon-stopped-loading' into dev 2026-08-15 13:32:25 -04:00
Bailey Dixon e90be03f2e fix(desktop): load UI while daemon is stopped 2026-08-15 13:32:11 -04:00
Bailey Dixon f1e4fdcc91 Merge pull request #360 from Codename-11/chore/backmerge-android-1.9.0
chore: back-merge Android 1.9.0 release
2026-08-14 21:52:34 -04:00
Bailey Dixon 5b8b3da350 chore: back-merge Android 1.9.0 release 2026-08-14 21:52:16 -04:00
Bailey Dixon 447ec356d7 Merge pull request #359 from Codename-11/dev
release(android): android-v1.9.0
2026-08-14 21:32:50 -04:00
Bailey Dixon ab359e5efb release(android): android-v1.9.0 2026-08-14 21:01:51 -04:00
Bailey Dixon 86b8161cb7 feat(android): refine sessions and messaging 2026-08-14 20:58:31 -04:00
Bailey Dixon e401fdb0c7 fix(android): persist landed message reactions 2026-08-14 17:04:54 -04:00
Bailey Dixon d4325d5aab fix(android): restore compact chat interactions 2026-08-14 16:57:19 -04:00
Bailey Dixon c734d75484 feat(android): add desktop-style session profiles 2026-08-14 16:57:18 -04:00
Bailey Dixon 0411804780 fix(android): accept compatible session flags 2026-08-14 16:57:18 -04:00
Bailey Dixon 8f89c2841d fix(android): keep dashboard teardown off main thread 2026-08-14 16:57:18 -04:00
Bailey Dixon 933c1842a0 Merge pull request #358 from Codename-11/chore/backmerge-desktop-beta3
chore: back-merge Desktop beta.3 release
2026-08-14 16:31:24 -04:00
Bailey Dixon dfe1b53327 chore: back-merge desktop beta.3 release 2026-08-14 16:30:37 -04:00
Bailey Dixon d36580a983 Merge pull request #356 from Codename-11/dev
release: Desktop beta.3 process-containment patch
2026-08-14 16:11:35 -04:00
Bailey Dixon 2d178ff884 Merge pull request #357 from Codename-11/release/desktop-0.4.0-beta.3
fix(desktop): close process containment race
2026-08-14 16:05:00 -04:00
Bailey Dixon d61955f82a fix(desktop): close process containment race 2026-08-14 15:58:57 -04:00
Bailey Dixon adec6ed2c0 Merge pull request #355 from Codename-11/release/desktop-0.4.0-beta.3
release(desktop): desktop-v0.4.0-beta.3
2026-08-14 15:44:24 -04:00
Bailey Dixon e9e44c8bb2 release(desktop): desktop-v0.4.0-beta.3 2026-08-14 15:36:53 -04:00
Bailey Dixon c6b0732a02 Merge pull request #354 from Codename-11/fix/desktop-tray-process-containment
fix(desktop): contain tray subprocess storms
2026-08-14 15:22:21 -04:00
Bailey Dixon d919115788 fix(desktop): contain tray subprocess storms 2026-08-14 15:15:12 -04:00
Bailey Dixon 49da085ae8 Merge pull request #353 from Codename-11/chore/backmerge-desktop-beta2-server-1.8.0
chore: backmerge Desktop beta.2 and Server 1.8.0 releases
2026-08-14 15:05:21 -04:00
Bailey Dixon 889b6f0858 chore: merge desktop beta.2 and server 1.8.0 release history into dev 2026-08-14 15:05:12 -04:00
Bailey Dixon 5100c524f6 Merge pull request #351 from Codename-11/dev
release: Desktop beta.2 and Server 1.8.0
2026-08-14 15:04:03 -04:00
Bailey Dixon c609ae867f Merge pull request #352 from Codename-11/chore/backmerge-desktop-beta1
chore: back-merge Desktop beta.1 release history
2026-08-14 14:49:23 -04:00
Bailey Dixon 107f8c7720 chore: merge desktop beta.1 release history into dev 2026-08-14 14:49:08 -04:00
Bailey Dixon 8963e4fafd Merge pull request #350 from Codename-11/release/server-1.8.0
release(server): server-v1.8.0
2026-08-14 14:46:57 -04:00
Bailey Dixon 5d9624e2ef release(server): server-v1.8.0 2026-08-14 14:35:01 -04:00
Bailey Dixon 4b063d3fd7 Merge pull request #349 from Codename-11/release/desktop-0.4.0-beta.2
release(desktop): desktop-v0.4.0-beta.2
2026-08-14 12:56:04 -04:00
Bailey Dixon 9b9d7b654c release(desktop): desktop-v0.4.0-beta.2 2026-08-14 12:45:56 -04:00
Bailey Dixon a26e17e72c Merge pull request #348 from Codename-11/fix/cua-windows-health-compat
feat(desktop): enhance activity and control diagnostics
2026-08-14 12:38:12 -04:00
Bailey Dixon a3a6a9bb13 fix(desktop): satisfy tray release lint 2026-08-14 12:36:46 -04:00
Bailey Dixon 169bd09559 merge: sync desktop activity work with dev
# Conflicts:
#	CHANGELOG.md
2026-08-14 11:32:56 -04:00
Bailey Dixon 45d631e7ac feat(desktop): enhance activity and control diagnostics 2026-08-14 11:30:36 -04:00
Bailey Dixon eb6a6c95d2 merge: integrate official desktop relay plugin 2026-08-14 07:58:10 -04:00
Bailey Dixon 3b102663c2 feat(plugin): add official desktop relay surface 2026-08-14 07:56:26 -04:00
Bailey Dixon 0e5fc4c606 Merge branch 'fix/android-proactive-thread-entry' into dev 2026-08-14 07:50:07 -04:00
Bailey Dixon c3189f2cbb fix(android): open proactive messages as threads 2026-08-14 07:49:39 -04:00
Bailey Dixon 0d6c3bd6b0 Merge pull request #346 from Codename-11/dev
release(desktop): desktop-v0.4.0-beta.1
2026-08-13 21:18:41 -04:00
Bailey Dixon 06d88ad40a Merge pull request #345 from Codename-11/release/desktop-0.4.0-beta.1
release(desktop): desktop-v0.4.0-beta.1
2026-08-13 21:11:57 -04:00
Bailey Dixon 8ae5b3fbc2 release(desktop): desktop-v0.4.0-beta.1 2026-08-13 21:04:07 -04:00
Bailey Dixon 39b7a8f108 Merge pull request #344 from Codename-11/fix/desktop-updater-cua-hardening
feat(desktop): adopt CUA as primary control backend
2026-08-13 20:57:50 -04:00
Bailey Dixon af6e167692 fix(desktop): normalize Windows installer paths 2026-08-13 20:51:17 -04:00
Bailey Dixon 274bd6ae98 fix(desktop): honor CUA health schema 2026-08-13 20:45:58 -04:00
Bailey Dixon 9fc55b379a fix(desktop): clarify CUA readiness fallback 2026-08-13 20:34:45 -04:00
Bailey Dixon 559a0ffdc8 feat(desktop): make CUA the primary control backend 2026-08-13 20:16:03 -04:00
Bailey Dixon 75bcd9180f feat(desktop): add optional CUA control engine 2026-08-13 19:33:11 -04:00
Bailey Dixon 9c995a443d fix(desktop): harden bundle updates 2026-08-13 19:06:25 -04:00
Bailey Dixon 7440ef2948 Merge pull request #343 from Codename-11/dev
release: server 1.7.0 and desktop 0.4.0-alpha.8
2026-08-13 17:14:58 -04:00
Bailey Dixon a88539bc59 fix(android): dequeue reach frames compatibly 2026-08-13 16:56:54 -04:00
Bailey Dixon b2ccfdc500 fix(security): carry secure link trust anchor 2026-08-13 16:49:44 -04:00
Bailey Dixon 481c62ac59 fix(desktop): bind pinned secure link probes 2026-08-13 16:42:37 -04:00
Bailey Dixon 5d415fbaf0 fix(android): use compatible reach buffer removal 2026-08-13 16:39:26 -04:00
Bailey Dixon 074b715055 fix(android): complete secure route translations 2026-08-13 16:37:32 -04:00
Bailey Dixon f63ee8721e release(desktop): desktop-v0.4.0-alpha.8 2026-08-13 16:21:51 -04:00
Bailey Dixon 777bc80bcc release(server): server-v1.7.0 2026-08-13 16:21:50 -04:00
Bailey Dixon 9539975bb5 merge: integrate native secure routes 2026-08-13 15:41:46 -04:00
Bailey Dixon 2863a1bc8f merge: reconcile native secure routes with dev 2026-08-13 15:31:53 -04:00
Bailey Dixon b0a7cf0494 feat: add self-hosted secure connection routes 2026-08-13 15:31:46 -04:00
Bailey Dixon 76b4084310 merge: integrate Android and Relay upstream work 2026-08-13 13:24:32 -04:00
Bailey Dixon 2ace70c4fc test: close integration verification gaps 2026-08-13 13:24:02 -04:00
Bailey Dixon 4f52f371ba fix(ops): fail closed on unsafe certification state 2026-08-13 11:16:27 -04:00
Bailey Dixon 064c89bda4 docs: record Android and Relay integration 2026-08-13 11:08:27 -04:00
Bailey Dixon 0cb1e3642f feat(android): add gateway-native profile editor 2026-08-13 11:03:10 -04:00
Bailey Dixon cf4bf87242 fix(android): honor upstream routing contracts 2026-08-13 11:00:39 -04:00
Bailey Dixon 9cbed21014 fix(android): preserve durable gateway rewinds 2026-08-13 10:58:55 -04:00
Bailey Dixon ce75c0fa01 docs: add controlled runtime safety preflight 2026-08-13 10:50:52 -04:00
Bailey Dixon bf2aece6e6 docs: reconcile upstream architecture evaluations 2026-08-13 10:50:14 -04:00
Bailey Dixon 198da78fc8 fix(android): honor upstream approval and compression outcomes 2026-08-13 10:50:14 -04:00
Bailey Dixon 986ce3b12b fix(plugin): isolate profile-owned registrations 2026-08-13 10:50:14 -04:00
Bailey Dixon b53f757830 fix(plugin): support strict phone targets 2026-08-13 10:50:14 -04:00
Bailey Dixon cdeccd69e4 feat: add secure relay route selection 2026-08-12 20:10:41 -04:00
Bailey Dixon bb72516bb5 Merge pull request #340 from Codename-11/chore/backmerge-server-1.6.4
chore: back-merge server-v1.6.4 hotfix
2026-08-12 18:43:50 -04:00
Bailey Dixon 3a51644342 chore: merge server-v1.6.4 release history into dev
# Conflicts:
#	docs/decisions.md
#	user-docs/desktop/tools.md
2026-08-12 18:43:39 -04:00
Bailey Dixon 51c0c7dee9 Merge pull request #338 from Codename-11/fix/server-multidevice-hotfix
fix(server): release targeted multi-desktop routing
2026-08-12 18:39:31 -04:00
Bailey Dixon 7ef2420c85 release(server): server-v1.6.4 2026-08-12 18:38:32 -04:00
Bailey Dixon 6a810c850b fix(server): route concurrent desktop clients explicitly 2026-08-12 18:38:02 -04:00
Bailey Dixon d383002583 Merge pull request #336 from Codename-11/release/server-1.6.4
release(server): server-v1.6.4
2026-08-12 18:35:31 -04:00
Bailey Dixon e3aae829e1 release(server): server-v1.6.4 2026-08-12 18:35:16 -04:00
Bailey Dixon 5207ed4193 Merge pull request #335 from Codename-11/fix/desktop-placement-device-identity
feat(desktop): support targeted multi-device control
2026-08-12 18:32:06 -04:00
Bailey Dixon b46bb00ea8 test(desktop): serialize cross-platform suite 2026-08-12 18:31:50 -04:00
Bailey Dixon b8dde409c5 merge: synchronize desktop management with dev
# Conflicts:
#	CHANGELOG.md
#	docs/decisions.md
2026-08-12 18:26:20 -04:00
Bailey Dixon ca7ded3939 test(server): prove concurrent desktop routing 2026-08-12 18:24:44 -04:00
Bailey Dixon db85a26c68 feat(desktop): add contextual approvals and UI pairing 2026-08-12 18:24:43 -04:00
Bailey Dixon aa2595629d feat(desktop): expand tray management controls 2026-08-12 17:55:56 -04:00
Bailey Dixon d79146dc90 feat(desktop): add ask every time access preset 2026-08-12 17:13:51 -04:00
Bailey Dixon eabc4dd328 refactor(desktop): clarify access navigation 2026-08-12 16:57:50 -04:00
Bailey Dixon e165bfeff3 feat(desktop): animate bidirectional relay traffic 2026-08-12 15:42:43 -04:00
Bailey Dixon 40bcd796d1 refactor(desktop): simplify host access presets 2026-08-12 13:29:29 -04:00
Bailey Dixon 57ae0c9456 feat(desktop): unify capabilities and activity drilldown 2026-08-12 13:06:34 -04:00
Bailey Dixon 9b31a16c89 fix(desktop): preserve Hermes shortcut icons 2026-08-12 11:44:17 -04:00
Bailey Dixon f97bbdd395 feat(desktop): add host-wide raw USB control 2026-08-12 11:38:09 -04:00
Bailey Dixon 722a294947 feat(desktop): adopt compact capability ledger 2026-08-12 11:13:50 -04:00
Bailey Dixon bbfb57b462 feat(desktop): harden targeted remote management 2026-08-12 10:37:12 -04:00
Bailey Dixon 6db12a0bec merge: complete upstream app and Relay workflows 2026-08-12 09:24:24 -04:00
Bailey Dixon f1de957848 fix(android): translate Manage workflows 2026-08-12 09:08:31 -04:00
Bailey Dixon cc01d9c8ad test(android): compile upstream workflow fixtures 2026-08-12 09:00:04 -04:00
Bailey Dixon d574182d84 fix(android): wire Manage workflow dialogs 2026-08-12 08:46:10 -04:00
Bailey Dixon a328763da3 fix(android): localize backup completion 2026-08-12 08:46:05 -04:00
Bailey Dixon f53db68e7d feat(android): complete upstream Manage workflows 2026-08-12 07:45:55 -04:00
Bailey Dixon eb9e570fc0 feat(android): show session repository and PR state 2026-08-12 07:41:35 -04:00
Bailey Dixon 260f119637 fix(voice): align upstream auth and transport 2026-08-12 07:39:42 -04:00
Bailey Dixon d0fa2ea39d fix(android): preserve clarify selection semantics 2026-08-12 07:37:28 -04:00
Bailey Dixon a1c74b1567 fix(plugin): enumerate phone home target 2026-08-12 07:34:19 -04:00
Bailey Dixon 7c45acd38d chore: merge server-v1.6.3 release history into dev 2026-08-11 22:03:36 -04:00
Bailey Dixon 4605b87c10 Merge pull request #333 from Codename-11/dev
release(server): server-v1.6.3
2026-08-11 22:00:43 -04:00
Bailey Dixon 6a91d6ee7e fix(android): complete upstream feature translations 2026-08-11 21:46:45 -04:00
Bailey Dixon 95a2813efe fix(server): validate translated media path components 2026-08-11 21:37:54 -04:00
Bailey Dixon 2ecf521c8c chore: merge main release history into dev 2026-08-11 21:35:40 -04:00
Bailey Dixon 7752c5c404 release(server): server-v1.6.3 2026-08-11 21:35:05 -04:00
Bailey Dixon e1d3764cd2 feat(android): browse sessions across profiles 2026-08-11 20:50:36 -04:00
Bailey Dixon e34171b5ad feat(android): add gateway message reactions 2026-08-11 20:48:09 -04:00
Bailey Dixon 8040cac39a feat(android): redirect running subagents 2026-08-11 20:45:33 -04:00
Bailey Dixon aab70520ca feat(android): open referenced Hermes sessions 2026-08-11 20:40:27 -04:00
Bailey Dixon 5a0cd8123c feat(android): expand Hermes management surfaces 2026-08-11 20:37:03 -04:00
Bailey Dixon 4370d9a925 feat(android): adopt richer gateway chat contracts 2026-08-11 20:30:38 -04:00
Bailey Dixon 726308d2ef fix: harden gateway recovery diagnostics 2026-08-11 20:26:05 -04:00
Bailey Dixon 1acc3a4c80 fix: align app and relay upstream contracts 2026-08-11 20:04:43 -04:00
Bailey Dixon 11ccbd6e5c Merge pull request #332 from Codename-11/dev
release(desktop): desktop-v0.4.0-alpha.7
2026-08-11 19:55:05 -04:00
Bailey Dixon d13af35357 chore: merge main release history into dev 2026-08-11 19:48:26 -04:00
Bailey Dixon e3752d43f3 release(desktop): desktop-v0.4.0-alpha.7 2026-08-11 19:48:24 -04:00
Bailey Dixon 97293b62c3 Merge pull request #331 from Codename-11/dev
release(desktop): desktop-v0.4.0-alpha.6
2026-08-11 19:33:13 -04:00
Bailey Dixon 454e770648 chore: merge main release history into dev 2026-08-11 19:26:15 -04:00
Bailey Dixon e18572e8e3 release(desktop): desktop-v0.4.0-alpha.6 2026-08-11 19:24:27 -04:00
Bailey Dixon 83f69725b9 Merge pull request #330 from Codename-11/dev
release: Desktop 0.4.0-alpha.5
2026-08-11 19:05:39 -04:00
Bailey Dixon 72aa7c3046 chore: merge main release history into dev 2026-08-11 18:59:06 -04:00
Bailey Dixon 3995c64493 release(desktop): desktop-v0.4.0-alpha.5 2026-08-11 18:59:04 -04:00
Bailey Dixon ce538ced3d Merge pull request #329 from Codename-11/dev
release: Desktop 0.4.0-alpha.4
2026-08-11 18:43:32 -04:00
Bailey Dixon 352bc5b439 chore: merge main release history into dev 2026-08-11 18:35:52 -04:00
Bailey Dixon 9ec163b27b release(desktop): desktop-v0.4.0-alpha.4 2026-08-11 18:35:32 -04:00
Bailey Dixon 7a3efa2c4d Merge pull request #328 from Codename-11/dev
release: Desktop 0.4.0-alpha.3 and Server 1.6.2
2026-08-11 18:19:36 -04:00
Bailey Dixon c28be7c92e style(desktop): format tray contract test 2026-08-11 18:03:02 -04:00
Bailey Dixon 8d1758ec8b fix(desktop): build tray assets before Rust checks 2026-08-11 18:01:17 -04:00
Bailey Dixon ce8b8702c3 test(desktop): make UI install coverage portable 2026-08-11 17:53:56 -04:00
Bailey Dixon ca0a9eb524 release(desktop): desktop-v0.4.0-alpha.3 2026-08-11 17:51:25 -04:00
Bailey Dixon b91d8c9a09 release(server): server-v1.6.2 2026-08-11 17:51:13 -04:00
Bailey Dixon bebd327816 Merge pull request #327 from Codename-11/feature/desktop-relay-management-release
feat: ship desktop management UI and paired-device identity
2026-08-11 17:49:18 -04:00
Bailey Dixon 8fa97e0b46 feat(desktop): add host management tray UI 2026-08-11 17:48:47 -04:00
Bailey Dixon 45dc82e573 feat(server): enrich paired device identity 2026-08-11 17:48:09 -04:00
dependabot[bot] 48b23f4d9e chore(deps): bump gradle-wrapper from 9.6.1 to 9.7.0 (#326)
Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.6.1 to 9.7.0.
- [Release notes](https://github.com/gradle/gradle/releases)
- [Commits](https://github.com/gradle/gradle/compare/v9.6.1...v9.7.0)

---
updated-dependencies:
- dependency-name: gradle-wrapper
  dependency-version: 9.7.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-10 11:56:21 +00:00
dependabot[bot] f708ef3353 chore(deps): bump androidx.media3:media3-exoplayer from 1.10.1 to 1.11.0 (#325)
Bumps [androidx.media3:media3-exoplayer](https://github.com/androidx/media) from 1.10.1 to 1.11.0.
- [Release notes](https://github.com/androidx/media/releases)
- [Changelog](https://github.com/androidx/media/blob/release/RELEASENOTES.md)
- [Commits](https://github.com/androidx/media/compare/1.10.1...1.11.0)

---
updated-dependencies:
- dependency-name: androidx.media3:media3-exoplayer
  dependency-version: 1.11.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-10 11:55:39 +00:00
dependabot[bot] 3224595a46 chore(deps): bump gradle/actions from 6.2.0 to 6.3.0 (#324)
Bumps [gradle/actions](https://github.com/gradle/actions) from 6.2.0 to 6.3.0.
- [Release notes](https://github.com/gradle/actions/releases)
- [Commits](https://github.com/gradle/actions/compare/v6.2.0...v6.3.0)

---
updated-dependencies:
- dependency-name: gradle/actions
  dependency-version: 6.3.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-10 11:55:08 +00:00
dependabot[bot] c0453f040d chore(deps): bump the testing group with 2 updates (#323)
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.70.0 to 1.71.0
- [Release notes](https://github.com/takahirom/roborazzi/releases)
- [Commits](https://github.com/takahirom/roborazzi/compare/1.70.0...1.71.0)

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

---
updated-dependencies:
- dependency-name: io.github.takahirom.roborazzi:roborazzi
  dependency-version: 1.71.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.71.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-10 11:54:54 +00:00
Bailey Dixon 33a0ea3216 chore: merge main back after android-v1.8.1 2026-08-10 00:05:29 -04:00
Bailey Dixon cec05ceec2 Merge pull request #322 from Codename-11/dev
release(android): android-v1.8.1
2026-08-09 23:46:51 -04:00
Bailey Dixon 0e30699fff release(android): android-v1.8.1 2026-08-09 23:20:15 -04:00
Bailey Dixon d4041e4528 chore: merge main back after android-v1.8.0 2026-08-09 23:15:39 -04:00
Bailey Dixon c5ae402cd7 fix(android): align gateway and transcript contracts 2026-08-09 23:08:26 -04:00
Bailey Dixon 56eb213bbf Merge pull request #321 from Codename-11/dev
release(android): android-v1.8.0
2026-08-09 22:53:38 -04:00
Bailey Dixon 3165ebb8ce release(android): android-v1.8.0 2026-08-09 22:03:44 -04:00
Bailey Dixon a2457a39d4 Revert "Merge branch 'feature/hermes-management-profile-detail' into dev"
This reverts commit b481f1f337, reversing
changes made to 7b61ed4758.
2026-08-09 21:35:33 -04:00
Bailey Dixon c2799082b0 Revert "Merge branch 'feature/hermes-management-detail-surfaces' into dev"
This reverts commit 2a467bc03f, reversing
changes made to 44293030c9.
2026-08-09 21:35:33 -04:00
Bailey Dixon 2a467bc03f Merge branch 'feature/hermes-management-detail-surfaces' into dev 2026-08-09 21:13:35 -04:00
Bailey Dixon a30d3dc6ed feat(android): refine Hermes management surfaces 2026-08-09 21:13:29 -04:00
Bailey Dixon 44293030c9 fix(android): contain appearance header in viewport 2026-08-09 20:50:53 -04:00
Bailey Dixon 42ac8c5589 feat(marketing): refresh product screenshots 2026-08-09 20:08:42 -04:00
Bailey Dixon b481f1f337 Merge branch 'feature/hermes-management-profile-detail' into dev 2026-08-09 19:59:56 -04:00
Bailey Dixon 62c4017eeb feat(android): refine Hermes profile management detail 2026-08-09 19:59:40 -04:00
Bailey Dixon 7b61ed4758 Merge branch 'fix/hermes-management-detail-ui' into dev 2026-08-09 19:22:30 -04:00
Bailey Dixon 21259230b2 fix(android): restore Hermes management hub 2026-08-09 19:22:20 -04:00
Bailey Dixon 7ef1e93544 fix(android): reconcile profile shelf chat status 2026-08-09 19:13:34 -04:00
Bailey Dixon 61a50dc968 Merge branch 'feature/hermes-management-ui' into dev 2026-08-09 19:13:16 -04:00
Bailey Dixon 18b9ed005b chore(marketing): refresh production UI screenshots 2026-08-09 19:13:04 -04:00
Bailey Dixon c597187fa3 Merge branch 'feature/android-profile-shelf' into dev
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/ConnectionInfoSheet.kt
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/MessageBubble.kt
#	app/src/main/kotlin/com/hermesandroid/relay/ui/screens/ChatScreen.kt
#	app/src/main/res/values-b+pt+BR/strings.xml
#	app/src/main/res/values-b+zh+Hans/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ru/strings.xml
2026-08-09 19:11:50 -04:00
Bailey Dixon c97f3a3359 feat(android): streamline Hermes management UI 2026-08-09 19:10:45 -04:00
Bailey Dixon 2d9ccd4712 Revert "Merge branch 'feature/agent-profile-defaults' into dev"
This reverts commit 93643be844, reversing
changes made to 1132fdf576.
2026-08-09 18:37:16 -04:00
Bailey Dixon 93643be844 Merge branch 'feature/agent-profile-defaults' into dev 2026-08-09 18:18:00 -04:00
Bailey Dixon b82ee95b8f feat(android): add profile defaults editor 2026-08-09 18:17:53 -04:00
Bailey Dixon 1132fdf576 fix(android): stabilize passport scrolling and model layout 2026-08-09 18:17:31 -04:00
Bailey Dixon 04c69cd15f fix(android): preserve gateway model during api catalog loads 2026-08-09 18:05:16 -04:00
Bailey Dixon b4edcad1e7 fix(android): keep passport catalog refresh read only 2026-08-09 17:54:08 -04:00
Bailey Dixon bef9579917 fix(android): keep passport controls session scoped 2026-08-09 17:11:24 -04:00
Bailey Dixon c84e037b77 fix(android): stop message narration safely 2026-08-09 16:38:27 -04:00
Bailey Dixon 3ad33691cb fix(android): recover persisted tool activity and chat speech 2026-08-09 16:21:40 -04:00
Bailey Dixon bb0a810798 fix(android): protect chat identity from pets 2026-08-09 16:09:09 -04:00
Bailey Dixon b675c1498c Merge branch 'feature/android-clean-activity' into dev 2026-08-09 15:46:02 -04:00
Bailey Dixon 6da1ad1a99 Merge branch 'fix/android-avatar-pet-regressions' into dev 2026-08-09 15:46:01 -04:00
Bailey Dixon 380b9e918d feat(android): clean up transcript activity 2026-08-09 15:44:05 -04:00
Bailey Dixon d531b4d377 fix(android): restore chat and pet interactions 2026-08-09 15:36:57 -04:00
Bailey Dixon 8cba61d2d8 Merge branch 'fix/android-chat-input-polish' into dev 2026-08-09 13:30:59 -04:00
Bailey Dixon 4106fd4b78 fix(android): polish chat message presentation 2026-08-09 13:30:53 -04:00
Bailey Dixon 47426db290 Merge branch 'feature/appearance-customization' into dev 2026-08-09 13:21:01 -04:00
Bailey Dixon b7945b072f feat(android): enhance appearance and visual assets 2026-08-09 13:20:53 -04:00
Bailey Dixon 3aead772a0 Merge branch 'fix/android-chat-input-polish' into dev 2026-08-09 12:41:22 -04:00
Bailey Dixon ccf94e1d9d feat(android): refine chat experience 2026-08-09 12:41:17 -04:00
Bailey Dixon 6b6edc1322 Merge branch 'fix/android-pet-ui-awareness' into dev 2026-08-09 12:31:28 -04:00
Bailey Dixon 2644b94fa9 fix(android): keep floating pets clear of UI 2026-08-09 12:31:14 -04:00
Bailey Dixon 440e3d5bb9 fix(android): unbox thinking status 2026-08-08 22:40:07 -04:00
Bailey Dixon 97158bc861 fix(android): stabilize server-default shelf avatar 2026-08-08 22:35:32 -04:00
Bailey Dixon d5a313ab5d feat(android): refine profile and chat handoffs 2026-08-08 20:27:01 -04:00
Bailey Dixon 3033e331b0 chore: backmerge Android 1.7.1 and Server 1.6.1 releases 2026-08-08 20:06:51 -04:00
Bailey Dixon ca98f2ae97 Merge pull request #317 from Codename-11/dev
Release Android 1.7.1 and Server 1.6.1
2026-08-08 19:44:56 -04:00
Bailey Dixon 07bbb16671 feat(android): add profile shelf 2026-08-08 19:25:20 -04:00
Bailey Dixon ee08187c67 release(server): server-v1.6.1 2026-08-08 19:15:32 -04:00
Bailey Dixon 7ccde11a2d release(android): android-v1.7.1 2026-08-08 19:15:31 -04:00
Bailey Dixon 2378e6ab9f Merge branch 'fix/android-stream-tail-follow' into dev 2026-08-08 18:37:07 -04:00
Bailey Dixon 9045550317 fix(android): follow growing streamed replies 2026-08-08 18:37:01 -04:00
Bailey Dixon 7074920625 test(android): reconcile post-release issue coverage 2026-08-08 18:01:50 -04:00
Bailey Dixon cac8a517b4 Merge branch 'fix/android-nous-hosted-onboarding' into dev 2026-08-08 16:26:38 -04:00
Bailey Dixon c27019cdbb fix(connections): stabilize hosted Hermes onboarding 2026-08-08 16:26:33 -04:00
Bailey Dixon d0b060fe12 Merge branch 'fix/android-session-owned-queue' into dev
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/viewmodel/ChatViewModel.kt
2026-08-08 13:48:09 -04:00
Bailey Dixon 098cc82711 Merge branch 'fix/android-agent-passport-safety-sheet' into dev
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
2026-08-08 13:30:55 -04:00
Bailey Dixon 98a311afb5 fix(android): keep queued messages with origin session 2026-08-08 13:29:21 -04:00
Bailey Dixon cb1560fff3 fix(android): improve agent passport safety controls 2026-08-08 13:27:32 -04:00
Bailey Dixon 76bb9f8dcb Merge branch 'fix/issue-316-markdown-completion' into dev
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
2026-08-08 12:39:54 -04:00
Bailey Dixon 1eb0393dd9 fix(android): render markdown when replies complete 2026-08-08 12:38:13 -04:00
Bailey Dixon 96e6d29c9e Merge branch 'fix/android-approval-explicit-consent' into dev 2026-08-08 12:34:55 -04:00
Bailey Dixon f9bf4e384f fix(android): require explicit approval decisions 2026-08-08 12:34:46 -04:00
Bailey Dixon 615119b100 Merge branch 'fix/android-session-pin-archive' into dev
# Conflicts:
#	CHANGELOG.md
#	docs/decisions.md
2026-08-08 09:24:40 -04:00
Bailey Dixon cfe86b6cc3 fix(android): persist session pin and archive state 2026-08-08 08:56:55 -04:00
Bailey Dixon 677914a51d Merge branch 'fix/android-active-tool-card-expansion' into dev 2026-08-08 08:47:13 -04:00
Bailey Dixon 8b3adf10c6 fix(android): preserve live tool card expansion 2026-08-08 08:47:07 -04:00
Bailey Dixon 5cc8e7187b Merge branch 'fix/android-model-inventory-identity' into dev 2026-08-08 08:42:55 -04:00
Bailey Dixon ece46cae24 fix(android): normalize model inventory identities 2026-08-08 08:42:47 -04:00
Bailey Dixon c4d3934cfe chore: backmerge Android 1.7.0 and Server 1.6.0 releases 2026-08-06 21:59:49 -04:00
Bailey Dixon 545d238fd2 Merge pull request #311 from Codename-11/dev
release: Android 1.7.0 and Server 1.6.0
2026-08-06 21:38:49 -04:00
Bailey Dixon 9b36a34e2a release(android): android-v1.7.0 2026-08-06 21:01:01 -04:00
Bailey Dixon 7c35a51aed release(server): server-v1.6.0 2026-08-06 21:00:52 -04:00
Bailey Dixon 474147cb62 test(server): align session TTL route expectations 2026-08-06 20:59:59 -04:00
Bailey Dixon 0bd246586a chore: backmerge released main into dev 2026-08-06 20:16:54 -04:00
Bailey Dixon fc6aaffc11 fix(android): keep restored chats bottom-pinned 2026-08-05 22:08:55 -04:00
Bailey Dixon 197b23f344 feat: resolve Codex effort levels dynamically 2026-08-05 21:28:43 -04:00
Bailey Dixon 0862b4c346 Merge branch 'fix/android-provider-effort-levels' into dev 2026-08-05 21:09:51 -04:00
Bailey Dixon 9c7bc46c7c feat(android): explain reasoning effort compatibility 2026-08-05 21:09:37 -04:00
Bailey Dixon 9554eab757 Merge fix/android-provider-effort-levels into dev 2026-08-05 20:38:32 -04:00
Bailey Dixon 3cacc7d6d6 Merge dev into fix/android-provider-effort-levels
# Conflicts:
#	DEVLOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/viewmodel/ChatViewModel.kt
2026-08-05 20:37:14 -04:00
Bailey Dixon 311888a9fb fix(android): settle chat viewport and pet grounding 2026-08-05 20:35:22 -04:00
Bailey Dixon 96dfe472ef feat: resolve reasoning efforts through relay 2026-08-05 20:34:56 -04:00
Bailey Dixon 7d6a0215ba fix(android): stabilize chat drawer interactions 2026-08-05 19:55:55 -04:00
Bailey Dixon 51ec55e08c fix(android): restore developer settings imports 2026-08-05 19:23:31 -04:00
Bailey Dixon 4edcd18398 Merge fix/standard-voice-speech into dev
# Conflicts:
#	app/src/main/kotlin/com/hermesandroid/relay/viewmodel/VoiceViewModel.kt
2026-08-05 19:19:27 -04:00
Bailey Dixon 3f50a94d03 Merge fix/developer-options-data into dev
# Conflicts:
#	app/src/main/kotlin/com/hermesandroid/relay/data/FeatureFlags.kt
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/ActiveConnectionSections.kt
#	app/src/main/kotlin/com/hermesandroid/relay/ui/screens/DeveloperSettingsScreen.kt
#	app/src/test/kotlin/com/hermesandroid/relay/data/FeatureFlagsTest.kt
#	docs/localization-status.json
2026-08-05 19:18:59 -04:00
Bailey Dixon 94d2231a80 Merge chore/backmerge-main-after-android-1.6.0 into dev 2026-08-05 19:17:30 -04:00
Bailey Dixon 5ac798d5b3 Merge feature/local-dev-work-20260805 into dev 2026-08-05 19:17:17 -04:00
Bailey Dixon ebe1a8ebc4 chore(android): streamline local dev loop 2026-08-05 19:16:36 -04:00
Bailey Dixon fc3a1c169b fix(android): stabilize pet and model sync feedback 2026-08-05 19:08:27 -04:00
Bailey Dixon 6eb2c8bd9e fix(android): smooth active session glow loop 2026-08-05 18:53:31 -04:00
Bailey Dixon cbe323cf6d Merge fix/android-chat-tail-settle into dev 2026-08-05 18:35:50 -04:00
Bailey Dixon 5401e8f274 fix(android): keep completed chat tail stable 2026-08-05 17:58:09 -04:00
Bailey Dixon 0b62afa6c3 Merge feature/android-session-activity-ui into dev 2026-08-05 16:54:50 -04:00
Bailey Dixon 02801dda70 feat(android): surface active session states 2026-08-05 16:52:56 -04:00
Bailey Dixon 39011d5600 Merge pull request #307 from Codename-11/fix/android-focus-pointer-input
fix(android): restore focus voice controls
2026-08-05 16:21:32 -04:00
Bailey Dixon e50c644d09 fix(android): restore focus voice controls 2026-08-05 14:30:20 -04:00
Bailey Dixon 3ff4e7cf8e Merge pull request #304 from Codename-11/fix/android-actionable-diagnostics
fix(android): make connection diagnostics actionable
2026-08-05 10:52:31 -04:00
Bailey Dixon 683d9712d8 fix(android): make connection diagnostics actionable 2026-08-05 10:36:56 -04:00
Bailey Dixon 7ae4a3987e Merge pull request #301 from Codename-11/feature/android-reliability-support
feat(android): unify local reliability reporting
2026-08-04 21:44:52 -04:00
Bailey Dixon 9dcb280eff feat(android): unify local reliability reporting 2026-08-04 21:32:18 -04:00
Bailey Dixon a90067292a Merge pull request #300 from Codename-11/fix/android-chat-render-identity
fix(android): stabilize chat identity and issue labeling
2026-08-04 21:26:06 -04:00
Bailey Dixon 4447886e80 chore(ci): disable automatic issue labeling 2026-08-04 21:15:54 -04:00
Bailey Dixon 5d00885291 fix(android): enforce stable chat render identity 2026-08-04 20:50:41 -04:00
Bailey Dixon bbea5d1b73 Merge pull request #297 from Codename-11/dev
fix(release): repair Server 1.5.1 metadata
2026-08-03 22:25:29 -04:00
Bailey Dixon cce4b9b1d6 Merge pull request #296 from Codename-11/fix/server-1.5.1-release-heading
fix(release): align server 1.5.1 changelog heading
2026-08-03 22:23:19 -04:00
Bailey Dixon d3a4bd5423 fix(release): align server changelog heading 2026-08-03 22:22:38 -04:00
Bailey Dixon c3ff201ecc Merge pull request #294 from Codename-11/dev
release: server-v1.5.1 and android-v1.6.1
2026-08-03 22:20:48 -04:00
Bailey Dixon 20b75d9454 Merge pull request #295 from Codename-11/release/android-1.6.1
release(android): android-v1.6.1
2026-08-03 22:03:27 -04:00
Bailey Dixon d04264a224 release(android): android-v1.6.1 2026-08-03 21:53:39 -04:00
Bailey Dixon ee30ec4bf7 Merge pull request #293 from Codename-11/release/server-1.5.1
release(server): server-v1.5.1
2026-08-03 21:50:58 -04:00
Bailey Dixon 111c5409bf release(server): server-v1.5.1 2026-08-03 21:49:50 -04:00
Bailey Dixon 03ce9aa8d5 Merge pull request #291 from Codename-11/fix/android-relay-session-recovery
fix: repair Relay recovery and Android session UX
2026-08-03 21:46:33 -04:00
Bailey Dixon 41c2d10700 fix(android): refresh localization source hashes 2026-08-03 21:36:59 -04:00
Bailey Dixon c508392261 Merge dev into fix/android-relay-session-recovery 2026-08-03 20:40:45 -04:00
Bailey Dixon e9c0620d24 fix(android): hide clean-view hint during voice mode 2026-08-03 20:38:08 -04:00
Bailey Dixon 217746a243 Merge fix/android-int-map-crash into dev
# Conflicts:
#	CHANGELOG.md
2026-08-03 20:21:29 -04:00
Bailey Dixon a40e6a5b01 Merge origin/dev into dev
# Conflicts:
#	CHANGELOG.md
2026-08-03 20:21:05 -04:00
Bailey Dixon 118bf07638 fix(android): stabilize message text selection 2026-08-03 20:20:10 -04:00
Bailey Dixon 95f6721b06 Merge pull request #290 from Codename-11/fix/android-mic-handoff-hardening
fix(android): harden microphone capture handoff
2026-08-03 20:16:13 -04:00
Bailey Dixonandluimu64 ac023c0e24 fix(android): harden microphone capture handoff
Wait for barge-in microphone teardown without blocking the UI, cancel abandoned pending captures, and classify AudioRecord startup failures with actionable localized guidance.

Co-authored-by: luimu64 <luimu@luimu.dev>
2026-08-03 20:05:17 -04:00
Bailey Dixon cd7792918e Merge fix/android-relay-session-recovery into dev 2026-08-03 18:46:28 -04:00
Bailey Dixon e617809930 fix(android): reconnect Relay without stale backoff 2026-08-03 18:38:35 -04:00
Bailey Dixon 79532c6c9b Merge fix/android-relay-session-recovery into dev 2026-08-03 17:57:17 -04:00
Bailey Dixon 0af1cda38e fix: repair optional Relay session recovery 2026-08-03 17:57:05 -04:00
Bailey Dixon 454bd44e7a Merge fix/android-session-list-pagination into dev 2026-08-03 17:11:05 -04:00
Bailey Dixon b92a40174e fix(android): page session drawer requests 2026-08-03 17:10:48 -04:00
dependabot[bot] c6ab26ef13 chore(deps): bump com.microsoft.onnxruntime:onnxruntime-android (#288)
Bumps [com.microsoft.onnxruntime:onnxruntime-android](https://github.com/microsoft/onnxruntime) from 1.27.0 to 1.28.0.
- [Release notes](https://github.com/microsoft/onnxruntime/releases)
- [Changelog](https://github.com/microsoft/onnxruntime/blob/main/docs/ReleaseManagement.md)
- [Commits](https://github.com/microsoft/onnxruntime/compare/v1.27.0...v1.28.0)

---
updated-dependencies:
- dependency-name: com.microsoft.onnxruntime:onnxruntime-android
  dependency-version: 1.28.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-03 11:56:37 +00:00
dependabot[bot] 414ade5fa0 chore(deps): bump gradle/actions from 6 to 6.2.0 (#287)
Bumps [gradle/actions](https://github.com/gradle/actions) from 6 to 6.2.0.
- [Release notes](https://github.com/gradle/actions/releases)
- [Commits](https://github.com/gradle/actions/compare/v6...v6.2.0)

---
updated-dependencies:
- dependency-name: gradle/actions
  dependency-version: 6.2.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-03 11:55:44 +00:00
Bailey Dixon 9fdb11ae94 chore(android): script foreground service demo capture 2026-08-02 20:56:31 -04:00
Bailey Dixon fd35c9b2b6 docs(android): document Play foreground services 2026-08-02 19:47:52 -04:00
Bailey Dixon 9dc625ddd0 chore: backmerge Android 1.6.0 release 2026-08-02 19:46:48 -04:00
Bailey Dixon e5b25ab650 Merge pull request #284 from Codename-11/dev
release(android): android-v1.6.0
2026-08-02 19:28:01 -04:00
Bailey Dixon ea16750af4 Merge pull request #283 from Codename-11/release/android-1.6.0
release(android): android-v1.6.0
2026-08-02 18:58:50 -04:00
Bailey Dixon 7ae95915bf chore(release): reconcile Server 1.5.0 main release 2026-08-02 18:58:33 -04:00
Bailey Dixon c85f42c51c Merge pull request #279 from Codename-11/dev
release(server): server-v1.5.0
2026-08-02 18:58:20 -04:00
Bailey Dixon 15e0106648 fix(android): preserve legacy collection compatibility 2026-08-02 18:55:21 -04:00
Bailey Dixon 58d7e8581b chore(release): reconcile dev before Android 1.6.0
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
2026-08-02 18:51:59 -04:00
Bailey Dixon 8c570b214d Merge pull request #281 from Codename-11/fix/mobile-plugin-path-containment
fix(plugins): contain generated page paths
2026-08-02 18:42:04 -04:00
Bailey Dixon 52f19ca028 fix(plugins): contain generated page paths 2026-08-02 18:40:47 -04:00
Bailey Dixon acc7daa6f2 fix(dev): restore UI preview compilation 2026-08-02 18:29:45 -04:00
Bailey Dixon 9ca42e3e6c Merge pull request #280 from Codename-11/chore/reconcile-main-before-server-1.5.0
chore: reconcile main release history into dev
2026-08-02 18:28:11 -04:00
Bailey Dixon 781969d782 chore(release): reconcile Server 1.5.0 into Android 1.6.0
# Conflicts:
#	CHANGELOG.md
2026-08-02 18:19:47 -04:00
Bailey Dixon 279b83a77c release(android): prepare android-v1.6.0 2026-08-02 18:19:17 -04:00
Bailey Dixon 2f949c7d15 chore: reconcile main release history into dev 2026-08-02 18:17:50 -04:00
Bailey Dixon c77fd057bb Merge pull request #278 from Codename-11/release/server-1.5.0
release(server): server-v1.5.0
2026-08-02 18:16:25 -04:00
Bailey Dixon ed1c47f47d release(server): server-v1.5.0 2026-08-02 18:14:51 -04:00
Bailey Dixon c1800a3ddd chore(release): reconcile dev before Android 1.6.0
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/ThinkingBlock.kt
#	app/src/main/kotlin/com/hermesandroid/relay/voice/VoiceOverlayHost.kt
#	app/src/main/res/values-b+pt+BR/strings.xml
#	app/src/main/res/values-b+zh+Hans/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values/strings.xml
#	docs/localization-status.json
2026-08-02 18:14:45 -04:00
Bailey Dixon f5c2a2b888 feat(plugins): add live Android plugin surfaces 2026-08-02 18:14:42 -04:00
Bailey Dixon 3ec5a09885 chore(release): reconcile main before Android 1.6.0
# Conflicts:
#	DEVLOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/VoiceModeOverlay.kt
#	app/src/test/kotlin/com/hermesandroid/relay/ui/components/VoiceModeOverlayStateTest.kt
2026-08-02 18:09:37 -04:00
Bailey Dixon 2a8038a1bd Merge fix/android-pet-mvp-hardening into dev 2026-08-02 14:08:37 -04:00
Bailey Dixon d0684dd252 fix(android): harden floating pet mvp 2026-08-02 14:08:18 -04:00
Bailey Dixon dae75ebe13 feat(android): improve pet route inspector 2026-08-02 13:36:20 -04:00
Bailey Dixon 82fb46b914 Merge fix/android-list-identity-dev into dev 2026-08-02 13:17:30 -04:00
Bailey Dixon 3ac74404bf fix(android): keep pet inspector below app header 2026-08-02 13:12:04 -04:00
Bailey Dixon 9187d8e77c Merge pull request #277 from Codename-11/feature/russian-localization-salvage
feat(android): add Russian localization
2026-08-02 13:11:28 -04:00
Bailey Dixon 9b7bf0f7fd fix(android): preserve streamed list identity 2026-08-02 13:09:20 -04:00
Bailey Dixon a59b54c600 feat(android): collapse pet path inspector by default 2026-08-02 13:07:54 -04:00
Bailey Dixon 9c56598438 feat(android): improve pet terrain inspector 2026-08-02 13:03:25 -04:00
Bailey DixonandDScoNOIZ 4efc52dd5b feat(android): add Russian localization
Salvaged from #276 by @DScoNOIZ.

Co-authored-by: DScoNOIZ <212546794+DScoNOIZ@users.noreply.github.com>
2026-08-02 13:02:57 -04:00
Bailey Dixon b274e6f2a6 feat(android): expand floating pet terrain roaming 2026-08-02 12:28:54 -04:00
Bailey Dixon 6f5c49be17 Merge feature/android-live-plugins into dev
# Conflicts:
#	docs/localization-status.json
2026-08-02 11:39:59 -04:00
Bailey Dixon b328370d32 feat(plugins): add live Android plugin surfaces 2026-08-02 11:38:18 -04:00
Bailey Dixon 0e1d70e8ff fix(android): recover pets from occupied terrain 2026-08-02 10:53:22 -04:00
Bailey Dixon 4ea41386ee fix(android): constrain pet terrain routes 2026-08-02 10:46:59 -04:00
Bailey Dixon 6ac7e5457f feat(android): distinguish possible pet routes 2026-08-02 10:12:08 -04:00
Bailey Dixon 46463f4b00 feat(android): use narrow bubbles as pet hop points 2026-08-02 09:54:12 -04:00
Bailey Dixon 2f72c5444c feat(android): visualize and explore pet terrain 2026-08-02 09:28:09 -04:00
Bailey Dixon ecc97416fc feat(android): add bounded pet terrain journeys 2026-08-02 08:40:27 -04:00
Bailey Dixon 88667eea89 fix(android): hop from measured bubble edges 2026-08-02 07:03:49 -04:00
Bailey Dixon febd938651 fix(android): escape pet from invalid bubble overlap 2026-08-01 22:41:41 -04:00
Bailey Dixon 9419615068 fix(android): recover pet from scrolling chat bubbles 2026-08-01 22:34:33 -04:00
Bailey Dixon 8e4fffab6d fix(android): observe settings pet scroll state 2026-08-01 22:23:32 -04:00
Bailey Dixon 1112a622a7 fix(android): recover pet roaming after scroll 2026-08-01 22:20:03 -04:00
Bailey Dixon 285342bf7e fix(android): keep pet clear of chat scroll control 2026-08-01 22:09:04 -04:00
Bailey Dixon 401acdda8e fix(android): keep floating pet interactive during input 2026-08-01 21:58:22 -04:00
Bailey Dixon a0299d62ca feat(android): preserve pet roaming after drag 2026-08-01 21:49:45 -04:00
Bailey Dixon 4f37b87a3d feat(android): refine floating pet experience 2026-08-01 21:36:34 -04:00
Bailey Dixon 7d3ad1c19f fix(android): make pet visit chat surfaces 2026-08-01 20:55:41 -04:00
Bailey Dixon 54e069888d Merge branch 'docs/pet-experience' into dev 2026-08-01 20:35:28 -04:00
Bailey Dixon 7d3ebfb842 fix(android): localize pet capability previews 2026-08-01 20:35:23 -04:00
Bailey Dixon 7d9552bf1e docs(android): document interactive pet behavior 2026-08-01 20:29:55 -04:00
Bailey Dixon 73c0b6c99d fix(android): label mirrored pet travel accurately 2026-08-01 20:26:09 -04:00
Bailey Dixon 9b68577c47 feat(android): apply pet temperament pacing 2026-08-01 20:23:16 -04:00
Bailey Dixon ec3ff1da02 Merge branch 'feature/android-pet-route-surfaces' into dev 2026-08-01 20:15:30 -04:00
Bailey Dixon 0d78077393 Merge branch 'feature/petdex-capability-preview' into dev 2026-08-01 20:15:29 -04:00
Bailey Dixon eaf345b9c7 Merge branch 'feature/android-pet-temperament' into dev 2026-08-01 20:15:28 -04:00
Bailey Dixon 2d4afd035c Merge branch 'feature/android-pet-core-motion' into dev 2026-08-01 20:15:28 -04:00
Bailey Dixon b5f3eba340 feat(android): make pet roaming intentional 2026-08-01 20:12:29 -04:00
Bailey Dixon e6c48d5fa9 feat(android): preview pet animation capabilities 2026-08-01 20:09:58 -04:00
Bailey Dixon eed739c3a3 feat(android): add pet temperament preferences 2026-08-01 20:09:23 -04:00
Bailey Dixon 91ddebde79 feat(android): add pet roaming to app status chrome 2026-08-01 20:06:19 -04:00
Bailey Dixon a1d99f390f fix(android): keep pet clear of chat content 2026-08-01 19:55:16 -04:00
Bailey Dixon af284952e7 Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 19:49:27 -04:00
Bailey Dixon 4b872f3f54 Merge branch 'fix/android-route-resilience' into feature/android-pet-roaming 2026-08-01 19:46:57 -04:00
Bailey Dixon b725f2b295 feat(android): prefer pet bubble perches 2026-08-01 19:45:55 -04:00
Bailey Dixon 0359fb46ff fix(android): stabilize relay route failover 2026-08-01 19:44:45 -04:00
Bailey Dixon 0e8ab74685 feat(android): enrich pet overlay roaming 2026-08-01 19:38:30 -04:00
Bailey Dixon f49b8d8161 Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 13:57:15 -04:00
Bailey Dixon 8361a059e8 fix(android): avoid stale pet visit targets 2026-08-01 13:46:12 -04:00
Bailey Dixon f6c222ced5 feat(android): animate post-response pet visits 2026-08-01 13:41:27 -04:00
Bailey Dixon 05cda21119 feat(android): schedule post-response pet visits 2026-08-01 13:36:26 -04:00
Bailey Dixon 310893a49a feat(android): add bubble visit routing 2026-08-01 13:36:02 -04:00
Bailey Dixon 09c48efecf fix(android): prioritize pet locomotion states 2026-08-01 13:31:55 -04:00
Bailey Dixon 748c3b1c07 feat(android): add assistant pet visit targets 2026-08-01 13:31:23 -04:00
Bailey Dixon 259d64fe30 fix(android): hold pet drop until state syncs 2026-08-01 13:26:25 -04:00
Bailey Dixon e2044a15ea Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 11:38:13 -04:00
Bailey Dixon 33cc622643 fix(android): preserve manual pet placement 2026-08-01 11:25:01 -04:00
Bailey Dixon 2c388a4c73 fix(android): add obstacle-aware pet hops 2026-08-01 11:21:46 -04:00
Bailey Dixon a4323a6b04 fix(android): smooth pet movement states 2026-08-01 11:15:53 -04:00
Bailey Dixon af6680090f fix(android): refresh pet surface activity 2026-08-01 11:13:56 -04:00
Bailey Dixon 54362c7d31 Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 10:36:02 -04:00
Bailey Dixon 40837013c7 feat(android): add element-aware pet roaming 2026-08-01 10:35:49 -04:00
Bailey Dixon 70edc5e73f Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 09:48:55 -04:00
Bailey Dixon 55e8486f94 fix(android): animate pet roam locomotion 2026-08-01 09:48:47 -04:00
Bailey Dixon ab4519d4cf Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 09:35:50 -04:00
Bailey Dixon d5cfa2bf5c fix(android): match desktop pet overlay behavior 2026-08-01 09:35:34 -04:00
Bailey Dixon c5376b2c25 Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 09:14:19 -04:00
Bailey Dixon ee33666e1f fix(android): dock pet at chat end edge by default 2026-08-01 09:14:14 -04:00
Bailey Dixon c357f201c6 Merge branch 'feature/android-pet-roaming' into dev 2026-08-01 08:53:18 -04:00
Bailey Dixon 17a439cfaa feat(android): add roaming Petdex companions 2026-08-01 08:53:04 -04:00
Bailey Dixon 6b888e91d3 Merge Petdex preview cache follow-up into dev 2026-07-31 23:47:09 -04:00
Bailey Dixon 0793f9213c perf(android): prioritize cached pet previews 2026-07-31 23:47:04 -04:00
Bailey Dixon 146652e475 Merge Petdex preview retry follow-up into dev 2026-07-31 23:45:33 -04:00
Bailey Dixon 9bdaf3a02f fix(android): retry Petdex preview loading 2026-07-31 23:45:27 -04:00
Bailey Dixon e08d0e13a4 Merge branch 'feature/petdex-previews' into dev 2026-07-31 23:43:43 -04:00
Bailey Dixon 3c10c67075 feat(android): add Petdex gallery previews 2026-07-31 23:43:38 -04:00
Bailey Dixon e8e51d9ee4 Merge branch 'feature/android-floating-pet' into dev
# Conflicts:
#	CHANGELOG.md
#	app/src/main/kotlin/com/hermesandroid/relay/ui/components/MessageBubble.kt
2026-07-31 22:59:35 -04:00
Bailey Dixon dd5a80d03c fix(android): recover stalled voice output 2026-07-31 22:58:34 -04:00
Bailey Dixon 06a2f35144 feat(android): add floating pets and Petdex 2026-07-31 22:57:30 -04:00
Bailey Dixon 3d78e79c5d feat(android): refine voice mode and overlay 2026-07-31 22:35:18 -04:00
Bailey Dixon 50f745d9da Merge branch 'fix/android-standard-voice-oom' into dev
# Conflicts:
#	CHANGELOG.md
#	app/src/test/kotlin/com/hermesandroid/relay/network/upstream/StandardHermesVoiceClientTest.kt
2026-07-31 21:46:04 -04:00
Bailey Dixon 33e8a11615 fix(android): stream standard voice transcription uploads 2026-07-31 21:43:12 -04:00
Bailey Dixon 21bbad5f3b Merge branch 'fix/android-r8-resource-shrinking' into dev 2026-07-31 21:04:30 -04:00
Bailey Dixon 6524157549 fix(android): enable release resource shrinking 2026-07-31 21:04:17 -04:00
Bailey Dixon e8192b09dd docs(android): clarify voice stop dependency 2026-07-31 19:45:31 -04:00
Bailey Dixon ef3916a143 feat(android): align voice interruption with upstream 2026-07-31 19:30:53 -04:00
Bailey Dixon f2b92b2755 Merge pull request #274 from Codename-11/fix/android-1.5.3-voice-transcript-keys
release(android): Android 1.5.3 duplicate-key hotfix
2026-07-31 19:03:40 -04:00
Bailey Dixon 8651656899 release(android): android-v1.5.3 2026-07-31 18:50:21 -04:00
Bailey Dixon b458d83fcc fix(android): stabilize voice transcript keys 2026-07-31 18:27:59 -04:00
Bailey Dixon f4ae8d21ca fix(android): preserve passport shell in identity editor 2026-07-31 17:26:56 -04:00
Bailey Dixon b2f8070a1b feat(android): refine agent passport controls 2026-07-31 17:05:49 -04:00
Bailey Dixon 27f1393ea7 Merge branch 'feature/android-assistant-overlay' into dev 2026-07-31 15:44:26 -04:00
Bailey Dixon d8f8082639 feat(android): unify assistant voice surfaces 2026-07-31 15:44:20 -04:00
Bailey Dixon 5df42c1fda Merge branch 'feature/android-agent-passport-v2' into dev 2026-07-31 15:15:07 -04:00
Bailey Dixon 778c15de7f feat(android): deepen agent passport details 2026-07-31 15:14:58 -04:00
Bailey Dixon a606eb7c40 Merge branch 'fix/android-assistant-picker' into dev 2026-07-30 19:53:17 -04:00
Bailey Dixon a4df726bae fix(android): support voice-task assistant launch 2026-07-30 19:53:12 -04:00
Bailey Dixon f87de0f96a Merge branch 'fix/android-assistant-picker' into dev 2026-07-30 19:46:49 -04:00
Bailey Dixon 2471c3dd55 fix(android): activate selected assistant service 2026-07-30 19:46:42 -04:00
Bailey Dixon c53b0c6aa3 Merge branch 'fix/android-assistant-picker' into dev 2026-07-30 19:38:49 -04:00
Bailey Dixon 8ade8debf0 fix(android): expose assistant picker entry point 2026-07-30 19:38:42 -04:00
Bailey Dixon e84eeb8e4f Merge branch 'fix/android-wake-strictness-default' into dev 2026-07-30 19:23:52 -04:00
Bailey Dixon d28f0d5de7 fix(android): tune wake strictness defaults 2026-07-30 19:23:47 -04:00
Bailey Dixon c680f6f896 Merge branch 'feature/android-full-assistant-mode' into dev 2026-07-30 19:15:34 -04:00
Bailey Dixon 7df350365c feat(android): add opt-in digital assistant mode 2026-07-30 19:02:06 -04:00
Bailey Dixon 0795565a4d Merge branch 'feature/android-voice-wake-parity' into dev 2026-07-30 18:39:58 -04:00
Bailey Dixon fe4ef2441c fix(android): resume enabled wake listener visibly 2026-07-30 18:39:53 -04:00
Bailey Dixon 042f5c0927 Merge branch 'fix/android-voice-transcript-keys' into dev
# Conflicts:
#	CHANGELOG.md
#	DEVLOG.md
2026-07-30 18:28:01 -04:00
Bailey Dixon 2998773e70 fix(android): stabilize voice transcript keys 2026-07-30 18:27:31 -04:00
Bailey Dixon 91ab611b54 Merge branch 'feature/android-voice-wake-parity' into dev 2026-07-30 18:23:20 -04:00
Bailey Dixon c76d0bf33e fix(android): stabilize local wake activation 2026-07-30 18:23:05 -04:00
Bailey Dixon ff965305d2 Merge branch 'feature/android-voice-wake-parity' into dev 2026-07-29 21:20:31 -04:00
Bailey Dixon a7d76d56e5 feat(android): absorb upstream voice and wake parity 2026-07-29 20:24:16 -04:00
Bailey Dixon 6e1e3d8b38 Merge branch 'feature/open-ledger-batches' into dev 2026-07-28 21:49:40 -04:00
Bailey Dixon 04944ffe8d feat(android): consume upstream profile and gateway contracts 2026-07-28 21:47:27 -04:00
Bailey Dixon 34cf109804 Merge origin/dev into dev 2026-07-28 21:05:11 -04:00
Bailey Dixon e459f24a1a Merge branch 'fix/android-agent-passport-drawer' into dev 2026-07-28 21:04:53 -04:00
Bailey Dixon 4346e33fd4 fix(android): repair agent passport drawer flow 2026-07-28 21:04:47 -04:00
Bailey Dixon ca0c5b2a54 Merge pull request #266 from Codename-11/fix/android-https-gateway-route
fix(android): preserve secure gateway routes
2026-07-28 21:04:31 -04:00
Bailey Dixon 77e34c2c02 fix(android): preserve secure gateway routes 2026-07-28 19:35:14 -04:00
Bailey Dixon f4ee409106 docs(devlog): record Android 1.5.2 release 2026-07-28 18:20:37 -04:00
Bailey Dixon aa26f7c9b6 Merge pull request #265 from Codename-11/dev
release(android): android-v1.5.2
2026-07-28 17:58:37 -04:00
Bailey Dixon bfb608bea6 release(android): android-v1.5.2 2026-07-28 17:30:59 -04:00
Bailey Dixon 95a95fe7d2 Merge pull request #264 from Codename-11/fix/android-nous-native-auth
fix(android): support Nous system-browser sign-in
2026-07-28 17:28:56 -04:00
Bailey Dixon 1bdf2ae71b fix(android): support Nous system-browser sign-in 2026-07-28 17:15:26 -04:00
Bailey Dixon f9e7a2f320 Merge pull request #263 from Codename-11/fix/android-duplicate-compose-keys
fix(android): coalesce replayed chat message ids
2026-07-27 11:38:06 -04:00
Bailey Dixon 988fac8522 Merge pull request #262 from Codename-11/fix/android-oidc-manage-callback
fix(android): keep dashboard OIDC on cookie flow
2026-07-27 11:37:43 -04:00
Bailey Dixon d4832a6a38 fix(android): coalesce replayed chat message ids 2026-07-27 09:30:39 -04:00
Bailey Dixon 325b8e5670 Merge pull request #257 from Codename-11/dev
release(android): promote android-v1.5.1
2026-07-26 16:11:49 -04:00
Bailey Dixon 0e6d64f987 fix(android): restore standard voice narration 2026-07-26 08:42:04 -04:00
Bailey Dixon e9da59cf40 Merge pull request #254 from Codename-11/dev
fix(android): repair immutable release dispatch
2026-07-25 18:30:53 -04:00
Bailey Dixon c9a03c9ed7 Merge pull request #252 from Codename-11/dev
release(android): android-v1.5.0
2026-07-25 18:26:34 -04:00
Bailey Dixon e3bc816624 fix(android): repair developer options and data actions 2026-07-25 16:29:36 -04:00
dependabot[bot] de9211b7c5 chore(deps): bump actions/setup-node from 4 to 7
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 7.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v7)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-25 18:37:14 +00:00
dependabot[bot] 7ca5c61be5 chore(deps): bump actions/setup-python from 6 to 7
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 6 to 7.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v6...v7)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-20 11:55:24 +00:00
Bailey Dixon 68f8b58a0b Merge pull request #232 from Codename-11/dev
release(android): android-v1.4.9
2026-07-19 21:27:28 -04:00
767 changed files with 112746 additions and 9048 deletions
+4 -4
View File
@@ -63,7 +63,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
@@ -95,7 +95,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
@@ -139,7 +139,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
@@ -203,7 +203,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
+1 -1
View File
@@ -67,7 +67,7 @@ jobs:
fetch-depth: 1
- name: Set up Python 3.11
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
run: npm run build
- name: Setup Python
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
+4 -2
View File
@@ -100,13 +100,15 @@ jobs:
with:
node-version: '22'
cache: npm
cache-dependency-path: desktop/package-lock.json
cache-dependency-path: |
desktop/package-lock.json
desktop/tray/package-lock.json
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Install deps
run: npm ci
run: npm ci && npm --prefix tray ci
- name: Check tray formatting
run: npm run tray:fmt
+2 -2
View File
@@ -44,7 +44,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Python 3.11
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
@@ -84,7 +84,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Python 3.11
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
working-directory: website
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
-65
View File
@@ -1,65 +0,0 @@
name: Issue Triage
on:
issues:
types: [opened]
workflow_dispatch:
inputs:
issue_number:
description: "Issue number to label again"
required: true
type: string
concurrency:
group: issue-triage-${{ github.event.issue.number || github.event.inputs.issue_number }}
cancel-in-progress: false
permissions:
contents: read
issues: write
jobs:
auto-label:
if: >
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issues' && github.event.issue.user.type != 'Bot')
runs-on: ubuntu-latest
steps:
- name: Label from title prefix and issue area
uses: actions/github-script@v8
env:
ISSUE_NUMBER: ${{ github.event.issue.number || github.event.inputs.issue_number }}
with:
script: |
const issue_number = Number(process.env.ISSUE_NUMBER);
const { data: issue } = await github.rest.issues.get({
owner: context.repo.owner, repo: context.repo.repo, issue_number,
});
const title = (issue.title || '').toLowerCase();
const body = (issue.body || '').toLowerCase();
const haystack = `${title}\n${body}`;
const labels = [];
if (title.startsWith('[bug]')) labels.push('bug');
else if (title.startsWith('[feature]') || title.startsWith('[feat]')) labels.push('enhancement');
else if (title.startsWith('[docs]')) labels.push('documentation');
if (/\b(cli|desktop|terminal|daemon|pty|hermes-relay (install|binary|tray))\b/.test(haystack)) labels.push('area:cli');
else if (/\b(dashboard|plugin ui|react)\b/.test(haystack)) labels.push('area:dashboard');
else if (/\b(relay|plugin|aiohttp|python|pairing|voice (transcribe|synthesize)|bridge (endpoint|route))\b/.test(haystack)) labels.push('area:plugin');
else if (/\b(readme|user-?docs|documentation)\b/.test(haystack)) labels.push('area:docs');
else if (/\b(android|app|compose|apk|phone|samsung|gradle|chat|voice|notification|sphere|keystore)\b/.test(haystack)) labels.push('area:android');
if (!labels.length) {
core.info('No deterministic label matched; leaving the issue for maintainer triage.');
return;
}
try {
await github.rest.issues.addLabels({
owner: context.repo.owner, repo: context.repo.repo, issue_number, labels,
});
core.info(`Applied labels: ${labels.join(', ')}`);
} catch (error) {
core.warning(`Could not apply ${labels.join(', ')}: ${error.message}`);
}
+2 -2
View File
@@ -44,7 +44,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.12"
@@ -76,7 +76,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: false
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: false
+15 -2
View File
@@ -125,7 +125,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: false
@@ -163,7 +163,7 @@ jobs:
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: false
@@ -191,6 +191,19 @@ jobs:
# app/build/outputs/bundle/sideloadRelease/hermes-relay-<version>-sideload-release.aab
run: ./gradlew bundleRelease assembleRelease
# The Play AAB carries its mapping for Play Console deobfuscation, but
# sideload issue reports need the exact mapping from this immutable build.
# Keep both variants as a workflow artifact (not a public release asset).
- name: Retain R8 mappings for retrace
uses: actions/upload-artifact@v7
with:
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ github.sha }}
path: |
app/build/outputs/mapping/googlePlayRelease/mapping.txt
app/build/outputs/mapping/sideloadRelease/mapping.txt
if-no-files-found: error
retention-days: 90
- name: Scan release DEX for unsupported collection APIs
run: |
python3 scripts/check-android-collection-apis.py \
+186 -8
View File
@@ -80,7 +80,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.x'
bun-version-file: 'desktop/.bun-version'
- name: Install deps
run: npm ci
@@ -153,6 +153,40 @@ jobs:
desktop/dist/bin/hermes-relay-darwin-arm64
retention-days: 7
smoke-windows-cli-release-asset:
name: Smoke exact Windows CLI release asset
runs-on: windows-latest
needs:
- validate-release
- build-cli-binaries
steps:
- uses: actions/download-artifact@v8
with:
name: cli-binaries
path: release-assets
- name: Repeated launch and process cleanup gate
shell: pwsh
env:
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
run: |
$ErrorActionPreference = 'Stop'
$exe = (Resolve-Path 'release-assets/hermes-relay-win-x64.exe').Path
1..20 | ForEach-Object {
$output = & $exe --version
if ($LASTEXITCODE -ne 0) { throw "Windows CLI smoke failed with exit $LASTEXITCODE" }
if ($output -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
throw "Unexpected Windows CLI version output: $output"
}
}
Start-Sleep -Milliseconds 500
$leftovers = Get-CimInstance Win32_Process | Where-Object {
$_.ExecutablePath -eq $exe
}
if ($leftovers) {
throw "Windows CLI smoke left $(@($leftovers).Count) process(es) behind"
}
build-windows-tray-installer:
name: Build Windows tray installer
runs-on: windows-latest
@@ -168,18 +202,20 @@ jobs:
with:
node-version: '22'
cache: npm
cache-dependency-path: desktop/package-lock.json
cache-dependency-path: |
desktop/package-lock.json
desktop/tray/package-lock.json
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.x'
bun-version-file: 'desktop/.bun-version'
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Install deps
run: npm ci
run: npm ci && npm --prefix tray ci
- name: Type-check
run: npm run type-check
@@ -213,12 +249,153 @@ jobs:
$proc = Start-Process -FilePath tray/target/release/hermes-relay-tray.exe -WindowStyle Hidden -PassThru
Start-Sleep -Seconds 5
if ($proc.HasExited) { throw "tray app exited early with code $($proc.ExitCode)" }
$proc.Refresh()
if ($proc.MainWindowHandle -ne 0) { throw 'menu-only systray created an application window' }
$traySize = (Get-Item tray/target/release/hermes-relay-tray.exe).Length
if ($traySize -gt 5242880) { throw "tray executable exceeds 5 MiB: $traySize bytes" }
if ($traySize -le 0) { throw 'tray executable is empty' }
Stop-Process -Id $proc.Id -Force
Write-Host "menu-only tray launch smoke OK pid=$($proc.Id) bytes=$traySize"
Write-Host "management tray launch smoke OK pid=$($proc.Id) bytes=$traySize"
- name: Smoke-test packaged installer lifecycle
shell: pwsh
env:
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
run: |
$ErrorActionPreference = 'Stop'
function Normalize-UserPath([string]$Value) {
return (@($Value -split ';' | Where-Object { $_ }) -join ';')
}
function Get-RawUserPath {
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
if ($null -eq $environmentKey) { return '' }
try {
return [string]$environmentKey.GetValue(
'Path',
'',
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
)
} finally {
$environmentKey.Dispose()
}
}
$setup = (Resolve-Path 'dist/tray/hermes-relay-windows-x64-setup.exe').Path
$smokeRoot = Join-Path $env:RUNNER_TEMP 'hermes-installer-lifecycle-smoke'
$smokeProfile = Join-Path $smokeRoot 'profile'
$installDir = Join-Path $smokeRoot 'installed files'
$sessionDir = Join-Path $smokeProfile '.hermes'
$sessionSentinel = Join-Path $sessionDir 'remote-sessions.json'
$uninstaller = Join-Path $installDir 'uninstall-hermes-relay.exe'
$uninstallKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\HermesRelay'
$productKey = 'HKCU:\Software\HermesRelay'
$startupKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
$startMenuDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Hermes-Relay CLI'
$oldUserProfile = $env:USERPROFILE
$oldHomeEnv = $env:HOME
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
$hadUserPath = $environmentKey.GetValueNames() -contains 'Path'
$originalUserPath = Get-RawUserPath
$originalUserPathKind = if ($hadUserPath) { $environmentKey.GetValueKind('Path') } else { $null }
$userPathBefore = 'C:\Windows\System32'
$environmentKey.Dispose()
$startupBefore = (Get-ItemProperty -Path $startupKey -Name HermesRelayTray -ErrorAction SilentlyContinue).HermesRelayTray
if (Test-Path $uninstallKey) { throw 'installer smoke requires a clean HermesRelay uninstall registry key' }
if (Test-Path $productKey) { throw 'installer smoke requires a clean HermesRelay product registry key' }
if (Test-Path $smokeRoot) { Remove-Item -LiteralPath $smokeRoot -Recurse -Force }
New-Item -ItemType Directory -Force -Path $sessionDir | Out-Null
Set-Content -LiteralPath $sessionSentinel -Value '{"sentinel":"preserve-me"}' -Encoding UTF8
$env:USERPROFILE = $smokeProfile
$env:HOME = $smokeProfile
try {
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
$environmentKey.SetValue('Path', $userPathBefore, [Microsoft.Win32.RegistryValueKind]::String)
$environmentKey.Dispose()
$installProcess = Start-Process -FilePath $setup -ArgumentList @('/S', "/D=$installDir") -Wait -PassThru
if ($installProcess.ExitCode -ne 0) { throw "installer exited with code $($installProcess.ExitCode)" }
$expectedFiles = @(
'hermes-relay.exe',
'hermes-relay-tray.exe',
'hermes-relay-ui.cmd',
'hermes-relay-path.ps1',
'uninstall-hermes-relay.exe'
)
foreach ($name in $expectedFiles) {
$path = Join-Path $installDir $name
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
throw "packaged installer did not create $path"
}
}
$cli = Join-Path $installDir 'hermes-relay.exe'
$versionOutput = (& $cli --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) { throw "installed CLI --version exited with code $LASTEXITCODE" }
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
throw "installed CLI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$versionOutput'"
}
$helpOutput = (& $cli --help | Out-String)
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
throw 'installed CLI --help smoke failed'
}
if (-not (Test-Path -LiteralPath $sessionSentinel -PathType Leaf)) {
throw 'installer removed profile session data'
}
$uninstallProcess = Start-Process -FilePath $uninstaller -ArgumentList '/S' -Wait -PassThru
if ($uninstallProcess.ExitCode -ne 0) { throw "uninstaller exited with code $($uninstallProcess.ExitCode)" }
$deadline = [DateTime]::UtcNow.AddSeconds(20)
while ((Test-Path -LiteralPath $uninstaller) -and [DateTime]::UtcNow -lt $deadline) {
Start-Sleep -Milliseconds 250
}
foreach ($name in $expectedFiles) {
$path = Join-Path $installDir $name
if (Test-Path -LiteralPath $path) { throw "uninstaller left owned artifact $path" }
}
if (Test-Path $uninstallKey) { throw 'uninstaller left the Installed Apps registry key' }
if (Test-Path $productKey) { throw 'uninstaller left the HermesRelay product registry key' }
if (Test-Path -LiteralPath $startMenuDir) { throw "uninstaller left Start-menu artifacts at $startMenuDir" }
if (-not (Test-Path -LiteralPath $sessionSentinel -PathType Leaf)) {
throw 'uninstaller removed preserved profile session data'
}
if ((Get-Content -LiteralPath $sessionSentinel -Raw) -notmatch 'preserve-me') {
throw 'installer lifecycle modified preserved profile session data'
}
# Compare the raw registry value so expandable entries such as
# %USERPROFILE% are not resolved against the isolated smoke profile.
$userPathAfter = Normalize-UserPath (Get-RawUserPath)
if ($userPathAfter -ne $userPathBefore) {
throw "uninstaller did not restore user PATH (before='$userPathBefore', after='$userPathAfter')"
}
$startupAfter = (Get-ItemProperty -Path $startupKey -Name HermesRelayTray -ErrorAction SilentlyContinue).HermesRelayTray
if ($startupAfter -ne $startupBefore) {
throw "installer lifecycle changed the pre-existing tray startup preference"
}
Write-Host "packaged installer lifecycle smoke OK version=$versionOutput install=$installDir"
} finally {
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
Stop-Process -Force -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath $uninstaller) {
Start-Process -FilePath $uninstaller -ArgumentList '/S' -Wait | Out-Null
}
$env:USERPROFILE = $oldUserProfile
$env:HOME = $oldHomeEnv
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
if ($hadUserPath) {
$environmentKey.SetValue('Path', $originalUserPath, $originalUserPathKind)
} else {
$environmentKey.DeleteValue('Path', $false)
}
$environmentKey.Dispose()
if (Test-Path -LiteralPath $smokeRoot) {
Remove-Item -LiteralPath $smokeRoot -Recurse -Force -ErrorAction SilentlyContinue
}
}
- name: Upload Windows tray release asset
uses: actions/upload-artifact@v4
@@ -232,6 +409,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build-cli-binaries
- smoke-windows-cli-release-asset
- build-windows-tray-installer
steps:
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
+2 -2
View File
@@ -53,7 +53,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up Python 3.11
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
@@ -88,7 +88,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up Python 3.11
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.11"
+361 -1
View File
@@ -6,10 +6,370 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
## [Unreleased]
## [1.11.0] - 2026-08-20
### Added
- **Sideload Bridge access is explicitly capability-scoped.** Read-only, read-and-confirm, and custom presets grant only selected powers for the active connection. Screen inspection and control can be allowed for a bounded period or explicitly left unlimited, and Relay status reports the resulting permanent, timed, and unlimited grants.
### Changed
- **The sideload Bridge screen is a summary-first access cockpit.** Agent access, unattended mode, selected Android requirements, and advanced safety controls are separated clearly while the complete permission matrix and power-user controls remain available one tap deeper.
### Fixed
- **Android keeps failed session resumes visible and in context.** Continuing a stored Gateway session no longer falls through to a fresh session when Hermes rejects or mis-scopes the resume. Failed turns remain error-marked and expose a composer-adjacent recovery panel with route-aware details, explicit retry/dismiss actions, and sanitized Diagnostics evidence.
- **Software-keyboard Return inserts a newline across both common Android IME paths.** Keyboards that commit text directly and keyboards that synthesize `KEYCODE_ENTER` now keep multiline composition separate from physical-keyboard Send behavior. (#367)
- **Cancelled answer recovery retains its Stopped status.** Empty recovery placeholders with a persistent status badge are no longer discarded during stream finalization.
- **Android screen-on idle no longer continuously redraws the ASCII sphere.** Idle holds a stable frame while thinking, streaming, and voice states retain full-rate motion; inactive voice waveforms and closed session drawers also stop their frame loops.
- **Android capture and audio effects release power-sensitive resources at their actual lifecycle boundaries.** Screen capture attaches its MediaProjection surface only for a requested frame, unattended Bridge wake locks release when the command finishes, and barge-in AEC/noise suppression attach to the microphone capture session instead of playback.
- **Experimental wake-word listening reuses its PCM normalization buffer.** Continuous opt-in listening no longer allocates a new float frame for every inference call.
## [1.10.0] - 2026-08-18
### Added
- **Android preserves composer drafts across app restarts.** Text, quote/edit context, and pending attachments remain scoped to their exact connection, profile, and session in bounded app-private no-backup storage, and successful sends remove the saved draft.
- **Android can turn large pastes into reviewable text attachments.** The default-on Chat setting converts inserts of at least 5,000 characters into a compact attachment while preserving surrounding text; Gateway uploads the file through upstream Hermes and fallback transports retain the pasted content as text.
- **Android renders Markdown incrementally while replies stream.** The native streaming parser retains stable message, selection, and AST identities from the first token through completion, including provisional paragraphs, lists, links, fenced code, and tables.
### Fixed
- **The Android software keyboard exposes Return in the multiline composer.** The dedicated composer button sends, while physical Enter, Shift+Enter, and caret-arrow behavior remain unchanged. (#367)
- **Open chats reattach after Android returns to the foreground.** Gateway reconnect restores the visible session subscription and reconciles missed work without requiring the user to leave and reopen the conversation. (#365)
- **Imported credentials fail closed before network or secure-state mutation.** Control characters and malformed values are rejected before header construction or encrypted-state replacement without logging credential material.
- **Streaming follow remains stable through completion.** Deliberate scrollback stays untouched, bottom-follow uses one bounded owner, and Markdown, voice actions, timestamps, and token metadata settle without rebuilding the bubble or resetting its scroll anchor. (#341)
## [1.9.1] - 2026-08-16
### Added
- **Android adopts Hermes-owned profile creation, shared avatars, and animated pets.** Current Gateways provide the profile roster, explicit shared/copied/isolated authentication choices, partial create outcomes, validated avatar upload/fetch/clear, and profile-scoped pet selection that follows the agent across supported Hermes clients. Older hosts retain authenticated Dashboard creation plus Relay/local presentation fallbacks, and profile deletion remains Dashboard-only.
- **Android identifies proactive messages delivered after reconnect.** Relay marks messages flushed from its bounded offline queue, Thread bubbles label them as received “While away,” and Android shows one accessible localized summary for the completed batch.
- **Android can create finite recurring schedules from Manage.** The native editor uses the authenticated Hermes Gateway `cron.manage` contract, optionally stops after 1–999 runs, and rejects invalid counts rather than silently creating unlimited work.
- **Chat resets retain content-free local evidence.** New-chat and Thread transitions save a bounded app-private checkpoint for user-reviewed Diagnostics without prompts, message text, IDs, profile names, paths, URLs, media, tool payloads, secrets, or telemetry.
- **Android surfaces host resource risk before chat state is lost.** Current Hermes Dashboard memory and disk pressure signals render as a persistent, capability-gated warning; older hosts remain unchanged and no telemetry is added.
- **Android honors Hermes model-selection safeguards.** Every Gateway model transition, including fresh-chat and Server-default choices, now avoids raw session overrides; picks requiring cost or data-training consent show Hermes' exact warning and apply only after a confirmed second request.
### Changed
- **Profile identity sources are explicit in Agent Passport.** Server-owned static avatars and upstream pets follow the Hermes profile, while phone picks, Relay-host imports, phone-only animated icons, and Sphere skins remain separate local presentation choices.
- **Interactive Gateway asks remain resolver-bound.** Android continues to use upstream clarify, approval, sudo, and secret response RPCs; connector-only prompt/reaction operations are not copied into Relay cards as a second approval protocol.
### Fixed
- **Shared avatar picks now persist from Android's filesystem picker.** The app accepts any image Android can decode, applies display orientation, and safely resizes or re-encodes it to the upstream PNG/JPEG/WebP and 2,000,000-byte contract. Successful writes update the local shared cache immediately, and upload failures remain visible beside the control.
- **Nous-hosted Android sign-in follows the official native broker contract.** The gateway now selects its native provider exactly as Hermes Desktop does, callback attempts retain the upstream five-minute window, and post-callback failures explain whether the one-time code, hosted gateway, network, response, or secure storage prevented session creation without exposing auth material.
- **Android edit-and-regenerate fails closed on incomplete durable history.** Mixed Gateway transcripts now require the selected message's durable row identity instead of attempting an ordinal-only rewind, while older Hermes histories with no row identities remain editable.
- **Android fails closed when a Gateway does not confirm the selected profile.** Named-profile session creation and recovery now require Hermes to echo the exact owning profile, preventing stale or older gateways from silently running the launch profile under another agent's identity. Profile inspection also keeps read-only Gateway data available when `profiles.configure` is unsupported while disabling further write attempts without discarding drafts.
- **Android attachment sends are bounded and fail closed.** Picked files are size-limited while streaming into the encoder, cold and queued Gateway sends upload only after the exact session is ready, and an unsupported or interrupted document upload no longer falls through to a text-only route while its file card implies delivery. Every attachment type retains the same compact collapse/expand affordance.
## [0.4.0-beta.4] - 2026-08-15
### Fixed
- **The Windows management UI remains available while the daemon is stopped.** Missing, stale, malformed, or temporarily unavailable daemon status now resolves to an explicit stopped state instead of trapping the tray on its loading screen, so configuration, diagnostics, host management, and daemon controls remain accessible.
## [1.9.0] - 2026-08-14
### Added
- **Android session browsing matches Hermes Desktop's recent organization model.** The primary session drawer can toggle between the active profile and all profiles, group by recency, project, status, or profile, order by supported session metrics, and narrow rows by status, project, profile, or pull-request state without collapsing duplicate IDs across profile stores. Named profiles receive stable identity-color badges with locally persisted color overrides.
- **Android can edit current Hermes profiles through the standard Gateway.** The Profile Inspector capability-gates `profiles.describe` and `profiles.configure`, keeps Relay-only memory editing and older-Hermes fallback intact, and reports partial section saves without discarding failed drafts.
- **Android sessions show their coding context when Hermes supplies it.** Session rows can display repository, Git branch, and the current state of the pull request created by that session while older hosts remain unchanged.
- Android Manage can now finish host-owned backup workflows, edit or remove learning nodes with explicit recovery guidance, configure and activate memory providers, and complete profile-scoped WhatsApp QR onboarding through the authenticated upstream Dashboard contracts.
### Fixed
- **Android network clients shut down safely during route changes.** Replacing an authenticated Dashboard client now moves OkHttp connection-pool eviction off the main thread, preventing a live TLS socket close from crashing the app with `NetworkOnMainThreadException`. (#334)
- **Android preserves authoritative Gateway outcomes.** Protected-file cards cannot offer forbidden persistent scopes, compression no-ops show the server result, bounded resume failures do not create context-free replacement sessions, and edit/regenerate retains durable row identities across consecutive rewinds.
- **Android routes and uploads against live upstream truth.** Multiplex API fallback trusts `served_profiles` instead of installed profiles, and generic documents carry the Gateway-issued `@file:` reference into ordinary and queued prompts.
- **Android clarify cards preserve upstream decision semantics.** Multi-select prompts keep independent selections and submit one exact list, while server expiry events—not an invented local deadline—retire unanswered cards.
- **Android keeps profile management and retained automation truthful.** Custom Endpoint list and mutation routes now follow the selected Hermes profile, while completed one-shot cron jobs show their retained outcome and expose only valid Runs/Delete actions.
- **Android and Relay recover more generated media reliably.** Android accepts upstream-valid wrapped, punctuated, adjacent, spaced, and Windows `MEDIA:` markers without consuming fenced examples, and Relay translates Docker-visible workspace, home, cache, and configured-mount paths before applying its existing credential, sandbox, and size checks.
- **Android keeps cross-profile sessions with their owning agent.** Opening a session from All Profiles hydrates, resumes, sends, and renders with that session's profile without changing the global profile selection; New Chat from that view starts with the default profile.
- **Android reactions and standard voice follow the active conversation.** Reactions resolve durable rows for both user and assistant messages, while Vanilla Hermes voice remains on the authenticated Gateway instead of requiring the optional API fallback.
- **Android session navigation behaves predictably.** The drawer closes on outside taps, uses an ungrouped recent-session list by default, retains project grouping as an explicit option, and exposes secondary actions in All Profiles mode.
## [0.4.0-beta.3] - 2026-08-14
### Fixed
- **Windows tray polling can no longer accumulate unbounded helper processes.** Grant discovery now uses lightweight local state, management refreshes are single-flight and visibility-aware, and child probes have hard timeouts, bounded output, tree cleanup, caching, and backoff. A dedicated bounded `tray.log` records sanitized operational failures without mixing them into daemon logs.
- **Concurrent Desktop lifecycle requests cannot start duplicate daemons.** Cross-process lifecycle and runtime ownership locks serialize startup and recovery while preserving stale-owner cleanup.
## [1.8.0] - 2026-08-14
### Added
- **Official Hermes Desktop can surface Relay through its supported runtime Plugin SDK.** The unified plugin package now includes an opt-in, profile-scoped Desktop pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management. Loading, startup, reconnects, profile changes, and updates never open it; only labeled sidebar, status-bar, or command-palette actions register and reveal the movable native pane.
## [0.4.0-beta.2] - 2026-08-14
### Added
- **Desktop Activity now keeps inspectable local evidence.** Commands, files, devices, connection lifecycle, and computer control share a truthful event stepper with dedicated failure details; screenshot events can retain bounded local PNG evidence and open it in a larger borderless viewer. Settings controls retention as Off, 1 day, 7 days, or 30 days and shows local file usage.
### Fixed
- **Tunnel state stays responsive through interruption and retry.** The CLI UI distinguishes connected, reconnecting, and stopped states, exposes retry attempt/timing and a Retry now action, records connection failures and recovery in Activity, and shows compact connection cards only while the main UI is hidden.
- **Windows CUA readiness no longer depends on the flaky whole-desktop health scan.** Hermes-Relay verifies the canonical runtime, manifest, required tools, daemon, and safe permission mode before starting structured sessions, while accessibility health remains an explicit CLI/UI diagnostic that can be rechecked without forcing the compatibility backend. This temporary workaround is scoped to the upstream fixed-timeout issue and keeps individual actions fail-closed.
## [0.4.0-beta.1] - 2026-08-14
### Added
- **CUA Driver is the preferred Windows structured-control engine.** New local settings prefer a verified CUA runtime for window-targeted background actions, fresh snapshot tokens, and optional per-session animated agent cursors without moving the physical pointer; Windows Input is the explicit compatibility backend and backend choice is fixed for each control session. Full-display observation remains on the read-only system capture path. CLI and UI can explicitly install, check, or update the canonical CUA package after verifying the upstream release manifest and installer checksum; nothing is bundled or updated automatically, driver telemetry stays off for Hermes sessions, and activity records contain only bounded, redacted control metadata.
### Fixed
- **Windows bundle updates fail closed when installed processes retain a binary lock.** Setup waits for the invoking CLI, quiesces the tray and its short-lived CLI children, checks every payload extraction before writing release metadata, preserves custom install directories, and returns a failure instead of reporting a mixed-version installation.
- **CUA readiness follows the published driver contract.** Hermes accepts the documented `ok` health state, distinguishes an installed-but-degraded runtime from a missing installation, and constructs trusted Windows installer paths consistently across verification environments.
## [1.7.0] - 2026-08-13
### Added
- **Hermes Secure Link provides self-hosted pinned TLS ingress.** Relay, API, and Dashboard namespaces share one operator-owned TLS endpoint while retaining their native authentication boundaries, QR-carried certificate continuity, explicit rotation, and fail-closed route validation.
- **Hermes Reach is available for explicit experimentation.** The optional self-hosted rendezvous broker carries opaque Secure Link TLS records over outbound-only connections with bounded multiplexing, hashed credentials, replay protection, persistence, revocation, and no access to Hermes payloads.
- **Remote-access management exposes supported reachability clearly.** Dashboard status and pairing metadata distinguish Tailscale reachability, Secure Link transport protection, direct routes, and experimental Reach without presenting the broker as a replacement for authentication.
### Changed
- **Tailscale is the recommended remote route.** Pairing, Dashboard, documentation, and public site guidance present Tailscale as the easiest supported remote-access path; Reach remains disabled by default, advanced, and lower priority than supported routes.
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients honor custom headers, custom CA bundles, standard CA environment precedence, and an explicitly warned development-only verification override.
- **Voice Lab xAI sign-in uses device authorization.** The standalone login shows a verification URL and user code and polls for approval without requiring a loopback callback.
### Fixed
- **Phone delivery remains compatible with strict Hermes targets.** Version-tolerant parser and validator hooks retain older-host registration and exactly-once standalone delivery.
- **Profile-owned Relay registrations stay isolated.** Current Hermes uses profile-scoped ownership and context-local profile homes while legacy hosts retain a guarded compatibility path.
- **Phone is discoverable before its first historical session.** The Relay phone adapter publishes its configured home destination through Hermes' standard channel directory.
## [0.4.0-alpha.8] - 2026-08-13
### Added
- **Windows management separates each Relay host from this PC.** Host detail owns identity, pairing, access, capabilities, authorized clients, re-pairing, and guarded removal; Settings owns local daemon lifecycle, startup, privilege, terminal, logs, diagnostics, updates, and Help & About.
- **Desktop access uses clear host-scoped presets and capabilities.** Restricted, Ask Every Time, Standard, Full Access, and Custom remain explicit across commands, files, screen/input, USB, microphone, and camera controls.
- **Activity drilldown preserves bounded execution evidence.** Overview shows the latest three events and detail views expose request, output, result, exit, duration, and truncation metadata without copying sensitive inputs.
- **Connection presentation shows the live Agent-to-PC path.** Host selection, bidirectional packet motion, transition feedback, route details, and connection testing stay compact, responsive, and reduced-motion aware.
### Changed
- **Connect and disconnect remain responsive during daemon work.** Lifecycle calls and snapshot collection run outside the UI thread, transition status polls quickly without overlapping probes, and progress remains visible until authoritative daemon state arrives.
- **Tailscale is recommended for remote access.** Secure Link and direct TLS routes remain supported, while Hermes Reach is visibly experimental and lower priority.
### Fixed
- **Connection tests classify legacy private routes correctly.** A saved generic role is inferred from its actual endpoint, so LAN and Tailscale routes no longer appear as Custom VPN; results include reachability, latency, security, endpoint, and route count.
- **Ask-mode approval cards show the requested action.** A bounded preview appears in the compact card with full context and an Open in UI action.
- **Mixed capability policies are labeled Custom.** Overview no longer claims a preset when individual capability controls differ.
- **Tray placement follows the notification-area monitor and DPI.** Responsive popup geometry stays anchored above the tray icon across compact and high-DPI desktops.
- **PowerShell success output is complete and self-describing.** Scalar, pipeline, JSON, native stdout/stderr, exit status, and truncation metadata survive the desktop RPC response.
## [1.6.4] - 2026-08-12
### Added
- **Desktop tools support explicit host targeting.** Every client-routed desktop tool accepts a stable device ID or unambiguous computer name, and `/desktop/health` enumerates connected targets and their advertised tools.
- **USB operations retain both routing scopes.** Raw USB and ADB tools use `device` to select the desktop PC, while ADB operations continue to use `serial` to select hardware attached to that PC.
### Fixed
- **Multiple desktop clients remain connected simultaneously.** The Relay no longer replaces the previous desktop when another heartbeat arrives; concurrent requests are bound to their selected WebSockets, responses from another PC are ignored, and an untargeted call fails closed when several desktops are online.
- **Pairing another desktop preserves existing credentials.** Legacy placeholder device identifiers are treated as absent instead of shared ownership, preventing an unrelated PC from revoking the first desktop's session.
## [1.6.3] - 2026-08-11
### Fixed
- **Relay diagnostics distinguish a prior clean stop from a crash.** Doctor and `/relay/info` expose only bounded clean, unclean, or unknown gateway-exit state with an optional suspected out-of-memory hint, without returning raw log evidence.
- **Relay reconnects spread out after shared gateway restarts.** Ordinary exponential reconnect delays use full jitter while explicit reconnects and server-directed retry timing retain their exact behavior.
## [0.4.0-alpha.7] - 2026-08-11
### Fixed
- **Installer lifecycle validation uses an isolated Windows PATH fixture.** Release smoke tests now verify add/remove cleanup against a fixed registry value and restore the runner's original value afterward, independently of the temporary profile used for session-preservation checks.
## [0.4.0-alpha.6] - 2026-08-11
### Fixed
- **Installer cleanup validation compares the unexpanded Windows PATH.** Release smoke tests now read the raw user registry value, ensuring `%USERPROFILE%` entries are verified without temporary-profile expansion changing their apparent value.
## [0.4.0-alpha.5] - 2026-08-11
### Fixed
- **Installer cleanup validation handles expandable Windows PATH entries.** Release smoke tests restore the original profile environment before comparing user PATH, avoiding false failures when unchanged `%USERPROFILE%` entries are expanded inside an isolated test profile.
## [0.4.0-alpha.4] - 2026-08-11
### Fixed
- **Windows release validation waits for installer processes.** The packaged install/uninstall lifecycle smoke now captures GUI-subsystem process exit codes reliably before validating installed files, preserved sessions, registry state, and cleanup.
## [0.4.0-alpha.3] - 2026-08-11
### Added
- **Windows tray provides focused remote-access management.** The compact host-aware popup covers connection state, per-host Ask/Trusted/Full Access, pending grant dialogs, authorized-client revocation, activity, daemon controls, and settings without adding chat, terminal, plugin, voice, or session surfaces.
- **Desktop access policy is isolated per Hermes host.** `hermes-relay hosts` lists and selects local pairings and stores fail-closed access modes independently for each canonical relay URL.
- **Windows CLI installations can add or open the management UI directly.** `hermes-relay ui install|open|status` and the installed UI shim provide a supported lifecycle for optional UI setup, discovery, and activation.
### Changed
- **Daemon connectivity no longer requires a tool grant.** Ask mode can keep an authenticated daemon connected with zero desktop tools attached; Trusted enables command/file tools with task-scoped screen/input grants, while Full Access removes those task prompts only for the selected host.
- **Windows bundle updates preserve the desktop lifecycle.** The CLI and tray coordinate one verified installer launch, restore the daemon and UI after setup, and permit same-version UI add or repair without silently downgrading a newer CLI.
### Fixed
- **Background daemon start reports real readiness.** Detached startup now waits for the spawned process to authenticate and connect, and returns actionable log evidence for configuration, authentication, early-exit, and timeout failures.
- **Local and release tray builds embed the packaged UI.** Development installs use Tauri's production protocol instead of attempting to load a missing localhost development server, and release CI exercises a silent install/uninstall lifecycle.
- **Windows-trusted certificates work in the desktop CLI.** The packaged Windows binary and newer Node runtimes add the Windows certificate store without dropping bundled or operator-supplied roots, while TLS verification and Relay certificate pinning remain enforced.
## [1.6.2] - 2026-08-11
### Fixed
- **Paired sessions use recognizable device identities.** Relay sessions preserve a client-provided hostname as the primary name, retain model and platform details, and enrich valid reconnects without requiring users to pair again.
- **Long-lived session expiry is readable.** The Dashboard presents paired-session lifetime in days or weeks with the exact local deadline available in the detail view instead of accumulating hundreds of hours.
## [Android 1.8.1] - 2026-08-09
### Fixed
- **Android preserves complete long-session transcripts.** API-server and profile-scoped Dashboard history reads now use explicit bounded pagination, retain compatibility with older unpaginated responses, and keep edit, retry, sharing, and recovery anchors stable beyond Hermes' latest-500 default window.
- **Android follows authoritative Gateway turn contracts.** Submit rejections retain the server's message without silently falling through to SSE, event envelopes reconcile consistently, and edit-and-regenerate requests send the required truncation confirmation.
## [Android 1.8.0] - 2026-08-09
### Added
- **Android chat keeps work in context and makes live turns easier to read.** Draft text, edits, quotes, and attachments stay with their connection, profile, and session; conversation search and prompt-turn navigation jump by stable message identity; message actions reveal smoothly on tap; quoted replies use linked previews without placing markup in the composer; assistant replies retain their compact high-contrast bubbles; and pending attachments support preview, removal, and accessible reordering.
- **Android reasoning and tool activity use a quieter transcript.** Live thinking opens as an inline disclosure and settles to a collapsed Thought row, while consecutive routine reads, searches, commands, browser actions, and device actions share one live activity ticker or concise completed summary. Approvals, failures, generated media, file changes, output risks, and delegated work keep their own visible lifecycle surfaces even when ordinary tool progress is hidden.
- **Android Profile Shelf makes agent switching immediate without mixing conversations.** The Chat header expands a compact, accessible shelf with ordered profile avatars, a subtle Server-default home badge on the resolved identity, last-session restoration, display hiding, lock controls, and one full switcher shared with Agent Passport.
- **Android accepts shared text as a new Chat draft.** Hermes Relay now appears in the system sharesheet for text, opens the active profile in a fresh conversation, and fills the composer for review without sending automatically.
### Changed
- **Android appearance controls are more expressive and easier to preview.** Theme presets, accent and shape customization, imported Sphere skins, and custom pet creation share one live-preview workflow while preserving separate agent, background, and companion identities.
### Fixed
- **Android restores complete Gateway activity and makes settled replies speakable.** Successful Gateway turns reconcile structured persisted tool calls even when an upstream server omits live tool lifecycle events, and a configured voice can read a completed assistant reply from its message actions without requiring Voice Mode. While that narration is active, the same message actions expose Stop without cancelling an unrelated chat turn.
- **Android chat matches standard keyboard, scrolling, and photo behavior.** Sentence capitalization is enabled, physical Enter can send or insert a newline according to a device-level setting, Ctrl/Command+Enter always submits, directional keys stay with the text caret, expanded thinking and tool content retains bottom-follow until the user scrolls away, and portrait attachments honor their EXIF orientation in previews and message viewers.
- **Android distinguishes live-turn corrections from queued follow-ups.** The composer names its current action with visible text and accessible state, successful gateway redirects show a correction lifecycle marker, and attachment-bearing follow-ups always enter the session-owned queue because the upstream redirect operation is text-only.
- **Android visibly explains quiet startup work without an empty chat bubble.** The full-size thinking animation now sits directly in the conversation lane with a stable reviewable status until the first answer text arrives, while recovery keeps its explicit reconnecting state.
- **Android keeps pets and screen chrome inside safe interaction bounds.** Floating companions avoid agent identity rows and controls during scrolling, remain touchable for their menu, and settings headers respect edge-to-edge system insets.
## [Android 1.7.1] - 2026-08-08
### Fixed
- **Android chat follows a growing live reply.** Bottom-owned conversations now observe each replacement of the streaming message list, keeping newly added lines visible while preserving the reader's position after a manual scroll away.
- **Hosted Hermes onboarding completes through the official Dashboard sign-in path.** Android recognizes hosted account addresses, uses the system-browser native PKCE flow, and resumes the verified Dashboard session after its loopback callback.
- **Live Android tool cards remain expandable while a run is active.** Streaming Gateway updates preserve stable card identity and merge tool arguments and result previews into the existing row, so details can be opened before the session finishes.
- **Completed Android replies format Markdown immediately.** Live assistant text keeps its stable plain renderer only while incomplete, then the same owned row transitions to rich code blocks, lists, emphasis, and links without leaving or reopening the session.
- **Android approval cards require an explicit labeled decision.** Reading or scrolling a guarded command, navigating away, backgrounding, recomposition, later turn activity, and card dismissal cannot submit or locally resolve it; pending requests remain bound to their owning profile and session until an explicit response or authoritative upstream expiry.
- **Android Agent Passport controls are readable and easy to dismiss.** Safety and speed choices use full-width accessible targets with plain-language selected-state explanations, while a persistent close action and boundary-aware downward swipe make the sheet reliably dismissible without stealing nested content scrolling.
- **Android queued messages stay with their originating chat.** Follow-ups now retain their exact connection, profile, session, run, route, attachments, and voice context across concurrent Gateway session switches instead of following whichever session is visible when a run finishes.
- **Android model pickers reject duplicate catalog identities before rendering.** Repeated provider/model rows from cached or refreshed inventories are merged at the provider boundary, while identical model IDs under different providers remain distinct choices with provider-aware reasoning capabilities.
- **Android session pins and archives survive app restarts.** The session drawer now reads and updates the owning Hermes profile's durable session metadata, rolls failed changes back, and makes unpinned stars clearly distinct in light theme.
## [1.6.1] - 2026-08-08
### Fixed
- **The Dashboard plugin hands hosted Hermes connections to Android reliably.** Mobile setup exposes the canonical Dashboard address and keeps dialog focus handling contained, so system-browser authentication can return to the correct connection without disrupting the Dashboard.
## [Android 1.7.0] - 2026-08-06
### Added
- **Android exposes provider-aware reasoning controls.** The effort drawer consumes exact upstream or optional Relay capability metadata for each provider/model identity, while unmodified or older Hermes installations retain a fail-soft standard fallback including `max` and `ultra`.
- **Android support information is local, redacted, and reviewable.** Fatal crashes and handled failures share a bounded on-device record, Diagnostics can copy or share the exact reviewed text, and nothing is uploaded automatically.
### Fixed
- **Android chat chrome follows its active interaction state.** Opening the session drawer dismisses the composer keyboard, refreshed sessions keep their newest row visible, and floating pets wait for measured chat terrain, sit flush on supported rails, and treat the complete scroll-to-bottom control as forbidden space.
- **Android pets and optional model discovery initialize quietly.** Floating companions wait for a measured overlay before taking their home position, and background API model-inventory failures retain actionable local diagnostics without interrupting chat with a generic notice.
- **Android chat and Voice stay precisely bottom-pinned through replies, restores, and layout changes.** The active tail keeps its stable live renderer until another row takes ownership, restored sessions follow late composer and message measurement without overriding a reader, and bottom-owned transcripts settle to the exact list boundary after replies and keyboard animations instead of leaving a small hidden remainder.
- **Android Focus voice controls remain responsive.** The modal click-through guard now sits behind the voice UI instead of consuming pointer events from the mic, close, expansion, and panel controls.
- **Android diagnostics explain what failed and what to try next.** Relay, route, WebSocket, and API checks distinguish the saved route from the redacted request they actually attempted, name the operation, and provide targeted guidance for connection, DNS, timeout, TLS, authentication, rate-limit, and server failures.
- **Android chat and Voice keep one render identity through recovery.** Checkpoint restore, streamed callbacks, server-ID adoption, and replay now resolve the same owned transcript row before publication, preventing recurring Compose duplicate-key crashes.
- **Android crash reports retain actionable release context.** Reports identify the Android surface, avoid exposing hosts and credentials, migrate earlier local crash records, and release automation retains exact Play and sideload R8 mappings for retrace.
## [1.6.0] - 2026-08-06
### Added
- **Relay supplies exact provider/model reasoning capabilities when providers expose them.** The bounded, profile-aware overlay resolves dynamic catalogs for OpenAI Codex, Copilot, LM Studio, and Ollama Cloud, keeps provider credentials on the host, and leaves unknown or unavailable catalogs on the advisory fallback.
## [Android 1.6.1] - 2026-08-03
### Fixed
- **Voice capture waits for the microphone to be released.** Manual recording no longer races barge-in teardown, and AudioRecord startup failures now explain how to free or permit the microphone before retrying.
- **Android text selection stays stable as streamed replies finish.** Chat resets an active selection when live text becomes rich Markdown, preventing selection-handle drags from retaining removed text nodes.
- **Android session history follows the upstream page-size contract.** The drawer keeps its 200-session window through bounded 100-row requests, avoiding HTTP 422 errors from current dashboard servers while preserving active-profile isolation.
- **Android no longer mistakes optional-surface auth failures for expired Relay pairing.** Background session refreshes stay out of the global snackbar, Dashboard and API authorization errors name their owning credential, and Relay-only surfaces use consistent Optional, Ready, Reconnecting, Unavailable, and Needs re-pair states. Foreground recovery retries ordinary Relay backoff immediately while preserving server rate limits, and recovery prioritizes Dashboard or host session management while retained credentials are labeled as stored details instead of active pairing.
- **Voice controls no longer collide with new-chat coaching.** The clean-view hint yields while Voice owns the composer so it cannot cover the expanding Voice drawer.
## [1.5.1] - 2026-08-03
### Fixed
- **Re-pairing repairs one device instead of accumulating duplicate sessions.** An explicit host-approved pair replaces older sessions and refresh credentials for the same device, while the Dashboard and `/relay revoke <token-prefix>` remain available for operator cleanup.
## [Android 1.6.0] - 2026-08-02
### Added
- **Hermes can be selected as Android’s default Digital Assistant.** The opt-in system role supports background and locked-screen invocation, while the separate experimental “Hey Hermes” listener keeps pre-activation audio on the phone and exposes an ongoing Stop control.
- **Installed Hermes plugins can contribute native Android pages.** Android renders a bounded declarative schema instead of plugin code, keeps write access off until the user grants it, and supports approval-gated agent-created previews through Relay 1.5.0.
- **Pets can stay with you across the Android app without replacing the agent.** Petdex and imported companions live in an app-level overlay, can be held and dragged, and optionally roam across live-measured chat and settings surfaces without reserving message space. (#267)
- **Petdex browsing and one-tap installation are built into Appearance.** Search results use lightweight previews, full atlases download only after Install, creator attribution remains visible, and installed pets stay available offline. (#267)
- **Android can be used in Russian.** Both product flavors include an AI-assisted Russian catalog, language picker support, localized plurals, and refreshed translations for the 1.6 feature set.
### Changed
- **Assistant and floating Voice surfaces use compact, expandable controls.** Opening full Voice continues the same turn and microphone owner instead of restarting the session.
- **Voice interruption covers generation and playback.** Barge-in follows upstream RMS calibration and timing, exact stop phrases can end an active voice chat, and interrupted spoken context remains private to the next Standard turn.
- **Profile identity, the Sphere, and pets are separate appearance choices.** Agent avatars identify messages, background visualization controls ambient art, and Floating pet controls the companion independently. (#267)
- **The Agent Passport exposes more profile state and safer controls.** Profile configuration, skills, routing, reasoning, and scoped API access remain visibly distinct from the active session identity.
### Fixed
- **Voice output recovers when a streaming renderer produces no audio.** Android falls back to basic synthesis after a bounded first-audio timeout, and long Standard Voice uploads no longer retain duplicate encoded audio buffers.
- **Relay route failover avoids competing reconnect loops.** Route changes settle through one generation-aware reconnect owner instead of rapidly switching between LAN and remote candidates.
- **Live chat rows keep stable UI identity while upstream state reconciles.** Streamed messages and process rows no longer collide or restart merely because a server identity arrives later.
- **Floating pets recover from invalid or scrolling terrain.** Roaming uses measured bubble edges, avoids the jump-to-latest control and text overlap, resumes after drag or scrolling, and preserves locomotion, held, drop, and fallback animation states.
- **Hermes appears and activates in OEM Android assistant pickers.** Required Assist, Voice, recognition-service, and single-microphone lifecycle metadata now agree.
- **Experimental wake detection handles completed sherpa results and empty speech cleanly.** Tests use the real local microphone/model path, and no-speech activation returns to ready state instead of surfacing a fatal server error.
## [Android 1.5.3] - 2026-07-31
### Fixed
- **Voice transcripts retain stable rows after chat-history reconciliation.** Focus mode uses the same stable Compose identity as the main conversation, preventing duplicate-key crashes when live rows adopt persisted server IDs.
## [1.5.0] - 2026-08-02
### Added
- **Realtime Agent sessions can speak only settled answers.** Clients may enable an optional per-session `final_answer_only` policy that suppresses routine acknowledgements, progress narration, and intermediate commentary while preserving spoken approvals, confirmation questions, blocking failures, and the final Hermes answer.
- **Agents can draft native Android plugin pages through Relay.** New tools store bounded declarative JSON pages under the authenticated Relay plugin namespace, while Android retains control of enablement, publication, write grants, and persistent removal. Generated pages cannot include executable code, arbitrary network calls, Android intents, or backend action requests.
## [Android 1.5.2] - 2026-07-28
### Fixed
- **Dashboard sign-in completes across supported providers and network routes.** Self-hosted OIDC stays on the dashboard cookie flow, while Nous Portal opens in the system browser and completes standards-compatible PKCE through HTTPS, private-LAN, or Tailscale dashboard routes.
- **Replayed chat updates no longer destabilize the conversation list.** Duplicate upstream message identifiers are coalesced before Compose renders them.
## [Android 1.5.1] - 2026-07-26
### Added
@@ -391,7 +751,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
- **Spoken-turn badges (chat).** Voice-mode replies now carry a "Voice" chip and realtime replies a "Realtime Agent" chip — both with a speaker glyph — so spoken turns are distinguishable from typed ones in the scrollback.
- **App themes.** A new theme picker in Settings → Appearance ships eight looks: the signature Hermes Relay brand (with full light/dark) plus ports of the Nous Hermes baselines — Hermes Teal, Nous Blue (light), Midnight, Ember, Mono, Cyberpunk, and Rosé. The whole app — brand chrome, accents, and chat background — follows the chosen theme. Light/Dark/Auto applies to themes that ship both modes; fixed-mode themes show their own complete look.
- **Hot-swappable agent sphere.** The orb is now a pluggable "skin": an Adaptive skin that recolors to match your theme, built-in Classic / Aurora / Solar / Mono looks, and support for **user-authored skins** loaded from a small JSON spec. Each skin declares which live signals it reacts to (voice, tool bursts, activity), shown as capability badges in the picker. See `docs/sphere-spec.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. A plugin-provided **Secure proxy** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. The optional plugin-provided **Hermes Secure Link** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Enhanced voice control (Gemini & xAI).** When the relay uses a Gemini or xAI voice provider, Voice Settings can now steer it: pick a Gemini voice and model and turn on expressive tone tags (with optional natural-language voice direction), or set an xAI voice with expressive speech tags. Expressive tags also apply to xAI on the streaming voice-output renderer. Standard (no-plugin) voice stays configured server-side.
- **Voice render-path visibility.** Voice Settings shows which path is rendering speech (streaming vs. basic), and Diagnostics records it each session, making voice issues easier to troubleshoot.
- **Agent pets — a living, swappable avatar.** The orb can be replaced with an animated "pet" that reacts to what the agent is doing: idle / thinking / writing / speaking / listening states, a distinct **working** pose during tool calls, one-shot **greet** / **celebrate** reactions, and a loop that quickens as output streams. Add or remove pets right in Settings → Appearance (no `adb` needed), with a live state preview, a playback-speed slider, and optional frame auto-stabilization; capability badges (Voice · Tools · Activity) show honestly what each pet actually reacts to. Pets are pure data — an AI authoring kit and a JSON schema let you generate one from sprite art. See `docs/pet-spec.md` and the custom-avatars guide.
+4 -3
View File
@@ -235,9 +235,10 @@ This is a **public, distributed repo** — every committed file (CHANGELOG, DEVL
| **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` | Blocklist + destructive-verb confirmation + auto-disable timer; fails-closed on /call and /send_sms |
| `data/BridgeSafetyPreferences.kt` | DataStore for blocklist, destructive verbs, auto-disable minutes, confirmation timeout |
| `ui/screens/BridgeScreen.kt` | Bridge UI — master → permission checklist → [Advanced] → unattended → safety → activity log (v0.4.1 reorder) |
| `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) |
+11 -25
View File
@@ -1,35 +1,21 @@
# Hermes-Relay-CLI v__VERSION__
# Hermes-Relay CLI v__VERSION__
**Release Date:** 2026-07-13
**Release Date:** 2026-08-15
This alpha makes the desktop direction explicit: Hermes-Relay is a real CLI/TUI with an optional Windows right-click systray—not a second desktop application. The old Tauri/WebView dashboard and its embedded windows are gone. The installed CLI remains the single source of behavior for pairing, TUI, daemon management, grants, audit, diagnostics, chat, voice, and tools.
This patch keeps the Windows management UI usable when the Relay daemon is stopped or its status cannot be read.
**Experimental phase.** Assets are unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the optional native systray is Windows-only.
**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, and macOS x64/arm64; the management UI is Windows-only.
## What's changed
### Added
- **Persistent desktop-use control.** `hermes-relay computer-use status|enable|disable|cancel` stores one local preference, reports daemon privilege and active/pending grants, and can end an active task-scoped grant without relying on a GUI.
- **Headless grant review.** `hermes-relay grants` lists pending local computer-use requests and supports interactive review plus explicit `approve`, `reject`, and JSON forms for scripts.
- **Typed Relay chat option.** `chat --relay-chat` sends `chat.send` over WSS and renders typed `stream.event` v1 assistant, tool, artifact, memory, skill, and error lifecycles while preserving the existing gateway path as the default.
- **Release-parity verification.** One version contract now keeps the npm package, compiled CLI, Rust tray, lockfile, and installer metadata aligned. The Windows verification target covers TypeScript, compiled-binary smoke tests, Rust formatting/lint/check/tests, and installer packaging.
### Changed
- **Menu-only Windows systray.** The optional tray is a small native Rust process with no application window, WebView, overlay, embedded terminal, chat view, voice view, or settings dashboard. Interactive actions open the installed CLI in a normal terminal.
- **State- and privilege-aware daemon control.** The menu reports PID-backed daemon state and User/Administrator privilege, disables invalid lifecycle actions, and requests UAC only when **Start/Restart daemon as Administrator…** is explicitly chosen. The tray itself remains unprivileged.
- **Visible desktop-use safety.** The tray shows enablement, active grant mode and expiry, warns when an Administrator control grant is active, raises a native alert for pending approvals, opens CLI grant review, and provides immediate cancellation and emergency stop.
- **Per-user Windows installation.** The default PowerShell installer downloads the checksum-verified NSIS package, installs the CLI and optional tray under `~/.hermes/bin`, adds Start-menu shortcuts and user PATH, and can start the tray at sign-in. CLI-only installation remains available with `HERMES_RELAY_INSTALL_SURFACE=cli`.
### Fixed
- **Installed-binary diagnostics.** `hermes-relay doctor` reports the physical Bun-compiled executable instead of a virtual embedded-module path, so PATH and install-directory checks describe the binary that actually launched.
- **Release guardrails.** CLI tag automation rejects version drift, tags not contained in `main`, oversized tray binaries, or a tray process that creates an application window.
- **Stopped daemons no longer block the management UI.** Missing, stale, malformed, or temporarily unavailable daemon status falls back to an explicit stopped state while hosts, settings, activity, CLI details, diagnostics, and daemon controls continue loading normally.
- **Starting the daemon restores live status without reopening the UI.** A valid running status continues through the same bounded, single-flight snapshot path introduced in beta.3.
## Install
**Windows CLI + optional systray (PowerShell):**
**Windows CLI + management tray (PowerShell):**
```powershell
irm https://raw.githubusercontent.com/Codename-11/hermes-relay/main/desktop/scripts/install.ps1 | iex
@@ -53,11 +39,11 @@ Pin this release with `HERMES_RELAY_VERSION=__TAG__`.
```text
hermes-relay --version
hermes-relay pair --remote ws://<host>:8767 --grant-tools
hermes-relay hosts list --json
hermes-relay daemon start
hermes-relay daemon status
hermes-relay daemon status --json
```
On Windows, open **Hermes Relay Systray** from the Start menu and right-click its notification-area icon. No separate desktop window is installed.
On Windows, click the Hermes-Relay CLI UI notification-area icon to open the management popup directly above it.
See the [CLI and systray guide](https://hermes-relay.dev/docs/desktop/) for installation, commands, desktop-use safety, and troubleshooting.
See the [CLI and tray guide](https://hermes-relay.dev/docs/desktop/) for installation, access modes, grants, and troubleshooting.
+32 -7
View File
@@ -17,17 +17,41 @@ That's it — no extra setup or credentials required for a debug build.
Helper scripts for common development tasks:
```bash
scripts/dev.bat build # Build debug APK
scripts/dev.bat build # Build the sideload debug APK
scripts/dev.bat compile # Compile sideload Kotlin only
scripts/dev.bat test-one "com.hermesandroid.relay.SomeTest" # Run one test class
scripts/dev.bat install-fast # Build arm64 only + install + launch
scripts/dev.bat release # Build signed release APK
scripts/dev.bat bundle # Build release AAB for Google Play
scripts/dev.bat run # Build + install + launch + logcat
scripts/dev.bat test # Run unit tests
scripts/dev.bat run # Build sideload + install + launch + logcat
scripts/dev.bat test # Run sideload debug unit tests
scripts/dev.bat version # Show current version
scripts/dev.bat relay # Start relay server (dev, no TLS)
```
Linux/macOS equivalent lives at `scripts/dev.sh`.
### Fast Android iteration
Gradle's daemon, local build cache, configuration cache, and parallel task
execution are enabled for repeat local builds. Keep the same Gradle JVM
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.
Use the narrowest command that proves the change:
1. `scripts/dev.bat compile` for a Kotlin compile check.
2. `scripts/dev.bat test-one "<fully-qualified-class-or-pattern>"` for a focused regression.
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.
`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
universal and are unaffected unless `-Phermes.devAbi` is explicitly supplied.
## Repository Structure
```
@@ -51,12 +75,12 @@ The legacy `relay_server/` directory is a thin compatibility shim around `plugin
| Component | Stack |
|-----------|-------|
| **Android App** | Kotlin 2.0, Jetpack Compose, Material 3, OkHttp |
| **Android App** | Kotlin 2.4, Jetpack Compose, Material 3, OkHttp |
| **Relay Server** | Python 3.11+, aiohttp |
| **Serialization** | kotlinx.serialization |
| **Build** | AGP 9, Gradle 8.13, JVM toolchain 17 |
| **Build** | AGP 9.3.1, Gradle 9.6.1, JVM toolchain 17 |
| **CI/CD** | GitHub Actions (lint, build, test, signed APK artifacts) |
| **Min SDK** | 26 (Android 8.0) / Target SDK 35 |
| **Min SDK** | 26 (Android 8.0) / Target SDK 36 |
## Running the Relay Locally
@@ -174,7 +198,8 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
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 unit tests:** `scripts/dev.bat test` (runs JUnit + MockK + Compose testing)
- **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)
- **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.
+617
View File
@@ -1,5 +1,609 @@
# Hermes-Relay — Dev Log
## 2026-08-20 — Android stored-session resume failures stay visible
Android now treats a failed Gateway `session.resume` as authoritative for the
selected stored conversation. The client no longer creates a replacement
session and submits the continuation after a resume rejection or profile-scope
mismatch, preventing a context-free turn from silently selecting different
runtime state.
Gateway terminal failures and pre-submit transport failures now share a
session-scoped panel immediately above the composer. The panel keeps the failed
transcript row intact, shows only confirmed route/model/provider identity,
offers explicit Details, Retry, and Dismiss actions, and records bounded,
redacted evidence in the existing Diagnostics review/share flow. No route or
model is changed automatically.
## 2026-08-18 — Android 1.10.0 chat continuity and streaming Markdown
Hermes-Relay Android 1.10.0 is published from the immutable
`android-v1.10.0` tag, with the production Play submission committed as
versionCode 45. The release preserves exact-session composer drafts across
restarts, converts large pastes into reviewable attachments, and keeps standard
chat compatible with unmodified upstream Hermes.
Assistant replies now render completed Markdown structures incrementally while
holding an incomplete streaming tail stable. Stable message identity and a
bounded bottom-follow controller prevent completion-time replacement, stacked
scroll animations, and transcript-distance velocity from moving a reader who
has deliberately scrolled away. Foreground reconnect reattaches the visible
Gateway session, malformed imported credentials fail closed, and software
keyboard Return remains distinct from the dedicated Send action.
## 2026-08-17 — Android composer continuity and large-paste review
Android's multiline composer now leaves the software IME action as Return while
the dedicated trailing button sends. Physical keyboard Enter, Shift+Enter, and
directional caret behavior retain their existing contracts.
Composer drafts now persist in bounded app-private no-backup storage using
small owner metadata plus content-addressed attachment blobs. Draft ownership
follows the exact connection, opened session profile, session, and draft slot;
profile and connection switches save before restoring, lifecycle stop flushes
the latest state, and successful sends remove the saved draft.
A default-on Chat setting converts a single insertion of at least 5,000
characters into a reviewable text attachment. Preparation runs off the UI
thread behind a visible loading card. Current Gateways send it through upstream
`file.attach`; API-server SSE and proactive Thread paths materialize the same
UTF-8 content into the prompt so no route silently loses the paste.
## 2026-08-14 — Android 1.9.0 session identity and conversation controls
Hermes-Relay Android 1.9.0 is published from the immutable
`android-v1.9.0` tag. Multi-profile session browsing now keeps the aggregate
drawer scope selected while transcript hydration, resume, sending, and header
identity follow the session's owning profile. New Chat from All Profiles uses
the default profile, and the session list starts ungrouped while retaining
project grouping and the other desktop-style views as explicit options.
Message reactions now resolve durable rows for both user and assistant
messages. Vanilla Hermes voice remains on the authenticated Gateway instead of
requiring the optional API fallback. Session rows can expose profile, project,
branch, and pull-request context without crowding the chat header, secondary
drawer actions remain available in All Profiles, and outside taps dismiss the
drawer.
## 2026-08-09 — Gateway activity recovery and chat speech
Successful Android Gateway turns now reconcile against their profile-owned,
structured session history. This recovers persisted tool calls when an upstream
Gateway completes a turn without emitting live tool lifecycle events; assistant
prose is never inspected for inferred activity, and the recovered calls continue
through the existing Off, Compact, and Detailed display policy.
The Speak message action now follows configured voice readiness and idle output
state instead of active Voice Mode or presentation style. A settled assistant
reply can therefore be read aloud directly from chat, while live or provider
playback still prevents overlapping output. One-shot message narration owns its
completion state outside Voice Mode and replaces Speak with Stop while active;
stopping drains only that narration pipeline and does not cancel a chat turn
started while the response was playing.
## 2026-08-09 — Quiet reasoning and grouped tool activity
Android Chat now treats reasoning and routine tools as transcript scaffolding.
Visible live reasoning opens automatically without a tinted card, then collapses
to a quiet Thought disclosure when it settles unless the reader has explicitly
chosen its state. Empty reasoning remains absent and the existing first-token
status continues to own the waiting state.
Top-level routine calls retain their source order but render as consecutive
activity runs. A live run keeps one summary and one latest-activity ticker in a
stable footprint; a settled run becomes one collapsed summary that can disclose
the original identity-preserving tool rows. File edits, approval/question tools,
generated media, failures, output-risk findings, and delegated work split runs
and retain independent surfaces. Off hides only ordinary activity runs, Compact
uses compact disclosed rows, and Detailed preserves the full per-tool detail
surface on demand. Expansion still yields bottom-follow ownership, and each run
registers its measured bounds as Chat pet terrain.
## 2026-08-09 — Android chat experience and attachment polish
The Android composer now declares sentence capitalization and a Send IME
action. A device-level setting chooses whether unmodified physical Enter sends
or inserts a newline; Shift+Enter remains a newline and Ctrl/Command+Enter
always submits. Every submit route converges on the existing live-turn owner,
so the current gateway state still decides whether content steers the active
turn or queues behind it. Directional focus traversal is cancelled while the
editor owns focus so hardware arrow keys continue to move the caret and
selection.
Conversation bottom-follow now remains owned when thinking or tool details
expand. Only an actual drag ending above the bottom yields that ownership, and
a chat first measured while the IME is already visible now captures the same
resize-follow state as a keyboard opened after composition.
Bitmap-backed attachment surfaces now apply EXIF rotation and reflection before
display. Attachment reads and Base64 conversion also leave the UI thread, so
selecting a larger photo no longer performs the full ingestion path inside the
activity-result callback.
Composer drafts now belong to the stable connection, profile, and session
identity. Text, edit context, and pending attachments restore when returning to
a chat without persisting attachment bytes. Pending attachments expose bounded,
orientation-aware previews plus explicit remove and reorder controls.
Conversation overflow now opens transcript search with previous/next matches
and a prompt-turn rail, both keyed to the same stable UI identity as the message
list. Assistant prose retains the compact bubble and subtle edge treatment that
keeps it legible above the animated chat background. Tapping a message reveals
the existing copy, quote, speak, and edit actions with reduced-motion-aware
expansion and accessible targets.
Quotes are composer-owned structured references instead of raw blockquote text.
The composer and sent message render a linked, highlighted author preview; the
transport remains ordinary Markdown so unmodified Desktop and TUI clients show
a readable quoted reply. Thinking and top-level tools continue to use their
independent compact thought bubbles and configured compact or full tool cards,
without an aggregate completion card. The composer also names Correction and
Queue states with visible labels. Gateway redirects remain text-only:
follow-ups with attachments are forced through the existing destination-owned
queue so files cannot be left behind by a correction request.
## 2026-08-08 — Standalone Android thinking status
Blank streaming assistant rows now present the full-size working animation
directly in the conversation lane above the visible `Still working…` label,
without painting an empty assistant bubble around the status. The first answer
token replaces that standalone state with the normal response bubble, while
recovery retains the distinct `Reconnecting to your answer…` wording. The
status owns one stable TalkBack description and suppresses animated child
nodes, avoiding repeated announcements without claiming measurable progress.
## 2026-08-08 — Android text-share draft handoff
The shared Android manifest now advertises a `text/*` `ACTION_SEND` target for
both app flavors. `MainActivity` accepts only non-blank single-item text shares
and places them in a process-local, identity-fenced handoff that survives cold
Compose initialization. Once the configured chat context settles, the app root
navigates to Chat and delegates draft creation and composer prefill to
`ChatViewModel`.
The ViewModel reuses the existing new-chat lifecycle, preserving Gateway
background-turn reconciliation and the active connection/profile/transport
namespace. Composer prefills use a one-consumer conflated channel so an intent
received before Chat composition is delivered once. Shared text is never
routed through message sending; the user must review and submit it explicitly.
## 2026-08-08 — Android Profile Shelf and profile-context identity
Chat profile selection now lives in a collapsible shelf directly below the top
app bar. The header toggles the shelf, the active capsule opens Agent Passport,
inactive 48 dp avatars switch context, and a pinned overflow opens the same full
switcher used by Passport. Saved ordering and hidden state drive both surfaces;
the selected hidden profile remains disclosed, while a one-identity shelf stays
out of the layout. Long-press actions expose inspection, Passport, profile lock,
and hiding without adding activity or presence claims.
The shelf uses the chat surface instead of a second elevated toolbar. A neutral
active capsule, 36 dp avatar artwork inside 48 dp targets, compact spacing, and
a contained overflow affordance keep the row visually subordinate to Chat. When
Server default resolves to a concrete profile, that profile's avatar remains
the identity and a small home badge discloses its default routing role.
Local avatar lookup remains keyed to the Server-default presentation identity,
so an image customized while that row is selected appears consistently in both
the Chat header and shelf rather than being re-keyed to whichever explicit
profile is currently active.
The Server-default sentinel is now distinct from a profile literally named
`default`. Profile selection restores the last compatible connection/profile/
transport session, otherwise leaves a fresh draft. Gateway turns detach and
reconcile in their original session, live SSE turns keep switching disabled,
and every profile transition clears session-scoped model, provider, personality,
reasoning, approval, Fast, and YOLO state before the destination session seeds
its own values. Server sticky-default state is never written.
## 2026-08-08 — Streaming reply tail follow
Android's conversation-bottom follower now reads the current immutable message
list from Compose state inside its long-lived layout observer. Each streamed
replacement can therefore advance the viewport as the active bubble gains
lines, while dragging or scrolling away still releases bottom ownership.
## 2026-08-08 — Settled live replies transition to Markdown
Android now releases the live plain-text renderer immediately after an
assistant row settles. The transition retains the row's stable UI identity,
commits the final live frame before replacing its selectable text topology,
and anchors the same bottom-owned row during the Markdown remeasure. Readers
who scrolled away retain their viewport, while completed code fences, lists,
emphasis, links, and interrupted partial replies no longer require session
navigation before rich rendering appears.
## 2026-08-08 — Explicit-consent ownership for Android approvals
Android no longer treats unrelated Gateway activity or a terminal display event
as proof that an approval was resolved. Approval cards remain pending through
scrolling, recomposition, navigation, and background restoration, and retain
their exact connection, profile, and session ownership. Only a labeled action
that successfully reaches `approval.respond`, an authoritative upstream expiry,
or an explicit interrupt can retire the local request; the interrupt path stays
visibly denied because upstream force-denies it.
## 2026-08-08 — Agent Passport control and dismissal accessibility
The Android Agent Passport keeps its title and explicit close action outside
the nested content scroller. Material bottom-sheet gestures are enabled again,
so a downward gesture scrolls long content toward its top boundary before the
sheet receives the gesture and dismisses; backdrop and Back dismissal retain
the same callback.
Safety and speed choices now sit below their labels instead of competing for a
narrow horizontal column. Every segment provides at least a 48 dp target,
allows two-line labels, exposes radio-selection semantics, and states the
meaning of the current approval, chat override, or processing-tier choice in
plain language. The layout remains scrollable on compact heights and at larger
font scales without moving the close action off-screen.
## 2026-08-08 — Session-owned Android send queues
Android follow-up queues now capture the composing connection/profile context,
stored session, configured transport, originating run, attachments, and voice
context as one immutable destination. Queue presentation is filtered to the
visible session, while completion eligibility is tied to the exact run and live
Gateway generation that owned the queue. A completion from another session or
an older live generation cannot dispatch through the current composer route.
In-flight checkpoints retain bounded queued text across process restoration.
Attachment bytes are not copied into Preferences DataStore; an attachment queue
that cannot be restored is rejected with a visible review-and-resend notice.
Connection replacement and session deletion cancel their owned queues, while
switching among concurrent Gateway sessions preserves each session's queue.
## 2026-08-07 — Provider-owned model inventory identity
Android now normalizes Gateway and API model inventories before publishing
them to picker consumers. Repeated provider rows merge by canonical provider
slug, repeated exact model IDs collapse within that provider, and capability
metadata follows the same provider/model identity. Models intentionally offered
by different providers remain distinct choices, even when their display labels
and model IDs match.
The searchable picker groups and keys rows by provider slug plus exact model ID
instead of provider display text. Cached loads, dynamic refreshes, API aliases,
and Manage inventory use the same idempotent identity rule, preventing duplicate
catalog data from reaching keyed Compose lists without hiding valid routes.
## 2026-08-05 — Restored chat bottom ownership and effort fallback clarity
Opening an existing Android session now retains exact bottom ownership through
late, non-streaming layout changes. Composer capability controls, status rows,
and restored message content can finish measuring after history first reaches
the footer; a session-scoped geometry observer corrects those changes without
using a fixed delay. New-message following remains governed by the smooth
auto-scroll setting, while a real drag, IME ownership, and the Voice dock keep
their existing anchors.
The advisory effort drawer now states that Hermes does not advertise exact
levels for the selected model before explaining why standard options are shown.
The wording is consistent across all shipped Android locales.
## 2026-08-05 — Provider-aware reasoning effort discovery
The optional Relay plugin now exposes a bearer-protected, profile-aware model
capability overlay without requiring changes to upstream Hermes. Android merges
that overlay with the standard `model.options` inventory using exact provider
and model identities, while older or unpaired Relay installations continue with
the canonical advisory fallback.
Dynamic LM Studio, Ollama Cloud, and Copilot discovery is bounded by a shared
network limiter, cached by profile, endpoint, model, and credential fingerprint,
and fenced across refresh generations. Neither credentials nor internal cache
scope are returned to clients. Composer controls, Agent Passport, session
creation, and asynchronous server reconciliation share the same capability
resolver so a displayed effort cannot silently differ from the value sent.
## 2026-08-05 — Chat drawer and companion terrain ownership
The Chat screen now clears composer focus when the session drawer commits to
opening, dismissing the IME without continuously clearing focus from drawer
search or rename fields. Drawer refreshes override keyed list anchoring only
when the leading session identity changes, keeping the newest row visible after
activity-based reordering.
Floating companions wait for Chat's measured composer rail before publishing
their first roaming position. Their collision footprint contains both the
pointer target and rendered sprite, and the complete scroll-to-bottom control
envelope is an obstacle rather than a landing perch. Supported rails add no
visual lift, and the floating-only renderer aligns each frame's opaque bottom
edge to its canvas baseline so transparent atlas padding cannot make pets hover;
centered previews and message avatars remain unchanged.
## 2026-08-05 — Measured pet placement and passive model sync
The floating pet now remains unpublished until the app-level overlay has a
positive measured viewport. Its initial home coordinate is therefore derived
from the real safe bounds instead of the zero-size pre-measure bounds that
collapsed to the top-left corner.
API provider inventory remains an optional background catalog on Gateway-led
connections. A timeout, refusal, or unavailable optional route no longer emits
a global chat notice during initialization, reconnection, or connection-sheet
refresh. The failure is retained as a contextual warning in local Diagnostics,
including the operation, endpoint role, redacted stack trace, preserved network
cause, and targeted troubleshooting guidance. Cached and Gateway-owned model
options remain unchanged.
## 2026-08-05 — Stable chat-tail completion
Chat and Voice now treat the active streamed reply as the owner of its live
renderer until a different row becomes the conversation tail. Stream
completion retains the existing Compose subtree and list anchor; the full
Markdown renderer is deferred until the row is no longer active or the session
is revisited.
The last-in-group timestamp occupies its final geometry from the first
streaming frame and is only revealed at completion. Measured positive growth
during an active stream continues to follow the bottom without replacing the
logical anchor. Once completion layout stabilizes, a bottom-owned transcript
settles to the exact LazyColumn boundary; proximity slop is reserved for
retaining follow intent during motion and cannot define the final position. The
visible footer supplies the exact remaining distance so rounding or adjacent
layout changes cannot leave a residual forward range.
IME expansion participates in that same viewport owner. A transcript already
at the bottom advances by the measured viewport-height loss throughout the
keyboard animation, then settles exactly after inset updates stop on both open
and close. A transcript being read above the bottom preserves its existing
anchor, and a real drag cancels keyboard follow immediately. Host-side coverage
verifies renderer ownership, unchanged bubble height, exact footer settling,
keyboard arming, viewport loss, completion/IME settlement ownership, and
history-reading behavior.
## 2026-08-05 — Focus voice input boundary repair
The Focus voice presentation remains modal without installing a consuming
pointer handler on the full overlay ancestor. Its click-through guard is now a
behind-content sibling: empty-space gestures cannot reach the chat or drawer,
while the mic, close, expand/collapse, and panel controls receive their full
pointer sequence.
Host-side Compose coverage injects real touch events instead of invoking
semantic click actions. It verifies both child callback delivery and the modal
background boundary so the two requirements cannot regress independently.
## 2026-08-05 — Actionable Android connection diagnostics
Android diagnostic entries now separate the configured route from the exact
request operation and path used to test it. Relay health checks identify the
HTTP `/health` probe that precedes a WebSocket connection, route selection
records its Dashboard, API, or Relay probe, and WebSocket and API checks name
their handshake or authentication stage.
Known network and HTTP failure classes attach a bounded next step for refused
listeners, DNS, routing, timeouts, TLS, credentials, rate limits, missing
routes, and server failures. The activity list, status timeline, detail dialog,
copy text, and GitHub issue prefill all carry the same context. Public issue
text preserves protocol and request paths while redacting hosts, credentials,
queries, and user information.
## 2026-08-04 — Android transcript identity ownership
ChatHandler now owns one render identity for every published transcript row.
Checkpoint recovery and all streamed message mutations resolve both the mutable
server/domain ID and the stable UI identity, so history adoption cannot leave a
stale client reference that appends a second row. The publication boundary also
coalesces repeated render identities before Chat or Voice can observe them,
while keeping the first transcript position and latest state.
Focused coverage composes history reconciliation with checkpoint restore,
exercises stale post-adoption callbacks, and runs deterministic transition
sequences across restore, replay, deltas, thinking, and usage updates. Voice's
temporary transcript row now occupies an auxiliary key namespace disjoint from
real message rows.
## 2026-08-04 — Android reliability and support foundation
Android fatal capture and centrally classified handled failures now converge on
a versioned, allowlisted reliability record. Reports are redacted before local
persistence, capped at 20 records with 14-day retention, written atomically,
and correlated only with random app/report identifiers. Expected cancellation
and permission denial remain non-reportable. The pre-existing one-file crash
format migrates locally on first launch.
Crash recovery leads with the recovery outcome and no-upload guarantee, then
requires an explicit review before copy, share, or GitHub actions. Diagnostics
adds an offline support-information review using the same exact redacted text.
Android issue prefills now request the Android area while repository-wide issue
ownership remains maintainer-reviewed, and the release workflow retains both
variant R8 mappings for deterministic retrace.
The architecture audit defers an ANR watchdog, richer allowlisted breadcrumbs,
hashed product correlation, and OOM emergency writing until their lifecycle,
privacy, and false-positive behavior can be validated on devices.
## 2026-08-02 — Android Russian localization
Android now ships complete Russian catalogs for the main and sideload builds.
The in-app language picker, Android locale configuration, chat and voice labels,
tool and status presentation, diagnostics, onboarding, and plural resources are
registered against the canonical English catalog. Existing non-English catalogs
were refreshed to retain exact resource and format-argument parity.
The integration preserves PR #276 as the source contribution while excluding
unrelated recovery, routing, and test-stability changes from the localization
scope. The localization registry records Android coverage only; Russian public
documentation and marketing pages continue to use the canonical English
fallback until those surfaces are translated separately.
## 2026-07-31 — Upstream-compatible voice interruption semantics
Android full-turn barge-in now follows upstream Hermes' RMS behavior: roughly
450 ms of quiet-room calibration, a 90th-percentile floor, 3× default
multiplier, separate generation/playback minimums, a bounded ceiling, 500 ms
playback grace, and an 80%-majority decision window. Calibration remains frozen
against speaker output and cannot itself trigger. Renderer-driven phase tracking
returns to generation thresholds in quiet output gaps and rearms playback grace
only after a gap of at least one second. Opt-in Logcat diagnostics expose the
inputs used for device tuning. Barge-in is enabled by default while retaining its master,
Silero sensitivity, RMS multiplier, playback grace, and resume controls.
Voice stop phrases now use an editable exact-match list that defaults to
`stop`; clearing the list disables the behavior. A match ends the active voice
chat in generation or playback, but the same word outside voice chat and longer
requests continue through normal Hermes input. Continuous-mode pause/resume and
explicit background-task cancellation retain their narrower state gates.
Interrupting spoken playback arms the upstream one-shot interruption note for
the next Standard model-bound message. The latch expires after 120 seconds and
travels only in API-local voice interface context, never in visible or
persisted user text. Generation and pre-audio synthesis interruption do not mark
an unspoken reply, Realtime keeps its provider-session context, and silencing remains independent
from cancellation of promoted background work.
## 2026-07-30 — Expandable Android assistant surface
Android Digital Assistant sessions now open as a compact bottom bar over the
current app, expand in place for transcript and response detail, and collapse
without changing the active turn. Open full voice disables only the
system-owned session UI and reveals the existing app Voice surface, preserving
the same session, response stream, and microphone owner.
Connection, chat, and voice state machines now have one main-process,
application-lifetime owner. Assistant activation can initialize and run a cold
voice turn without constructing or foregrounding `MainActivity`; opening full
Voice binds the Activity to those same ViewModels and audio resources.
The optional `SYSTEM_ALERT_WINDOW` Voice surface now follows the same
wide-bar-to-expanded-sheet progression while retaining its minimized bubble.
It remains a separately user-invoked control for turns that began in the app;
the Assistant-role session does not require display-over-other-apps permission.
The assistant window is transparent outside the bar or sheet, leaves the
underlying app unresized, and restricts touch interception to the measured
surface. Back collapses an expanded surface first; Back from compact, Stop, and
ordinary dismissal remain terminal. A hidden full-Voice handoff instead follows
the app-owned turn through its final Closed state.
Package-scoped lifecycle reconciliation also clears assistant state if Android
reclaims the separately processed UI while full Voice remains active.
Assistant activation is ID-aware and single-flight. Duplicate delivery cannot
re-arm capture, Retry replaces a pending readiness attempt, and Stop invalidates
the attempt before chat, Voice, or microphone mutations. Scoped voice settings
must hydrate from DataStore before route readiness, and process extraction
preserves connection-catalog isolation plus the existing gateway route-flip
settle window.
Physical-device validation on a Samsung SM-S938U confirmed cold invocation over
a non-Hermes foreground app, compact and expanded presentation without
foregrounding `MainActivity`, and one main-process microphone owner. Locked
invocation reached a shown system assistant session without runtime or recorder
errors; Samsung's secure lock screen prevented screenshot-based visual review.
## 2026-07-30 — Foreground wake-word diagnostics and recovery
The Android-local sherpa listener now treats each non-empty keyword result as a
completed KWS event, resets the stream immediately, and maps the stored
confirmation setting to sherpa's native trailing-blank confirmation instead of
requiring an already-completed result to recur across application frames. Voice
settings can arm a ten-second test against the same foreground service,
microphone owner, installed model, and current tuning; it displays live input
level and reports detection without opening voice or transmitting audio.
Expected empty-transcript responses after activation now record a no-speech
diagnostic and return voice to its ready state with a retry hint rather than
surfacing the provider's HTTP error. Other transcription failures retain the
existing error path. Foreground-service behavior is documented explicitly:
background detections remain pending behind the notification until Hermes is
visible; Android default-assistant integration is a separate mode. Opening the
visible Voice settings screen also reconciles an enabled listener after package
replacement or process death without adding boot/background auto-start.
Focused wake preferences/core and no-speech classification tests pass.
Sideload lint, sideload debug packaging, and Google Play debug Kotlin
compilation pass. This batch adds no model, native library, ABI, permission, or
network dependency; the existing approximately 6 MB downloaded model and
packaged sherpa ABI footprint are unchanged.
## 2026-07-30 — Voice transcript identity alignment
Android voice Focus mode now keys transcript rows with the same stable UI
identity as the main Chat list. A live row may adopt its persisted server
message ID during history reconciliation while retaining its original Compose
identity; using the mutable domain ID in the voice overlay could otherwise
collide during that transition and close the app.
Focused JVM coverage recreates two visible rows with a shared reconciled server
ID and verifies distinct stable transcript keys. Sideload production and
Android-test Kotlin compilation pass. The existing full-overlay instrumentation
fixture remains blocked by its continuously animating surface never reaching
Compose idleness.
## 2026-07-30 — Opt-in Android Digital Assistant mode
Android now declares an explicit `VoiceInteractionService` and separately
processed `VoiceInteractionSessionService`. Only Android's user-confirmed
Assistant role activates the integration. Optional background “Hey Hermes”
detection reuses the local sherpa model and tuning, releases its recorder before
the system session opens the existing voice flow, and resumes after session
exit. Package-scoped lifecycle messages reconcile prompt/listen state,
transcript/response presentation, cancellation, errors, and process recreation.
The Digital Assistant listener and the existing experimental microphone
foreground service are separate, mutually exclusive opt-ins. Both retain local
pre-activation privacy and the shared one-microphone contract. Standard voice
continues through the upstream Dashboard audio surface. Voice settings include
role status, setup, removal, runtime status, and the limitation that third-party
assistants do not receive Google's low-power hotword hardware.
## 2026-07-29 — Full-turn voice interruption and local wake-word preview
Android barge-in now owns one microphone/VAD listener from response generation
through playback drain for both Standard and Realtime voice. Quiet-room RMS
calibration freezes before output begins, playback receives a grace interval,
and model-confirmed majority filtering separates actual interruption from raw
ducking hints. Turn epochs, stream cancellation, late-delta suppression, and
an awaited microphone handoff keep an interrupted response from speaking again
or racing the replacement recording. Exact stop/pause intent is phase-aware,
while explicit background-task cancellation remains separate from silencing.
An opt-in Android-local “Hey Hermes” preview uses sherpa-onnx in a user-started
microphone foreground service. Its approximately 6 MB English model is
downloaded and hash-verified on first enable rather than bundled. The service
keeps pre-activation audio local, exposes an ongoing Stop notification, pauses
for active voice, and shares a process-wide single-microphone ownership
contract with voice recording, barge-in, and realtime diagnostics. The stored
configuration includes strictness, confirmation frames, new-session behavior,
and a deliberately inactive future profile-routing shape.
Focused JVM coverage exercises calibration, grace, listener teardown,
Thinking-to-Speaking ownership, generation/playback interruption, command
gating, wake preferences, activation, and microphone exclusion. Android
compilation for both distribution flavors, sideload lint, and sideload APK
packaging pass with all four supported ABIs. On-device acoustic, foreground
service, and lifecycle checks remain the corresponding validation gates.
## 2026-07-28 — Android 1.5.2 production release
Android 1.5.2 shipped from the approved `dev` to `main` release tree as
versionCode 35. The release adds provider-aware Dashboard sign-in: Nous uses
the advertised native PKCE system-browser flow, while compatible self-hosted
providers retain cookie-backed full-page Dashboard authentication. Callback
origin discovery remains server-driven, private-network HTTP compatibility is
preserved, and arbitrary public HTTP redirects remain rejected.
The private Play preflight validated the exact application tree before release
PR #265 merged. The immutable `android-v1.5.2` tag resolves to the resulting
`main` tip, the production workflow promoted versionCode 35 to the completed
Google Play production track, and the public GitHub release contains the
signed AAB, sideload APK, and SHA-256 manifest. The published sideload APK
checksum was independently verified; replacing the debug-signed phone build
with the release-signed artifact requires an uninstall because Android
correctly rejects cross-signature in-place updates.
## 2026-07-27 — Android replayed-message identity reconciliation
Android history reconciliation now collapses reconnect/rejoin replays of the
same persisted message ID before publishing the transcript to Compose. The
latest repeated snapshot replaces the value at the message's first transcript
position, preserving stable ordering, distinct messages, and the LazyColumn
identity contract without index- or random-key fallbacks.
Focused coverage reproduces the duplicate UUID condition and verifies that the
authoritative final content wins while every rendered message keeps a unique
stable UI key.
## 2026-07-26 — Android 1.5.1 patch reconciliation
Android 1.5.1 reconciles the post-1.5.0 voice and chat fixes into versionCode
@@ -6714,3 +7318,16 @@ After: Phone (HTTP/SSE) → API Server (:8642) [chat — direct]
- Deploy docs site (GitHub Pages or similar)
- Phase 2: Terminal channel (xterm.js in WebView, tmux integration)
- Phase 3: Bridge channel migration
# 2026-07-30 — Wake-word strictness tuning
- Lowered the unset Android wake-word strictness default from `0.6` to `0.3` after physical-device testing showed reliable activation only at the lower slider positions.
- Added the live numeric strictness value to Voice settings so tuning is observable.
- Preserved saved user values and the existing three-frame confirmation default; this adjustment does not migrate working installations or broaden the detector acceptance window beyond the selected threshold.
# 2026-07-30 — OEM assistant-picker compatibility
- Added the standard `android.intent.action.ASSIST` activity filter because some OEM assistant pickers enumerate Assist activities even when a valid `VoiceInteractionService` is present.
- Routed activity-based Assist invocations through the existing system-assistant activation protocol so both Android entry points share microphone ownership and session lifecycle behavior.
- Added the required `recognitionService` metadata and a bounded recognition component after device validation showed Samsung could grant the package role while leaving the active voice-interaction service empty. The component does not open the microphone; Hermes assistant sessions continue to use the established transcription pipeline.
- Declared `CATEGORY_VOICE` on the Assist activity and retained `ACTION_ASSIST` on the explicit activation intent. `VoiceInteractionSession.startVoiceActivity()` adds the voice category, and Android rejects the launch as `START_NOT_VOICE_COMPATIBLE` unless the target filter matches both.
+11 -10
View File
@@ -1,22 +1,22 @@
# Hermes-Relay-Plugin v__VERSION__
# Hermes-Relay-Server v__VERSION__
**Release Date:** July 22, 2026
**Release Date:** August 14, 2026
This patch hardens Relay authorization, adds upstream-aware diagnostics, and keeps plugin bootstrap work off the Gateway event loop.
This release adds an official, opt-in Relay pane for Hermes Desktop through the supported runtime Plugin SDK. It keeps Relay management profile-scoped and user-invoked without opening a pane during startup, reconnects, profile changes, or plugin updates.
It can accompany Hermes-Relay-Android v1.5.0 for optional Relay diagnostics and power features. Standard chat and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
## What's changed
### Added
- **Upstream-aware Gateway diagnostics.** Doctor and `/relay/info` expose optional health, configuration-route, and capability signals so clients can explain compatibility gaps without treating an older upstream install as a broken Relay.
- **Official Hermes Desktop pane.** The unified plugin package registers a movable native pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management.
- **Explicit entry points.** Labeled sidebar, status-bar, and command-palette actions register and reveal the pane lazily; repeated opens reuse the same surface.
- **Profile-scoped state.** Cached Relay state follows the active Hermes profile and is disposed cleanly when the plugin unloads.
### Fixed
### Changed
- **Privileged Relay paths enforce host authorization and active grants.** Pairing, Android bridge, terminal, session policy, remote profile configuration, and voice provider origins retain their intended trust boundaries.
- **Plugin bootstrap remains responsive.** Database initialization and compatibility inspection run outside the Gateway event loop while preserving compatibility with older upstream bootstrap contracts.
- **Windows Gateway detection is non-signalling.** Starting Relay and periodic profile rescans no longer risk terminating an existing Gateway process.
- **Plugin loading stays passive.** Loading, startup, reconnects, profile changes, and updates never reveal the pane or perform pane-owned network work.
## Install / update
@@ -24,13 +24,14 @@ It can accompany Hermes-Relay-Android v1.5.0 for optional Relay diagnostics and
hermes plugins install Codename-11/hermes-relay/plugin --enable
# Classic install / update on a systemd host:
curl -fsSL https://raw.githubusercontent.com/Codename-11/hermes-relay/main/install.sh | bash
curl -fsSL https://raw.githubusercontent.com/Codename-11/hermes-relay/server-v__VERSION__/install.sh | bash
# or, if already installed:
hermes-relay-update
## Verify
hermes relay doctor
# Agent/tool callers can use desktop_health to list desktop targets.
python scripts/check-plugin-version-sync.py --expect __VERSION__
---
+44 -15
View File
@@ -34,10 +34,10 @@
Hermes-Relay puts your [Hermes agent](https://github.com/NousResearch/hermes-agent) on the devices you actually carry. The brain stays on your own machine — Hermes-Relay is how you reach it.
- **📱 Android app** — streaming chat, hands-free voice, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. On sideload builds, the agent can read your screen and act on it.
- **📱 Android app** — streaming chat, hands-free voice, native plugin pages, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. Add a floating Petdex companion or optionally make Hermes your Android assistant; sideload builds can also let the agent read and act on your screen.
- **⌨️ Hermes-Relay CLI** *(alpha)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough — chat, management, and voice need **no plugin**. Add the optional relay only when you want terminal, phone control, or the CLI's tools. **Pair once from either surface; both work.**
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough — chat, management, voice, Petdex, and ordinary installed-plugin pages need **no Relay plugin**. Add the optional Relay only when you want terminal, phone control, agent-created page drafts, or the CLI's tools. **Pair once from either surface; both work.**
<p align="center">
<img src="docs/diagrams/architecture-homepage.png" alt="How Hermes-Relay connects — Vanilla Hermes (Chat, Manage, Voice) runs with no plugin; the optional Relay plugin adds Terminal, Bridge, relay voice and desktop tools to the app and CLI; Device Control needs the sideload build." width="900">
@@ -70,6 +70,21 @@ an HTTPS reverse proxy. The [full walkthrough](https://hermes-relay.dev/docs/gui
covers Windows, remote access, and dashboard authentication. You do not need to
enable the separate API server or invent an API key for the standard path.
For plugin-enabled setups, optional **Hermes Secure Link** presents Relay, API,
and Dashboard routes through one pairing-pinned TLS origin. It protects traffic
to the paired endpoint while each service keeps its own authentication; it does
not provide reachability or independently identify the physical host. You still
use LAN routing, Tailscale or another VPN, or an operator-managed public route
to reach the listener. Secure Link is off by default and requires a fresh QR
pairing after it is enabled. See the
[remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
**Hermes Reach** is an experimental, advanced outbound-broker route. It remains
available for development and self-hosted evaluation, but it is disabled by
default, ordered after supported routes, and not recommended for normal remote
access. Use Tailscale for the easiest supported remote setup, or a public TLS
domain / Direct Secure Link when you want to own the complete network path.
### 3 · Connect and talk
Open the app, choose **Connect to Hermes**, and enter or discover the dashboard
@@ -99,7 +114,7 @@ the whole Vanilla Hermes setup.
### 4 · Optional: install Relay for power tools
Install the Relay plugin on the server only when you want Terminal, Bridge phone control, relay sessions, media routes, or the realtime voice engine:
Install the Relay plugin on the server only when you want Terminal, Bridge phone control, relay sessions, media routes, the realtime voice engine, or approval-gated agent-created plugin-page drafts:
```bash
hermes plugins install Codename-11/hermes-relay/plugin --enable
@@ -115,8 +130,11 @@ shell shims, and the full clone/update workflow:
curl -fsSL https://raw.githubusercontent.com/Codename-11/hermes-relay/main/install.sh | bash
```
The plugin-manager install owns the plugin code, dashboard tab, CLI commands,
and agent tools. `hermes relay compat status/install/remove` manages only the
Installed Hermes plugins can expose bounded, host-rendered pages to Android
through the authenticated Dashboard without running plugin code on the phone.
Relay 1.5.0 additionally supports approval-gated agent-created page drafts. The
plugin-manager install owns the plugin code, dashboard tab, CLI commands, and
agent tools. `hermes relay compat status/install/remove` manages only the
optional legacy API compatibility hook when an older Hermes build needs it. Scan
the QR from the phone's Connections screen — or use
`hermes pair --register-code ABCD12` with the manual code from Android
@@ -135,7 +153,7 @@ Full server setup, TLS, and systemd details: [docs/relay-server.md](docs/relay-s
<table>
<tr>
<td align="center" width="25%"><img src="assets/screenshots/01_startup.png" alt="Cold start" width="100%"><br><sub><b>Cold start</b></sub></td>
<td align="center" width="25%"><img src="assets/screenshots/01_voice_conversation.png" alt="Voice controls in chat" width="100%"><br><sub><b>Voice in chat</b></sub></td>
<td align="center" width="25%"><img src="assets/screenshots/02_chat.png" alt="Streaming chat" width="100%"><br><sub><b>Streaming chat</b></sub></td>
<td align="center" width="25%"><img src="assets/screenshots/03_voice.png" alt="Hands-free voice" width="100%"><br><sub><b>Hands-free voice</b></sub></td>
<td align="center" width="25%"><img src="assets/screenshots/04_sessions.png" alt="Session history" width="100%"><br><sub><b>Session history</b></sub></td>
@@ -159,7 +177,7 @@ Full server setup, TLS, and systemd details: [docs/relay-server.md](docs/relay-s
</table>
The Android app ships complete AI-assisted catalogs for **Deutsch**, **Español**,
**日本語**, **Português (Brasil)**, and **简体中文**. Choose a language from
**日本語**, **Português (Brasil)**, **Русский**, and **简体中文**. Choose a language from
**Settings → Appearance → Language**; translation status and fluent review are
tracked independently so community corrections remain easy to contribute.
@@ -183,7 +201,7 @@ tracked independently so community corrections remain easy to contribute.
## Hands on any machine — the Hermes-Relay CLI&nbsp;<sub>(alpha)</sub>
> **Alpha.** Self-contained CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64 — no Node required. Windows also has an optional native, menu-only systray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
> **Alpha.** Self-contained CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64 — no Node required. Windows also has an optional compact management tray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
The agent's brain stays on the host; the CLI lets it call tools **on your machine** over the same WSS relay — `read_file`, `write_file`, `terminal`, `search_files`, `screenshot`, `clipboard`, `open_in_editor`, and more — behind a one-time consent gate, interactive diff approval for patches, and a `--no-tools` kill-switch.
@@ -199,7 +217,15 @@ hermes-relay update # self-update via GitHub Releases
It pairs against the **same relay and credential store** as the Android app — pair once from either, both work. Tagged on the `desktop-v*` [release track](https://github.com/Codename-11/hermes-relay/releases?q=desktop), with historical releases still visible under `cli-v*`.
On Windows, the default installer adds the optional right-click-only systray: no dashboard or app window, just TUI launch, User/Administrator-aware daemon controls, pairing, local grant review, audit, diagnostics, logs, desktop-use status/cancellation, sign-in startup, and emergency stop.
On Windows, the default installer adds the optional compact **Hermes-Relay CLI UI** tray popup for host selection and pairing, connection and daemon state, per-host Ask/Trusted/Full Access, local grant dialogs, authorized-client revocation, activity, settings, and emergency stop. It is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
Structured Windows computer control prefers a compatible local CUA Driver
runtime for window-targeted background actions and virtual per-session agent
cursors. It remains behind Hermes host policy, grants, targeting, audit, and
emergency stop; Windows input is an explicit compatibility backend. CUA is not
bundled or updated automatically, but the local CLI/UI can explicitly install,
check, or update its verified canonical package. It is never exposed as a raw
remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs/desktop/tools.html#computer-use-engines).
- **Docs:** [CLI guide](https://hermes-relay.dev/docs/desktop/) · [`desktop/README.md`](desktop/README.md)
- **AI-agent setup recipe:** `/hermes-relay-desktop-setup`
@@ -264,11 +290,14 @@ Already installed? The same recipe is auto-loaded as a Hermes skill — invoke `
```bash
# Android: open the repo root in Android Studio, wait for Gradle sync, Run (Shift+F10).
scripts/dev.bat build # Build debug APK
scripts/dev.bat build # Build sideload debug APK
scripts/dev.bat compile # Compile sideload Kotlin only
scripts/dev.bat test-one "com.hermesandroid.relay.SomeTest" # Focused unit test
scripts/dev.bat install-fast # arm64 phone build + install + launch
scripts/dev.bat release # Build signed release APK
scripts/dev.bat bundle # Build release AAB for Google Play
scripts/dev.bat run # Build + install + launch + logcat
scripts/dev.bat test # Run unit tests
scripts/dev.bat run # Build sideload + install + launch + logcat
scripts/dev.bat test # Run sideload debug unit tests
scripts/dev.bat version # Show current version
scripts/dev.bat relay # Start the relay server (dev, no TLS)
```
@@ -277,13 +306,13 @@ scripts/dev.bat relay # Start the relay server (dev, no TLS)
| Component | Stack |
|-----------|-------|
| **Android app** | Kotlin 2.0, Jetpack Compose, Material 3, OkHttp |
| **Android app** | Kotlin 2.4, Jetpack Compose, Material 3, OkHttp |
| **Hermes-Relay CLI** | TypeScript, Bun-compiled native binary, Node ≥21 (source/dev), zero runtime deps |
| **Server / plugin** | Python 3.11+, aiohttp |
| **Serialization** | kotlinx.serialization (Android) |
| **Build** | AGP 9, Gradle 8.13, JVM toolchain 17 (Android); `tsc` + `bun build --compile` (CLI) |
| **Build** | AGP 9.3.1, Gradle 9.6.1, JVM toolchain 17 (Android); `tsc` + `bun build --compile` (CLI) |
| **CI/CD** | GitHub Actions — lint, build, test, APK artifact, CLI binaries per platform |
| **Min SDK** | 26 (Android 8.0) · Target SDK 35 |
| **Min SDK** | 26 (Android 8.0) · Target SDK 36 |
<details>
<summary><b>Repository structure</b></summary>
+5 -3
View File
@@ -18,9 +18,9 @@
## 功能简介
- **Android 应用**:流式聊天、会话历史、文件附件、Hermes 管理、语音模式、多连接和配置文件。
- **Android 应用**:流式聊天、会话历史、文件附件、Hermes 管理、语音模式、原生插件页面、Petdex 悬浮宠物、多连接和配置文件;也可将 Hermes 设为 Android 助手。
- **无需插件的标准路径**:聊天、管理和标准语音可直接连接未修改的上游 Hermes Agent。
- **可选 Relay 插件**:增加终端、手机控制、媒体传输、通知助手、Relay 语音和电脑工具。
- **可选 Relay 插件**:增加终端、手机控制、媒体传输、通知助手、Relay 语音、电脑工具,以及需确认的代理创建插件页面草稿。
- **安全连接**:二维码配对、Android Keystore、证书固定、按通道授权和可配置会话有效期。
- **远程使用**:可配置 Tailscale 或 HTTPS 地址,在家庭局域网和远程路由之间自动切换。
- **两种 Android 发行渠道**:Google Play 版本适合日常使用;sideload 版本包含完整手机控制能力。
@@ -67,7 +67,7 @@ hermes gateway
### 4. 可选:安装 Relay
仅在需要终端、手机控制、媒体路由、Relay 会话、实时语音或电脑工具时安装:
仅在需要终端、手机控制、媒体路由、Relay 会话、实时语音、电脑工具或代理创建插件页面草稿时安装:
```bash
hermes plugins install Codename-11/hermes-relay/plugin --enable
@@ -76,6 +76,8 @@ hermes relay start --no-ssl
hermes pair
```
已安装的 Hermes 插件可通过已认证的 Dashboard 向 Android 提供由应用安全渲染的原生页面,无需在手机上运行插件代码。Relay 1.5.0 另支持需用户确认的代理创建页面草稿。
完整说明请阅读[中文快速开始](https://hermes-relay.dev/docs/zh-CN/guide/quick-start);远程访问、协议和高级配置暂时链接到英文参考文档。
## 中文界面
+22 -4
View File
@@ -119,19 +119,23 @@ artifacts.
### CLI / tray versioning
`desktop/package.json` is the Desktop/CLI release track's source of truth. Its version
must match the generated CLI and native Windows systray metadata. The systray is
a menu-only controller for the installed CLI; it has no application window,
WebView, embedded terminal, or separate desktop product surface. The public
must match the generated CLI and Windows tray metadata. The tray is a compact
management popup over the installed CLI and shared state; it has no chat,
embedded terminal, plugins, voice, or separate desktop product surface. The public
release remains one `Hermes-Relay-Desktop` track containing CLI binaries plus the
optional Windows installer.
| File | Purpose |
|---|---|
| `desktop/package.json` | canonical CLI version |
| `desktop/.bun-version` | exact Bun compiler/runtime for standalone binaries |
| `desktop/package-lock.json` | npm root/workspace package metadata |
| `desktop/src/version.ts` | compiled CLI runtime version |
| `desktop/tray/Cargo.toml` | native systray package version |
| `desktop/tray/Cargo.lock` | locked systray package version |
| `desktop/tray/tauri.conf.json` | tray application and bundle version |
| `desktop/tray/package.json` | tray UI package version |
| `desktop/tray/package-lock.json` | locked tray UI package version |
Prepare a new CLI version on `dev` without creating a tag or npm-generated
commit:
@@ -149,6 +153,8 @@ manually, run `npm run sync:version` before checking. `npm run verify` is the
single Windows release-parity gate: version sync, type-check, tests, TypeScript
build, compiled CLI smoke, and tray formatting, Clippy, check, and tests. CI runs
the portable portions on every desktop change and the Windows tray gates separately.
Release jobs read `desktop/.bun-version`; cross-built and Windows-built artifacts
must not silently embed different Bun runtime versions.
## Branching policy
@@ -494,6 +500,14 @@ the new app version and a higher `appVersionCode`.
in `app/build.gradle.kts`. Never rename the sideload APK — the
in-app update checker matches assets by `.apk` + `sideload` in the
name, and user-docs verify steps cite the filename.
The release workflow also retains
`app/build/outputs/mapping/{googlePlayRelease,sideloadRelease}/mapping.txt`
for 90 days in the `android-r8-mappings-<version>-<sha>` workflow
artifact. It is intentionally not a GitHub Release asset. To symbolicate an
in-app or sideload report, download the artifact for the exact version/SHA and
run Android's retrace tool with the matching flavor mapping:
`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/whats_new.txt` — in-app "What's New" content
shown in the settings/about screen. Update with the version number
and a brief feature summary. Gets stale silently if forgotten
@@ -509,7 +523,11 @@ the new app version and a higher `appVersionCode`.
the version reference and the "Release Notes" section that gets
pasted into the Play Console "What's new" field. Keep the Play
"What's new" within **500 characters** and framed around the
release's themes, not a feature dump.
release's themes, not a feature dump. Compare its **Foreground service
permissions** section with the merged `googlePlayRelease` manifest and
complete Play Console declarations for every declared service type before
approval; the Publisher API can upload a draft and still reject promotion
when an App content declaration is missing.
#### Scrub for public distribution
+20 -13
View File
@@ -1,10 +1,10 @@
# Hermes-Relay-Android v1.5.1
# Hermes-Relay-Android v1.11.0
**Release Date:** July 26, 2026
**Release Date:** August 20, 2026
## Download
> Installing on your phone? Download `hermes-relay-1.5.1-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.11.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,22 +12,29 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
## Summary
This patch restores reliable narration and background behavior in Voice, adds focused and full-conversation voice layouts, and keeps richly formatted streamed answers anchored at their completed end.
This release makes Android control more explicit and chat recovery more honest. Sideload users can grant only the Bridge capabilities they intend, including bounded or unlimited screen access, while every build gains clearer stored-session failures, complete multiline keyboard behavior, persistent cancellation status, and lower idle power use.
## Added
- Voice Focus keeps narration, Markdown, tools, media, and actionable cards in a compact voice-first view.
- Voice Conversation exposes the complete Chat renderer while preserving the active voice session.
- A final-answer speech preference keeps intermediate progress visual while supported voice paths wait for the settled response.
- Choose read-only, read-and-confirm, or custom Bridge capability presets for the active connection in sideload builds.
- Grant screen inspection and control for a bounded duration or explicitly keep them unlimited, with the active policy reflected in Relay status.
## Changed
- Use a summary-first Bridge screen that separates Agent access, unattended mode, Android readiness, and advanced safety without removing the full permission matrix.
## Fixed
- Standard Voice narrates valid completed assistant responses instead of losing them during the generation-to-speech handoff.
- Realtime tasks promoted to background release the foreground spinner and microphone while progress and results remain reachable.
- Completed streamed answers switch to full Markdown and preserve the measured trailing edge instead of jumping to the start of the response.
- Assistant text uses the theme's full-contrast foreground with a more readable chat type scale.
- Keep stored-session resume failures in the conversation with route-aware details and explicit retry or dismiss actions instead of silently switching context.
- Insert newlines from both direct-text and synthesized-Enter software keyboards while preserving physical Enter, Shift+Enter, and Ctrl/Cmd+Enter behavior.
- Retain the Stopped status when a blank recovery placeholder is cancelled.
- Stop idle Sphere, waveform, and closed-drawer redraw loops when no motion is visible.
- Attach screen-capture surfaces only for requested frames, release unattended wake locks at command completion, and bind audio effects to the capture session.
- Reuse wake-word normalization buffers during continuous opt-in listening.
## Install / Verify
- App version: **1.5.1** (versionCode **34**).
- Standard Chat and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
- App version: **1.11.0** (versionCode **46**).
- Standard Chat, sessions, Manage, stored-session recovery, software-keyboard multiline input, and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
- Granular Device Control grants and screen-access durations are sideload-only; the Google Play build continues to ship Hermes Bridge Core without AccessibilityService Device Control.
- The optional Relay plugin is not required for standard Android chat, session recovery, or multiline composition.
+154 -19
View File
@@ -6,6 +6,100 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
---
## Certify Android power fixes across the reported device matrix
Issue #377's static estimates are not device measurements. The code now keeps
the idle Sphere static, gates inactive waveform/drawer animation, detaches the
MediaProjection surface between requested frames, binds AEC/NS to the capture
session, releases unattended wake locks at command completion, and reuses the
wake-word normalization buffer. Complete the remaining physical proof before
assigning battery percentages or declaring the report closed:
- Re-run the reported Android 13 / Pixel 4 XL workload with screen-on and
screen-off intervals separated, and with experimental wake listening both
disabled and explicitly enabled. Capture scoped CPU/thread/network/wakelock
evidence plus Battery Historian or Perfetto without resetting batterystats
unless the device owner approves the reset.
- On Android 14+ and a foldable/rotation path, request two screenshots around a
geometry change and verify the existing VirtualDisplay resizes, its surface
is detached between requests, and the projection token is not reused.
- On at least one device with platform AEC, run Standard and Realtime barge-in
through playback and confirm the effect is enabled on the AudioRecord session,
the microphone remains single-owner, interruption still works, and teardown
leaves no audio effect or capture session active.
- Compare Wi-Fi and cellular separately. Treat radio-tail claims as unproven
until packet timing and mobile-radio active time reproduce them on hardware.
---
## Certify the official Desktop Relay plugin
The unified `plugin/desktop/plugin.js` implementation is covered by source-level
SDK contract, packaging, explicit-open, no-auto-open, close, unload, and profile
cache-isolation tests. A physical official Hermes Desktop session is still
required before calling the UX live-certified:
- Test default and named local profiles, ordinary authenticated remote mode,
and SSH mode with differently named local/remote profile mapping.
- In two full app windows, prove enabling, registration, explicit open,
requests, close/reopen, hot reload, and disable/unload remain window-local.
- Prove startup, reconnect, profile change, layout restore/reset, update, and
background events never open or focus Relay.
- Drag and dock the pane across native zones, close it, reopen it from all three
labeled actions, and verify no private-hook fallback is needed.
- Exercise Relay running/unreachable, zero/one/multiple devices, pairing,
revocation, bridge activity, media, remote access, and renderer error logging
without exposing credentials, pairing payloads, filesystem paths, or tokens.
---
## Structured desktop hardware capabilities
Structured access and per-host USB policy now ship with typed, serial-bound ADB
list, shell, push, pull, install, and bounded logcat operations. Remaining work:
- Add microphone and camera only with backend readiness detection, bounded local
grants, active-use indicators, audit events, and immediate cancellation.
- Reconcile legacy `desktop_screenshot` with the task-granted computer screenshot
path so screen capture follows one policy.
- Extend capability policy beyond hardware only where a typed broker provides a
meaningfully stronger boundary than Structured mode already provides.
---
## Android Plugin Studio protocol follow-ups
The first live declarative Plugin lane is host-local: Relay tools create bounded
draft JSON, Android previews it through the authenticated Dashboard namespace,
and exact-digest Keep/Remove actions require an Android user tap. Complete the
multi-session protocol before treating `lifecycle=session` as an isolation claim:
- Derive draft ownership from trusted Hermes task context and store only an HMAC
of that identifier; never accept a model-supplied session owner.
- Filter draft discovery by the Android app's active Hermes session while keeping
profile and connection publications separate with explicit precedence.
- Replace foreground five-second catalog polling with authenticated catalog
invalidation events plus ETag polling fallback.
- Expire abandoned drafts and pending approvals, and add revision-bound profile
versus connection promotion targets.
---
## Split fast Android unit tests from resource and screenshot tests
The quick-loop commands now narrow execution to the sideload debug variant and
support one-class filtering, but all `:app` unit tests still share one Android
test variant. That variant includes merged Android resources, gives every test
worker a 2 GiB heap, runs on JDK 21, and enables Roborazzi recording because a
small subset of Robolectric/screenshot tests requires those settings.
Create a separate resource/screenshot test lane so pure state, parser, routing,
and formatting tests can run as ordinary JVM tests without Android resource
packaging. Keep golden-image recording explicit rather than applying it to all
unit tests, preserve a CI task that runs both lanes, and benchmark cold plus
warm focused-test latency before adopting the split.
---
## Verify Android native dashboard sign-in on device
Android now selects Custom Tab + PKCE for HTTPS gateways that advertise
@@ -875,7 +969,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
- Live gateway must discover the plugin (`~/.hermes/plugins/hermes-relay` → `plugin/`) and `plugins.enabled` must include `hermes-relay` for the `phone` platform to register. Confirm `phone` appears in `hermes gateway status` with `PHONE_ENABLED=1`.
- End-to-end: with the app paired + "Let Hermes message me" on, run `send_message target=phone text=...` (and a cron `deliver=phone`) and confirm a notification on the device. Verify 503 (no phone) and the off-by-default gates.
- **Phase 2c reply round-trip — ✅ DONE (verified on-device 2026-06-29).** Confirmed: agent → phone notification → inline reply → drained through the relay's loopback `GET /phone/replies` (different process) → `handle_message` (`role_authorized=True`, no `PHONE_ALLOW_ALL_USERS`) → agent answer back in the *same* thread. Both fixes required (see DEVLOG / the Phase 2c bullet above).
- **FIX: cron `deliver=phone` / standalone send is broken.** Live testing: `hermes send --to phone` returns `{"error": "Unknown platform: phone"}`. The standalone (non-gateway) send path doesn't run a `kind=standalone` plugin's programmatic `ctx.register_platform`, so it never learns `phone` — only the running gateway (which loads `register()` at startup) does. The agent path (`send_message target=phone` in the gateway) works and was verified end-to-end on-device; the standalone/cron path needs the platform discoverable there too (declare it so the standalone loader picks it up, or route cron through the gateway). Until then `cron deliver=phone` won't work.
- **Cron `deliver=phone` live certification pending.** The plugin now registers its standalone sender and enumerates the canonical phone home through the upstream adapter channel-directory hook. Re-run the device scenario above on the deployed plugin to certify scheduled delivery, including the offline queue and opt-in gates.
- **FIX SHIPPED (2026-07-07) — installer + doctor guard against stale duplicate plugin copies; live-host verify pending.** Root cause of the 2026-06-29 round-trip failure: the gateway loader dedups discovered plugins by manifest `name`, so a second directory declaring `name: hermes-relay` (an old-installer backup copy, or a stray native install) could win the dedup and make the gateway load stale code — silently ignoring every later deploy. `plugin/doctor.py` now emits a `plugin-name-unique` warning when more than one directory under `~/.hermes/plugins/` declares the same plugin name (distinct real targets only — two links to the same target are deduped), and `install.sh` sweeps any such duplicate so only the canonical `hermes-relay` symlink survives. (Current `install.sh` already `rm -rf`s the old link rather than backing it up inside the plugins dir, so the original "back up outside the plugins dir" half is moot.) **Verify on the live host:** `hermes relay doctor` reports the `plugin-name-unique` check, and a reinstall leaves exactly one `hermes-relay` entry under `~/.hermes/plugins/`.
## Phone platform — usability roadmap (post device-verification, 2026-06-29)
@@ -886,9 +980,9 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
**Refinement (2026-06-29) — unified-session model: "Threads."** Going further on "unified surface": the agent conversation is **not a separate tab/segment** at all — it is a **source-tagged session inside the one Chat surface**, a **Thread** (`source=phone`). What makes a Thread special vs. a normal gateway chat are *session properties*, not a separate UI: (a) the agent can initiate, (b) relay `proactive` transport + relay-gated, (c) standing/named DM. **Scrollback = the gateway session store** (same read path Chat uses); **live receive = relay `proactive` push** (→ notification); **send = `proactive.reply`**. `ProactiveInboxStore` is demoted to a live-push cache + outbox (no parallel history). The Thread capability shows in the **best-path/capability UI** (relay tier, like terminal/bridge/voice) and as a clean **Threads** entry — thread-spool icon, NOT a phone glyph — pinned atop the session drawer when active; never a connection-wizard step. Degrades cleanly (no plugin → no `source=phone` sessions → Chat unchanged). **Supersedes the "separate Agent lane / 4th nav segment" sketch** and merges with the "source attribution in Chat" goal below. Keep the two "gateway" senses straight: *platform layer* (the Thread's `source`) ≠ *dashboard `/api/ws` transport* (how live bytes flow). Full re-cut: docs/decisions.md ADR 12.
- **Outbound buffering — ✅ relay-side DONE (2026-06-29).** `ProactiveChannel.push()` now queues agent→phone messages in a bounded deque (drop-oldest, 24 h TTL) when no phone is subscribed and returns `{queued: true}` (not 503); `_flush_outbound` delivers FIFO on the next subscribe (stale pruned). Inspect/cancel via `peek_outbound`/`cancel_outbound` + loopback `GET`/`DELETE /phone/outbound`. **UI surfacing of the queued state** (host-side, since the queue exists while the phone is OFFLINE): (a) ✅ **desktop CLI `relay queue` / `relay queue --clear` / `--cancel <id>` DONE (2026-06-29)** over the new endpoints (loopback-only — run on the relay host); a dashboard Relay-tab view is the optional GUI equivalent; (b) **remaining** — in the threaded agent surface, mark messages that arrived-while-away, and show the user's OWN pending replies (the Phase 3 reply queue) with a sending/Cancel affordance — that's where phone-side "queued + cancel" belongs.
- **Outbound buffering — ✅ relay-side + arrived-while-away receive UX DONE.** `ProactiveChannel.push()` queues agent→phone messages in a bounded deque (drop-oldest, 24 h TTL) when no phone is subscribed and returns `{queued: true}`. `_flush_outbound` delivers FIFO on the next subscribe (stale pruned), marks flushed messages, and sends one batch-complete count; Android labels those Thread bubbles “While away” and shows one accessible batch summary without changing unread behavior. Inspect/cancel remains available through `peek_outbound`/`cancel_outbound`, loopback `GET`/`DELETE /phone/outbound`, and desktop `relay queue`. **Remaining:** show the user's OWN pending replies (the Phase 3 reply queue) with an honest Queued/Cancel affordance; a dashboard queue view remains optional.
- **Threads surface (unified-session model — see ADR 12 + the Refinement above).** Build order, each shippable: **(1)** source tags in the session drawer (`source=phone` → clean **Threads** chip + thread-spool icon, NOT a phone glyph) — also delivers the "source attribution in Chat" goal; **(2)** open a Thread in Chat from its session-store history (reuse the existing message-history path); **(3)** route the live `proactive` push into the session view + notification + unread, demoting `ProactiveInboxStore` to cache/outbox; **(4)** reply from the Chat composer via `proactive.reply` + persist the user turn + local `Sending/Queued/Failed` status — **MVP**; **(5)** a **Threads capability row** in the best-path UI + a pinned **Threads** entry atop the drawer (thread-spool icon, shown only when relay-paired + opted-in) + retire `HermesInboxScreen`, re-point the notification deep-link + Settings "View messages"; **(6)** outbox/retry on reconnect; **(7)** relay `proactive.reply.ack` (honest Delivered) + `proactive.cancel`; **(8)** multi-thread `chat_id` (named/project Threads). **Verify gate before (1):** confirm the app's session-list/history path surfaces a `source=phone` session cleanly (upstream `session.list` returns all sources flat, so it should — but check whether the drawer currently filters it out). Honesty call: do NOT show "Delivered" until (7) lands (can't confirm it client-side before the ack).
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering** (an agent reply lands in the open Thread as an ASSISTANT bubble, suppressing the notification/inbox — `injectIntoThread`); **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`** (deleted; route + nav removed; notification tap + Settings "View messages" re-pointed to Chat; surface renamed "Hermes messages" → **"Threads"**); relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DEFERRED (reasons):** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **exact-Thread deep-link** from the notification (opens Chat today, not the specific thread — needs select-session-on-entry); **remove the now-orphaned `ProactiveInboxStore`** (viewer-less write-only log); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering**; **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`**; relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DONE (2026-08-14):** notification taps survive cold start and open the exact `chat_id`; agent-initiated outbound messages appear as connection-scoped provisional Threads backed by the bounded proactive store, then promote to the real `source=phone` session after the first reply. **DEFERRED:** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
- **User-created Threads (slice 8, Discord-style) — CODE-COMPLETE on `dev` (built + installed 2026-06-29; on-device behavior pending).** "+ New Thread" in the drawer's Threads view → name dialog → `ChatViewModel.startNewThread` mints a fresh `chat_id`; the first composer message opens it over `proactive.reply` (gateway auto-creates the `source=phone` session) → `switchToCreatedThread` polls + switches to the real session + applies the name. Existing-thread replies route by the `chat_id` parsed from the session id (`…:dm:<chat_id>`; opaque id → home fallback). **On-device verifies:** (1) a fresh-`chat_id` no-`reply_to` inbound creates a new `source=phone` session; (2) the phone session id carries the `…:dm:<chat_id>` form the client parses; (3) `renameSession` titles a phone session. **Remaining slice-8:** AGENT-initiated named Threads (the upstream `send_message` thread/chat_id param so the agent can open its own named Threads).
- **`chat_id` not exposed by `/api/sessions` (root cause of the 2026-06-29 on-device create-flow bugs — fixed client-side).** Confirmed on the host: a phone session's `id` is a timestamp (e.g. `20260629_204755_94f391d6`); the real `chat_id` lives in the `session_key` (`agent:main:phone:dm:<chat_id>`) and a `chat_id` column — but `/api/sessions` returns **neither `chat_id` nor `session_key`**, only `source` + the timestamp `id`. So the client could not map a session ↔ its `chat_id`, which broke create-thread switch/rename + reply routing + in-thread injection. **Client workaround shipped:** find a created thread by session-list **diff** (the new `source=phone` session), keep an in-memory `sessionId → chat_id` map (learned at creation + from incoming `phone.message`s) for reply routing, and inject by source (+ learned chat_id) rather than a parsed id. **Limitation:** for a thread the app didn't create *this* session (agent-created, another device, or after an app restart) `chat_id` is unknown until a message arrives while viewing it → its replies fall back to the home channel until then. **RESOLVED via the plugin (2026-06-29, per upstream-or-plugin policy):** the relay now exposes `GET /phone/threads` (`plugin/relay/session_store.py` reads the gateway store read-only → `[{session_id, chat_id, title}]`; `server.py` `handle_phone_threads`, bearer for the app / loopback for diag; 5 unit tests). The app (`RelayHttpClient.fetchPhoneThreads` → `ConnectionViewModel.phoneThreadChatIds` on every `auth.ok` → `ChatViewModel.seedThreadChatIds`, authoritative over the learned map) now routes replies correctly for **any** Thread — incl. ones it didn't create + after restart. Deployed + verified live. **Still-nice-to-have (lower priority): the upstream PR** to add `chat_id`/`session_key` to `/api/sessions` (the standard-path proper fix; the relay route then becomes redundant + the client prefers upstream when present).
- **Threads as named/project conversations (Discord-parity — folds into multi-thread #8).** A stable *named* `chat_id` per project = a persistent, agent-reachable project Thread (Discord named-thread parity for "persist a session for a project"). Enables: the agent **opening** a new named Thread for a background job/topic (a relay/gateway "open thread" affordance + a `send_message`-adjacent tool); cron/job updates landing in their own Thread; and replying to a Thread from any surface (desktop CLI / dashboard) since it is just a gateway session. Also evaluate per-Thread profile binding (a project Thread uses the "work" profile — ties to profile=contact).
@@ -908,7 +1002,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
The gateway-platform model is the *correct + sufficient architecture* (the phone is a registered platform peer, so anything that routes to a platform — `send_message`, cron `deliver=`, channel directory, background jobs — can reach the phone). These are the concrete gaps between "architecturally a peer" and "I never open Discord":
- **Guaranteed background delivery (the biggest gap; no push today).** Delivery is **live-WSS-only** + a 24 h relay buffer; there is **no FCM/UnifiedPush** wake-up. If the app process is dead AND not holding a socket, a message waits for the next reconnect, and the relay buffer is ephemeral (lost on relay restart). Discord/Telegram feel instant because they wake the device via push even when the app is dead. Decide a **push transport**: **UnifiedPush/ntfy** (recommended — self-hostable, no Google dependency, upstream *already* ships an `ntfy` platform, on-brand for self-hosted) vs **FCM** (simplest UX but adds Play Services + a push relay; clashes with self-hosted ethos — at most the `googlePlay` flavor) vs **persistent foreground keep-alive service** holding the relay WSS (zero new infra, like `GatewayKeepAliveService`, but battery cost + Doze-fragile). Likely: UnifiedPush primary + foreground-keepalive fallback.
- **Cron / background-job delivery is BROKEN** (already tracked above): `deliver=phone` standalone path → `Unknown platform: phone`. This is load-bearing for "receiver of crons/background jobs" — fix is required, not optional, for the replacement goal.
- **Cron / background-job delivery needs live certification.** The standalone sender and channel-directory enumeration are implemented; certify `deliver=phone` against a deployed Relay and paired device, including reconnect delivery from the bounded offline queue.
- **Agent-initiated multi-thread creation remains.** The app already renders N
`source=phone` sessions, user-created Threads vary `chat_id`, and replies route
by `chat_id` + `reply_to`. The missing parity is letting the agent open/name a
@@ -917,7 +1011,7 @@ The gateway-platform model is the *correct + sufficient architecture* (the phone
session store; the relay buffer is only the live/offline-delivery layer, not a
parallel history database.
- **Profile = contact mapping (new idea, fold in).** Multiple Hermes **profiles** (distinct agent personas/configs) could each be a distinct thread *source*/"contact" — DMing different agents. Maps cleanly onto the per-thread `chat_id` + source-attribution work; lets the app feel like a contact list of agents.
- **Per-thread notification controls + deep-link (Discord-parity affordances).** Per-thread notification channels, mute/DND/quiet-hours (Phase 3 partially), and a notification that **deep-links into the exact thread** (tap → land in that conversation) so dipping in/out while multitasking is frictionless.
- **Per-thread notification controls (Discord-parity affordances).** Exact-thread notification deep-linking is shipped. Remaining: per-thread notification channels and mute/DND/quiet-hours controls (Phase 3 partially).
- **Agent-initiated rich content.** Agent → phone thread with **images/cards** (relay media infra + `InboundAttachmentCard`/`HermesCardBubble` already exist on the chat side — reuse). Inbound (phone → agent) reply media stays deferred (text-first), but outbound rich content is low-cost parity.
- **In-thread "agent is working" indicator.** A typing/working state in the thread while the agent thinks/runs tools (Discord typing-dots parity) — the chat surface already has thinking indicators to reuse.
@@ -1042,12 +1136,14 @@ to tool state, safety prompts, or the current task.
playback-synchronized amplitude through `shouldMarkRealtimeOutputActive`,
matching the basic-TTS path. Confirm visually on-device with the 1.4.1 batch.
- **Voice command layer — initial 1.4.1 subset code-complete; live verify and
navigation residuals remain.** Exact final transcripts can stop speech,
- **Voice command layer — upstream stop phrases and phase-aware pause are
code-complete; live verify and navigation residuals remain.** Exact final transcripts can end the active voice chat,
explicitly cancel the active background task, pause/resume Continuous mode,
repeat a settled background answer, and start a new Standard chat. Bare `stop`
and `cancel`, partial transcripts, and command-like ordinary prompts stay on the
normal Hermes route. Realtime `new chat` remains gated on a clean websocket
repeat a settled background answer, and start a new Standard chat. Bare
`stop` is configurable and exact-only while voice chat is active; bare
`pause` remains phase-gated to Continuous mode. `cancel`, partial transcripts,
and command-like ordinary prompts stay on the normal Hermes route. Realtime
`new chat` remains gated on a clean websocket
session-rebind boundary; `open overlay` and `return to Hermes` remain future
navigation commands. Verify barge-in Stop, pause during a background run, local
command Chat cleanup, and Continuous rearm on device.
@@ -1082,11 +1178,34 @@ and whether the agent is waiting on the user.
experimental barge-in choice. Relay update is server-first; local Voice/barge-in
values share one DataStore transaction, with relay rollback on local failure.
- **Barge-in hardening** — keep barge-in experimental until echo/self-recording
- **Barge-in hardening — code complete; on-device matrix remains.** Full-turn
listener ownership, AEC/noise suppression, upstream-compatible RMS
calibration and thresholds, configurable playback grace, duck/cut behavior,
late-delta fencing, next-turn interruption context, and single-microphone
handoff are implemented. Phone testing still needs to cover speakerphone/headphones, quiet/noisy rooms, Standard/Realtime
generation and playback, stop/pause, and resume-after-interruption.
is solved. The target path is proper AEC, playback-ducking, and a rule that
- **Experimental wake word — on-device validation.** Verify first-enable model
installation and integrity failure recovery, all supported ABIs, Android
notification/microphone permission variants, background-start restrictions,
task recreation from the detection notification, acoustic false-positive and
false-negative rates, battery impact, stop action, and wake→voice→wake
microphone handoff. Voice settings now provide a bounded real-microphone/model
test with an input meter; use it to distinguish audio capture from KWS tuning
before testing the full activation flow. The first release remains fixed to
“Hey Hermes”; do not
expose profile-specific phrases until routing and acoustic behavior are
implemented and validated.
output audio can never become a user turn.
- **Android Digital Assistant — on-device validation.** On a physical device,
select and remove Hermes through the system Assistant role; verify gesture,
power-button, screen-off, credential-lock, and unlocked “Hey Hermes”
invocation; confirm the system session appears without overlay/full-screen
permissions; exercise compact, expanded, collapsed, and full-Voice handoff
states, background tap-through, rotation and insets, cancel/back, microphone
denial, network failure, process kill/recreation, and wake→voice→wake
resumption. Measure idle battery drain because third-party assistants do not
receive Google's dedicated low-power hotword hardware.
- **Audio quality guardrails** — normalize output volume across realtime and
@@ -1158,8 +1277,27 @@ When the answer becomes clearer, this section becomes either an ADR in `docs/dec
## Smaller deferred items
- **Certify the preferred CUA Driver backend (ADR 56).** The canonical-runtime
probe, bounded adapter, server-owned control-session envelope, per-session
grant state, local engine/status controls, telemetry-off process environment,
and Hermes snapshot-token primitives now exist. Before graduating the engine,
finish end-to-end enforcement of app/display/folder scopes and sensitive
pixel/accessibility denial or redaction, harden the grant-bridge ACL and nonce
lifecycle, and complete live Windows certification proving the physical cursor and
foreground app stay unchanged, stale or cross-window tokens fail, two remote
control sessions receive isolated animated cursors, and foreground escalation
never happens implicitly. Exercise revoke on grant expiry, disconnect,
re-pair, policy downgrade, emergency stop, Windows-session change, and daemon
shutdown. The explicit local CUA install/update surface now verifies upstream
manifest identity and installer SHA-256; add Windows publisher verification
when upstream signs the installer. Keep raw CUA tools, configuration,
recording, replay, and JavaScript outside the remote agent surface.
Remove the temporary Windows readiness/health split once
[trycua/cua#3103](https://github.com/trycua/cua/issues/3103) ships in the
supported CUA range; restore a mandatory health gate only if the upstream
probe is bounded and cannot leave UI Automation falsely busy.
- **MediaProjection consent flow** — wired in MainActivity (2026-04-12), needs end-to-end test on a real device
- **WorkManager upgrade for auto-disable timer** — currently a coroutine `Job + delay()` in `AutoDisableWorker.kt`; documented at top of file. Upgrade when androidx.work joins the classpath
- **WorkManager upgrade for timed screen-access expiry notification** — authority already fails closed from persisted absolute expiry after restart; the prompt notification is currently a coroutine `Job + delay()` coordinated by `BridgeSafetyManager` / `AutoDisableWorker`. Upgrade only if background notification timing becomes important after androidx.work joins the classpath.
- **Wave 3 voice-bridge multi-turn confirmation** — currently a 5s TTS countdown with cancel; conversational confirmation is the follow-up
- **LLM client wiring for `android_navigate`** — `_default_vision_model` is stubbed; production swap to a real Anthropic/OpenAI vision client
- **Real screenshots of each flavor's a11y permission dialog** — for `user-docs/guide/release-tracks.md`
@@ -1215,14 +1353,11 @@ Follow-ups:
profile/skill-aware empty-state chips and the ~40-flow recomposition hotspot at
the top of `ChatScreen`.
- **Pet hot-load + in-app add/remove (shipped 2026-06-20).** Pets now live-refresh: an `avatarsRefreshTick` keys the avatar `produceState` in `RelayApp`, and Appearance re-scans `pets/` on open and after in-app import/delete — no app restart. Appearance gained "Add a pet" (SAF `.zip` import via `PetImporter`, zip-slip/zip-bomb guarded + validated through `toAvatar`) and an "Installed pets" list with per-pet remove (`PetLoader.deletePet`, confirm dialog, Sphere fallback). Remaining:
- **Sphere-skin parity.** Skins are still process-scoped + `adb push` only — the live tick and the importer cover pets, not skins. Extend the tick to `loadUserSkins` and add a `.json` skin import if hot-loading/adding skins in-app is wanted.
- **Sphere-skin parity (shipped 2026-08-09).** Appearance now imports a bounded, validated declarative `.json` skin through the system picker, hot-refreshes the shared sphere registry, and selects the imported skin without an app restart.
- `**adb push` into `Android/data` hangs on Samsung scoped storage.** Confirmed: pushing a pet pack to `/sdcard/Android/data/<pkg>/files/pets/` stalls (no bytes written) although `adb shell ls` of the dir works. In-app `.zip` import is the supported path; `/sdcard/Download` pushes fine. Consider softening `docs/pet-spec.md` + user-docs to lead with in-app import over adb.
- **On-device import/delete smoke.** Import `/sdcard/Download/lucy.zip` via Add a pet → confirm Lucy appears, selects, and animates all states; then remove it and confirm the avatar falls back to the Sphere.
- **Pet state-change re-decode can flash one blank frame.** When the agent state switches clips, the first frame of the new clip may briefly be blank during decode; prewarm/hold-last-frame to smooth it. Root cause is the same as the next item: `PetAvatar.Render` re-decodes from disk on every clip change.
- **Pet frame-sequence memory: no cap or downsample (audit 2026-06-19).** `decodeClip` decodes every frame of the selected clip into `List<ImageBitmap>` at full resolution with no `inSampleSize` downscale to the display size and no frame-count/dimension ceiling — a long sequence of large PNGs can use a lot of RAM and a single very large image can OOM `BitmapFactory`. Add `inSampleSize` downsampling to the avatar's draw size and/or a documented hard cap. Spec now warns authors (prefer sprite sheets), but the renderer doesn't enforce it.
- **Pet decoded-clip cache (audit 2026-06-19).** `PetAvatar.Render` keys `produceState` on `clip`, so idle→thinking→speaking→idle within one turn re-runs `BitmapFactory.decodeFile` from disk each transition (repeated I/O + GC churn, and the blank-frame flash above). Add a small per-avatar `Map<SphereState, PetFrames>` decode cache.
- **Pet behavior model — richer state association (spec'd 2026-06-19, `docs/pet-spec.md` "Agent states &amp; pet behavior").** Shipped: the honesty clamp (declared reactivity ∩ `PET_RENDERER_CAPABILITIES`), the friendly `writing` alias, the `**working`/tool-use overlay** (pet-local sub-state from `toolCallBurst`; opt-in `working` clip drives both the swap and the Tools badge), the **one-shot reaction layer** (`greet`/`wake` on appear, `done`/`celebrate` on turn-finish — opt-in, play-once-then-revert, transition-derived; `ONE_SHOT_MAX_MS` backstop), and `**intensity` modulation** (opt-in `reactive.intensity` → live playback speedup ≤1.6× via `rememberUpdatedState`; un-clamps the Activity badge). Voice · Tools · Activity reactivity is now complete. Remaining:
- `**attention` one-shot (only deferred behavior).** A reaction on notification arrival — needs a host event the avatar doesn't yet receive (unlike `greet`/`done`, which ride state transitions). Would plumb a notification edge into `AvatarRenderState` (or a side channel) + a `PetOneShot.Attention`. Low priority: the avatar is rarely on-screen when notifications land (backgrounded) — see the value analysis; revisit only if the avatar becomes an always-on surface (persistent overlay / Quest port).
- **On-device verification (working + one-shots + intensity).** Best seen in clean mode (`AgentTextFlow` feeds `toolCallBurst` + `streamingIntensity` + state transitions). Confirm: a `working` clip swaps in during a tool run and releases ~600ms after (`WORKING_BURST_THRESHOLD` 0.5); a `done` clip plays once on reply completion then returns to idle; a `greet` clip plays once when the avatar appears; with `intensity:true`, a writing/working loop visibly quickens while streaming. Watch for the known clip re-decode flash on each swap (separate TODO — decoded-clip cache).
- **On-device verification (working + one-shots + intensity).** Best seen in clean mode (`AgentTextFlow` feeds `toolCallBurst` + `streamingIntensity` + state transitions). Confirm: a `working` clip swaps in during a tool run and releases ~600ms after (`WORKING_BURST_THRESHOLD` 0.5); a `done` clip plays once on reply completion then returns to idle; a `greet` clip plays once when the avatar appears; with `intensity:true`, a writing/working loop visibly quickens while streaming. Confirm each decoded clip swap holds the previous complete visual until the new state is ready.
- **Undecodable-but-present image appears valid (audit 2026-06-19).** A file that exists but isn't a decodable image passes the loader's `isFile` check, so the pet shows in the picker but renders blank. Documented as a caveat; consider a cheap header sniff at load time if false-valid pets become a support issue.
+47 -2
View File
@@ -7,6 +7,15 @@ plugins {
alias(libs.plugins.play.publisher)
}
val supportedHermesDevAbis = setOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
val hermesDevAbi = providers.gradleProperty("hermes.devAbi").orNull
hermesDevAbi?.let { requestedAbi ->
require(requestedAbi in supportedHermesDevAbis) {
"Unsupported hermes.devAbi '$requestedAbi'. Expected one of: " +
supportedHermesDevAbis.sorted().joinToString()
}
}
// Rename output artifacts to include the app version. AGP respects
// `archivesName` for both APK (assemble*) and AAB (bundle*) outputs, so
// this single line produces `hermes-relay-<version>-<flavor>-<buildType>`
@@ -43,6 +52,17 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
// Optional local-only fast path for device iteration. Native voice/VAD
// dependencies make the universal sideload APK very large, while a
// connected phone needs only its own ABI. Release and normal debug
// builds remain universal unless the developer explicitly supplies
// -Phermes.devAbi=<abi>.
hermesDevAbi?.let { requestedAbi ->
ndk {
abiFilters += requestedAbi
}
}
// Feature flags — DEV_MODE enables all experimental features in debug builds
buildConfigField("boolean", "DEV_MODE", "false")
}
@@ -125,6 +145,7 @@ android {
}
release {
isMinifyEnabled = true
isShrinkResources = true
ndk {
debugSymbolLevel = "SYMBOL_TABLE"
}
@@ -164,6 +185,21 @@ android {
}
}
packaging {
jniLibs {
// sherpa-onnx v1.13.4 and the Silero VAD both use ONNX Runtime.
// Keep them on sherpa's 1.27.0 baseline and package one shared core.
pickFirsts += "**/libonnxruntime.so"
// The Android app calls only sherpa's JNI facade. These native C/C++
// API facades are development surfaces and are not loaded by the app.
excludes += setOf(
"**/libsherpa-onnx-c-api.so",
"**/libsherpa-onnx-cxx-api.so",
)
}
}
// JVM unit tests run against the stubbed Android SDK jar, where every
// platform API method throws RuntimeException("... not mocked") by
// default. With returnDefaultValues = true, those stubs instead
@@ -262,6 +298,12 @@ dependencies {
// Bundled ONNX Silero model (~2.2 MB); pulled from JitPack.
implementation(libs.android.vad.silero)
// Experimental, opt-in local keyword spotting. Models are downloaded only
// after the user enables the feature; no model binary is bundled in APKs.
// Keep the shared runtime aligned with sherpa-onnx v1.13.4.
implementation(libs.onnxruntime.android)
implementation(libs.sherpa.onnx)
// Google Play In-App Update — googlePlay flavor ONLY (FLEXIBLE flow).
// Scoped via the `googlePlayImplementation` configuration so it never
// ships in the sideload APK, which updates via the GitHub-releases
@@ -277,10 +319,13 @@ dependencies {
// Coil 3 — async image loading for generated images in chat
implementation(libs.coil.compose)
implementation(libs.coil.gif)
implementation(libs.coil.network.okhttp)
implementation(libs.exifinterface)
// QR Code scanning (ML Kit + CameraX)
implementation(libs.mlkit.barcode)
implementation(libs.zxing.core)
implementation(libs.camera.core)
implementation(libs.camera.camera2)
implementation(libs.camera.lifecycle)
@@ -327,8 +372,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.70.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.70.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.72.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.72.0")
testImplementation(libs.compose.ui.test.junit4)
testImplementation(libs.compose.ui.test.manifest)
testImplementation("androidx.test.ext:junit:1.3.0")
@@ -0,0 +1,70 @@
package com.hermesandroid.relay.plugins.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.hermesandroid.relay.plugins.document.PluginDocumentState
import com.hermesandroid.relay.plugins.document.PluginElement
import com.hermesandroid.relay.plugins.document.PluginPage
import com.hermesandroid.relay.plugins.document.PluginText
import com.hermesandroid.relay.plugins.document.PluginValue
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class PluginDocumentRendererTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun pageRendersBindingsAndEmitsControlledStateChanges() {
var interaction: PluginInteraction? = null
val page = PluginPage(
id = "home",
title = PluginText.Binding("title", "Fallback"),
content = PluginElement.Group(
id = "root",
children = listOf(
PluginElement.Text(
id = "message",
text = PluginText.Binding("message"),
),
PluginElement.Toggle(
id = "enabled-toggle",
label = PluginText.Literal("Enabled"),
binding = "enabled",
),
),
),
)
val state = PluginDocumentState(
mapOf(
"title" to PluginValue.StringValue("Status plugin"),
"message" to PluginValue.StringValue("Everything is healthy"),
"enabled" to PluginValue.BooleanValue(false),
),
)
composeTestRule.setContent {
MaterialTheme {
PluginPageRenderer(page, state, { interaction = it })
}
}
composeTestRule.onNodeWithText("Status plugin").assertIsDisplayed()
composeTestRule.onNodeWithText("Everything is healthy").assertIsDisplayed()
composeTestRule.onNode(isToggleable()).performClick()
assertEquals(
PluginInteraction.ValueChanged(
elementId = "enabled-toggle",
key = "enabled",
value = PluginValue.BooleanValue(true),
),
interaction,
)
}
}
@@ -0,0 +1,147 @@
package com.hermesandroid.relay.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.MaterialTheme
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.assertDoesNotExist
import androidx.compose.ui.test.assertExists
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.test.platform.app.InstrumentationRegistry
import com.hermesandroid.relay.R
import com.hermesandroid.relay.ui.components.avatar.AgentAvatar
import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
import com.hermesandroid.relay.ui.components.avatar.AvatarSource
import com.hermesandroid.relay.ui.components.avatar.LocalAgentAvatar
import com.hermesandroid.relay.ui.components.avatar.LocalBackgroundVisualizationEnabled
import com.hermesandroid.relay.viewmodel.InteractionMode
import com.hermesandroid.relay.viewmodel.VoiceState
import com.hermesandroid.relay.viewmodel.VoiceUiState
import org.junit.Rule
import org.junit.Test
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 {
AmbientTestProviders(enabled = false) {
TestVoiceOverlay()
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertDoesNotExist()
composeTestRule.onNodeWithText(targetString(R.string.voice_overlay_tap_mic)).assertExists()
}
@Test
fun voiceMode_backgroundOn_rendersSphere() {
composeTestRule.setContent {
AmbientTestProviders(enabled = true) {
TestVoiceOverlay()
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertExists()
}
@Composable
private fun AmbientTestProviders(enabled: Boolean, content: @Composable () -> Unit) {
MaterialTheme {
CompositionLocalProvider(
LocalAgentAvatar provides TaggedAmbientRenderer,
LocalBackgroundVisualizationEnabled provides enabled,
content = content,
)
}
}
@Composable
private fun TestVoiceOverlay() {
VoiceModeOverlay(
uiState = VoiceUiState(
voiceMode = true,
state = VoiceState.Idle,
interactionMode = InteractionMode.TapToTalk,
),
onMicTap = {},
onMicRelease = {},
onInterrupt = {},
onDismiss = {},
onModeChange = {},
onClearError = {},
)
}
private fun targetString(id: Int): String =
InstrumentationRegistry.getInstrumentation().targetContext.getString(id)
private object TaggedAmbientRenderer : AgentAvatar {
override val id = "ambient-test"
override val label = "Ambient test"
override val description = "Test renderer"
override val source = AvatarSource.BUILT_IN
override val reactivity = SphereReactivity()
@Composable
override fun Render(state: AvatarRenderState, modifier: Modifier) {
Box(modifier = modifier.testTag(AMBIENT_RENDERER_TAG))
}
}
private companion object {
const val AMBIENT_RENDERER_TAG = "ambientVisualizationRenderer"
}
}
@@ -121,12 +121,15 @@ class OnboardingFlowTest {
}
@Test
fun connectPage_showsNearbyFirst() {
fun connectPage_recommendsGeneralSetupQr() {
setOnboardingContent()
navigateToPage(4)
composeTestRule
.onNodeWithText("Enter address instead")
.onNodeWithText("Scan Hermes setup QR")
.assertIsDisplayed()
composeTestRule
.onNodeWithText("Recommended")
.assertIsDisplayed()
}
@@ -135,7 +138,7 @@ class OnboardingFlowTest {
setOnboardingContent()
navigateToPage(4)
composeTestRule.onNodeWithText("Enter address instead").performClick()
composeTestRule.onNodeWithText("Server or VPS").performClick()
composeTestRule.waitForIdle()
composeTestRule
@@ -148,7 +151,7 @@ class OnboardingFlowTest {
setOnboardingContent()
navigateToPage(4)
composeTestRule.onNodeWithText("Enter address instead").performClick()
composeTestRule.onNodeWithText("Server or VPS").performClick()
composeTestRule.waitForIdle()
composeTestRule
@@ -156,12 +159,28 @@ class OnboardingFlowTest {
.assertIsDisplayed()
}
@Test
fun cloudSetup_requestsTheHostedDashboardAddress() {
setOnboardingContent()
navigateToPage(4)
composeTestRule.onNodeWithText("Nous-hosted Hermes").performClick()
composeTestRule.waitForIdle()
composeTestRule
.onNodeWithText("Connect to Nous-hosted Hermes")
.assertIsDisplayed()
composeTestRule
.onNodeWithText("Use the complete HTTPS address shown for your hosted agent.")
.assertIsDisplayed()
}
@Test
fun connectPage_keepsPairingOptional() {
setOnboardingContent()
navigateToPage(4)
composeTestRule.onNodeWithText("Other connection methods").performClick()
composeTestRule.onNodeWithText("Advanced").performClick()
composeTestRule.waitForIdle()
composeTestRule
Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 180 KiB

@@ -1 +1,3 @@
Choose compact Voice Focus or the complete Conversation layout. Standard Voice reliably speaks completed replies, Realtime background work no longer blocks voice controls, and streamed answers render Markdown while staying anchored at their completed end.
v1.11.0 - More reliable chat
Keep stored-session failures visible with route-aware retry details. Use Return for multiline prompts across more software keyboards. Preserve Stopped status when cancelling answer recovery. Reduce idle redraws and release capture and audio resources sooner.
@@ -1 +1,3 @@
可选择精简的语音专注视图或完整的对话视图。标准语音现在会可靠朗读已完成的回复,实时后台任务不再阻塞语音控制,流式回复会渲染 Markdown 并停留在完成位置。
v1.11.0 - 更可靠的聊天体验
已存会话恢复失败时会保留错误与重试信息。更多输入法可用回车键换行。取消回复恢复时会保留“已停止”状态。空闲动画更少,并更及时地释放屏幕捕获和音频资源。
+93 -2
View File
@@ -20,6 +20,7 @@
for the device-control bridge service; the merger dedups.) -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
@@ -47,6 +48,32 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- User-mediated text handoff. The app opens a fresh Chat draft
and fills the composer; it never sends from an external intent. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
<!-- The loopback native-PKCE result page uses this fixed, tokenless
link only to bring the installed flavor back to the foreground.
MainActivity intentionally does not interpret the URI as an auth
callback or navigation command. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="${applicationId}"
android:host="return" />
</intent-filter>
<!-- Some Android OEM assistant pickers enumerate ACTION_ASSIST
activities in addition to VoiceInteractionService providers. -->
<intent-filter>
<action android:name="android.intent.action.ASSIST" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.VOICE" />
</intent-filter>
</activity>
<!-- AppCompat persists in-app language choices on Android 12 and lower.
@@ -93,8 +120,8 @@
<!-- Protects user-started active turns automatically; the optional
"Persistent connection" setting extends the same foreground
protection to idle/background connectivity (and relay-paired
device features). In main so BOTH flavors ship it. specialUse
needs a Play Console foreground-service declaration at submission. -->
device features). In main so BOTH flavors ship it. Every Play
foreground-service type needs its matching App content declaration. -->
<service
android:name=".network.upstream.GatewayKeepAliveService"
android:exported="false"
@@ -104,6 +131,70 @@
android:value="Keeps user-started Hermes turns connected until they finish or need input, and optionally keeps idle connections responsive when the user enables Persistent connection." />
</service>
<!-- Experimental, explicitly user-started on-device wake-word listener.
Audio remains local and the service is never boot/restart started.
The Play build's microphone type needs an App content declaration. -->
<service
android:name=".wake.WakeWordForegroundService"
android:exported="false"
android:foregroundServiceType="microphone"
android:stopWithTask="false" />
<!-- User-started protection for voice capture from the system overlay.
The service does not own AudioRecord; it keeps foreground-only
microphone app-ops available while Hermes is behind another app.
Include this use case in the Play microphone declaration. -->
<service
android:name=".voice.VoiceOverlayForegroundService"
android:exported="false"
android:foregroundServiceType="microphone"
android:stopWithTask="false" />
<!-- Explicitly opt-in Android Digital Assistant integration. Android
binds this only after the user selects Hermes for ROLE_ASSISTANT. -->
<service
android:name=".assistant.HermesVoiceInteractionService"
android:exported="true"
android:label="@string/assistant_service_label"
android:permission="android.permission.BIND_VOICE_INTERACTION">
<intent-filter>
<action android:name="android.service.voice.VoiceInteractionService" />
</intent-filter>
<meta-data
android:name="android.voice_interaction"
android:resource="@xml/voice_interaction_service" />
</service>
<!-- Heavy assistant UI is isolated from the always-running interaction
service, matching the platform lifecycle guidance. -->
<service
android:name=".assistant.HermesVoiceInteractionSessionService"
android:exported="true"
android:permission="android.permission.BIND_VOICE_INTERACTION"
android:process=":assistant_session" />
<!-- Required companion component for VoiceInteractionService metadata.
Hermes session transcription remains owned by the existing voice
pipeline; this service does not open a second microphone stream. -->
<service
android:name=".assistant.HermesRecognitionService"
android:exported="true"
android:permission="android.permission.BIND_VOICE_INTERACTION">
<intent-filter>
<action android:name="android.speech.RecognitionService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<receiver
android:name=".assistant.AssistantSessionStateReceiver"
android:exported="false"
android:process=":assistant_session" />
<receiver
android:name=".assistant.AssistantSessionLifecycleReceiver"
android:exported="false" />
</application>
</manifest>
+321
View File
@@ -1,5 +1,326 @@
{
"versions": [
{
"version": "1.11.0",
"title": "Access with clear boundaries",
"date": "2026-08-20",
"sections": [
{
"header": "Choose what Bridge can do",
"bullets": [
"Use read-only, read-and-confirm, or custom capability presets for the active connection in sideload builds.",
"Allow screen inspection and control for a bounded period or explicitly keep access unlimited."
]
},
{
"header": "Recover without losing context",
"bullets": [
"Keep stored-session failures visible with route-aware details and clear retry or dismiss actions.",
"Insert newlines across more software keyboards and retain Stopped status when answer recovery is cancelled."
]
},
{
"header": "Use less power while idle",
"bullets": [
"Pause invisible Sphere, waveform, and drawer animation loops when no motion is needed.",
"Attach capture surfaces only for requested frames and release audio or wake-lock resources at their lifecycle boundaries."
]
}
]
},
{
"version": "1.10.0",
"title": "Chat that stays put",
"date": "2026-08-18",
"sections": [
{
"header": "Watch replies take shape",
"bullets": [
"Render paragraphs, lists, links, fenced code, and tables incrementally without replacing the message at completion.",
"Keep bottom-follow smooth while intentional scrollback remains exactly where you left it."
]
},
{
"header": "Pick up where you left off",
"bullets": [
"Resume the visible Hermes session automatically after returning from another app.",
"Restore composer text, quote or edit context, and pending attachments in the correct conversation after an app restart."
]
},
{
"header": "Review before sending",
"bullets": [
"Turn large pastes into compact text attachments while preserving compatible fallback delivery.",
"Use Return on the software keyboard while the dedicated composer button remains the Send action."
]
}
]
},
{
"version": "1.9.1",
"title": "Profile identity that sticks",
"date": "2026-08-16",
"sections": [
{
"header": "Identity follows the right scope",
"bullets": [
"Change shared avatars from Android with automatic orientation, resizing, and safe conversion to the Hermes profile-asset contract.",
"Select upstream animated pets that follow the Hermes profile while phone-only animated icons, local avatar overrides, and Sphere skins stay local."
]
},
{
"header": "Profile setup stays explicit",
"bullets": [
"Create profiles with clear shared, copied, or isolated authentication choices and see partial setup outcomes.",
"Named-profile sessions and profile drafts fail closed when Hermes cannot confirm their owner."
]
},
{
"header": "Safer Gateway operations",
"bullets": [
"Attachments, rewinds, recovery, model-consent changes, and hosted sign-in now follow stricter upstream contracts.",
"Finite schedules, bounded reset evidence, and host resource warnings make consequential actions easier to review."
]
}
]
},
{
"version": "1.9.0",
"title": "Better sessions, reactions, and voice",
"date": "2026-08-14",
"sections": [
{
"header": "Sessions keep their identity",
"bullets": [
"Browse one profile or all profiles, customize sorting and filters, and optionally group sessions by project, recency, status, or profile.",
"Cross-profile sessions hydrate, resume, and send with their owning agent without changing the global profile selection; New Chat in All Profiles uses the default profile."
]
},
{
"header": "Conversation controls stay attached",
"bullets": [
"Reactions pin to durable rows on both user and assistant messages.",
"Vanilla Hermes voice stays on the authenticated Gateway instead of requiring the optional API fallback."
]
},
{
"header": "Context without clutter",
"bullets": [
"Session rows show profile, project, branch, and pull-request context when Hermes supplies it, while the default view remains ungrouped.",
"The session drawer restores secondary actions in All Profiles and closes when you tap outside it."
]
}
]
},
{
"version": "1.8.1",
"title": "Complete, reliable transcripts",
"date": "2026-08-09",
"sections": [
{
"header": "Keep long sessions complete",
"bullets": [
"Android pages explicitly through complete API-server and profile-scoped Dashboard history instead of silently stopping at Hermes' latest-500 default.",
"Sharing, retry, edit, and recovery retain stable transcript anchors while bounded safety limits keep unusually large reads controlled."
]
},
{
"header": "Follow Gateway truth",
"bullets": [
"Authoritative submit rejections preserve the server's message without an unintended SSE fallback.",
"Gateway event envelopes and edit-and-regenerate truncation confirmation now follow current upstream contracts."
]
}
]
},
{
"version": "1.8.0",
"title": "Conversations with more context",
"date": "2026-08-09",
"sections": [
{
"header": "Keep the whole turn together",
"bullets": [
"Quote, edit, search, and attach or reorder files without losing the active connection, profile, or session.",
"Share text from another Android app into a fresh Chat draft for review before sending."
]
},
{
"header": "See the work without the clutter",
"bullets": [
"Live thinking settles into a compact Thought disclosure, while routine tool activity groups into concise runs.",
"Approvals, failures, generated media, file changes, risks, and delegated work remain clearly distinct."
]
},
{
"header": "Switch agents, not identities",
"bullets": [
"The Profile Shelf switches agents from Chat while restoring each profile's last session.",
"Agent Passport model and reasoning controls remain scoped to the active session instead of rewriting server defaults."
]
},
{
"header": "Make it yours",
"bullets": [
"Preview theme accents and shapes, Sphere skins, and pets in one Appearance workflow.",
"Message speech controls, pet touch targets, scrolling terrain, image rotation, and edge-to-edge settings layout are more reliable."
]
}
]
},
{
"version": "1.7.1",
"title": "Safer, steadier conversations",
"date": "2026-08-08",
"sections": [
{
"header": "Chat stays with you",
"bullets": [
"Growing streamed replies stay visible while you are at the bottom, and intentional scrollback remains undisturbed.",
"Completed replies render Markdown immediately while live tool details remain expandable."
]
},
{
"header": "Sessions keep their ownership",
"bullets": [
"Queued follow-ups retain their originating connection, profile, session, route, attachments, and voice context.",
"Session pins and archives persist across restarts, and duplicate model rows are reconciled before rendering."
]
},
{
"header": "Safer controls and setup",
"bullets": [
"Approval cards require an explicit labeled decision, and Agent Passport safety controls are easier to read and dismiss.",
"Hosted Hermes setup completes through the official Dashboard system-browser sign-in flow."
]
}
]
},
{
"version": "1.7.0",
"title": "Smarter controls, steadier sessions",
"date": "2026-08-06",
"sections": [
{
"header": "Model controls fit the model",
"bullets": [
"Reasoning effort choices follow the selected provider and model when an exact supported list is available.",
"Unmodified Hermes and setups without the optional Relay capability overlay keep a fail-soft standard choice list."
]
},
{
"header": "Active chats stay easy to follow",
"bullets": [
"The searchable session drawer shows which conversations are working or waiting for input.",
"Restored and completed chats remain bottom-pinned through late layout changes without overriding intentional scrollback.",
"Chat and Voice keep stable rows through recovery, and Focus Voice controls receive taps normally."
]
},
{
"header": "Support stays private and useful",
"bullets": [
"Review locally redacted support information before choosing to copy, share, or open GitHub; nothing uploads automatically.",
"Connection diagnostics identify the failed operation and offer targeted guidance without exposing hosts or credentials."
]
}
]
},
{
"version": "1.6.1",
"title": "Clearer recovery, steadier chat",
"date": "2026-08-03",
"sections": [
{
"header": "Relay stays optional",
"bullets": [
"Relay-only surfaces now use consistent Optional, Ready, Reconnecting, Unavailable, and Needs re-pair states without nagging from background session refreshes.",
"Foreground recovery retries ordinary reconnect backoff immediately and explains whether Relay credentials are merely stored or actually need re-pairing."
]
},
{
"header": "Sessions and chat stay stable",
"bullets": [
"The session drawer restores its 200-row window through upstream-compatible 100-row pages.",
"Selecting streamed text stays stable when a completed response changes to rendered Markdown."
]
},
{
"header": "Voice controls stay reachable",
"bullets": [
"Manual recording waits for the previous microphone owner to release it and gives a useful recovery message if capture cannot start.",
"New-chat coaching yields while Voice owns the composer so it cannot cover the expanding Voice drawer."
]
}
]
},
{
"version": "1.6.0",
"title": "Pets, plugins, and voice",
"date": "2026-08-02",
"sections": [
{
"header": "A companion with personality",
"bullets": [
"Browse and install Petdex companions, or import your own pet without replacing the agent avatar or background Sphere.",
"Drag a pet anywhere or let it roam across measured chat bubbles, settings cards, controls, and other safe UI ledges."
]
},
{
"header": "Native plugin pages",
"bullets": [
"Installed Hermes plugins can contribute host-rendered native pages without loading executable plugin code on the phone.",
"Scoped writes stay off until granted, while Relay 1.5.0 adds approval-gated agent-created page previews."
]
},
{
"header": "Hermes as your assistant",
"bullets": [
"Optionally select Hermes as Android’s Digital Assistant and use a local “Hey Hermes” listener for background or locked-screen sessions.",
"Compact assistant and floating Voice controls expand for detail and continue the same turn when full Voice opens."
]
},
{
"header": "More reliable everywhere",
"bullets": [
"Voice output recovery, long recordings, route failover, streamed chat identity, and pet terrain recovery are more resilient.",
"Android now includes a complete AI-assisted Russian catalog refreshed for the 1.6 feature set."
]
}
]
},
{
"version": "1.5.3",
"title": "Voice stays open",
"date": "2026-07-31",
"sections": [
{
"header": "Stable voice transcripts",
"bullets": [
"Voice Focus keeps stable transcript rows while live messages reconcile with persisted chat history, preventing duplicate-key crashes that could close the app."
]
}
]
},
{
"version": "1.5.2",
"title": "Sign in without detours",
"date": "2026-07-28",
"sections": [
{
"header": "Provider-compatible sign-in",
"bullets": [
"Self-hosted OIDC returns through the dashboard callback, while Nous Portal opens securely in the system browser.",
"Private-LAN and Tailscale dashboard routes preserve the configured HTTPS callback and keep credentials scoped to the active connection."
]
},
{
"header": "Stable conversation updates",
"bullets": [
"Replayed upstream chat events are coalesced before rendering so duplicate message identifiers do not destabilize the conversation list."
]
}
]
},
{
"version": "1.5.1",
"title": "Voice and chat stay in place",
+7 -5
View File
@@ -1,6 +1,8 @@
v1.5.1 - Voice and chat stay in place
v1.11.0 - Access with clear boundaries
* Choose a compact Voice Focus view or the complete Conversation renderer.
* Hear Standard Voice replies reliably after generation completes.
* Keep Realtime background work active without blocking voice controls.
* Read formatted streamed answers without jumping back to their beginning.
* Choose explicit Bridge capability presets in sideload builds.
* Allow screen inspection and control for a set time or explicitly keep access unlimited.
* Keep stored-session failures visible with route-aware retry details.
* Use Return for multiline prompts across more software keyboards.
* Preserve Stopped status when cancelling answer recovery.
* Reduce idle redraws and release capture and audio resources sooner.
@@ -1,19 +1,37 @@
package com.hermesandroid.relay
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.gif.AnimatedImageDecoder
import coil3.gif.GifDecoder
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.crossfade
import com.hermesandroid.relay.bridge.UnattendedAccessManager
import com.hermesandroid.relay.data.AppAnalytics
import com.hermesandroid.relay.power.WakeLockManager
import com.hermesandroid.relay.runtime.HermesProcessRuntime
import com.hermesandroid.relay.util.AppForegroundTracker
import com.hermesandroid.relay.util.CrashReporter
class HermesRelayApp : Application(), SingletonImageLoader.Factory {
/**
* Shared chat/voice runtime for the main application process. It is lazy so
* the always-available assistant session UI process stays lightweight and
* cannot accidentally become a second microphone/session owner.
*/
val runtime: HermesProcessRuntime by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
check(isMainApplicationProcess()) {
"HermesProcessRuntime may only be created in the main application process"
}
HermesProcessRuntime(this)
}
/**
* Coil's singleton image loader for the whole app. Registering the OkHttp
* network fetcher EXPLICITLY guarantees `http(s)` image URLs (e.g. a
@@ -22,7 +40,14 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
*/
override fun newImageLoader(context: PlatformContext): ImageLoader =
ImageLoader.Builder(context)
.components { add(OkHttpNetworkFetcherFactory()) }
.components {
add(OkHttpNetworkFetcherFactory())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
add(AnimatedImageDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
}
.crossfade(true)
.build()
@@ -51,6 +76,19 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
AppForegroundTracker.initialize()
}
private fun isMainApplicationProcess(): Boolean {
val processName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getProcessName()
} else {
val pid = android.os.Process.myPid()
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.runningAppProcesses
?.firstOrNull { process -> process.pid == pid }
?.processName
}
return processName == packageName
}
companion object {
lateinit var instance: HermesRelayApp
private set
@@ -5,16 +5,18 @@ import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.Build
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.animation.doOnEnd
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.hermesandroid.relay.accessibility.ScreenCaptureRequester
import com.hermesandroid.relay.bridge.BridgeForegroundService
import com.hermesandroid.relay.bridge.UnattendedAccessManager
@@ -23,11 +25,16 @@ import com.hermesandroid.relay.notifications.TurnCompleteNotifier
import com.hermesandroid.relay.notifications.InteractionRequestNotifier
import com.hermesandroid.relay.ui.RelayApp
import com.hermesandroid.relay.util.NavRouteRequest
import com.hermesandroid.relay.util.SharedTextRequest
import com.hermesandroid.relay.util.extractSharedText
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collect
class MainActivity : AppCompatActivity() {
private val connectionViewModel: ConnectionViewModel by viewModels()
private val connectionViewModel: ConnectionViewModel
get() = (applicationContext as HermesRelayApp).runtime.connectionViewModel
// === PHASE3-bridge-ui-followup: MediaProjection consent flow ===
// ActivityResultLauncher for the system screen-capture consent dialog.
@@ -67,6 +74,8 @@ class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
com.hermesandroid.relay.assistant.AssistantSessionProtocol
.prepareAssistActivation(intent)
// Hold splash until DataStore is loaded and onboarding status is known
splashScreen.setKeepOnScreenCondition {
@@ -88,6 +97,12 @@ class MainActivity : AppCompatActivity() {
}
super.onCreate(savedInstanceState)
configureAssistantWindow(intent)
lifecycleScope.launch {
com.hermesandroid.relay.assistant.AssistantAppSessionState.active.collect { active ->
if (!active) clearAssistantWindow()
}
}
enableEdgeToEdge()
// === PHASE3-bridge-ui-followup: install MediaProjection requester ===
@@ -114,6 +129,15 @@ class MainActivity : AppCompatActivity() {
// in RelayApp's NavRouteRequest collector — we just pump the request
// into the SharedFlow here.
consumeNavRouteIntent(intent)
consumeSharedTextIntent(intent)
val consumedAssistantActivation =
com.hermesandroid.relay.assistant.AssistantSessionProtocol.consumeActivation(
this,
intent,
)
if (!consumedAssistantActivation) {
com.hermesandroid.relay.assistant.AssistantSessionProtocol.restoreActivation(this)
}
// === END PHASE3-safety-rails-followup ===
setContent {
RelayApp()
@@ -122,6 +146,9 @@ class MainActivity : AppCompatActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
com.hermesandroid.relay.assistant.AssistantSessionProtocol
.prepareAssistActivation(intent)
configureAssistantWindow(intent)
// === PHASE3-safety-rails-followup: deep-link nav route on re-launch ===
// Same as onCreate but for the singleTask / FLAG_ACTIVITY_CLEAR_TOP
// path: when the app is already running and the foreground service's
@@ -129,6 +156,8 @@ class MainActivity : AppCompatActivity() {
// instead of onCreate. RelayApp's collector handles both cases.
setIntent(intent)
consumeNavRouteIntent(intent)
consumeSharedTextIntent(intent)
com.hermesandroid.relay.assistant.AssistantSessionProtocol.consumeActivation(this, intent)
// === END PHASE3-safety-rails-followup ===
}
@@ -138,6 +167,49 @@ class MainActivity : AppCompatActivity() {
NavRouteRequest.tryRequest(route)
}
private fun consumeSharedTextIntent(intent: Intent?) {
val sharedText = extractSharedText(
action = intent?.action,
mimeType = intent?.type,
text = intent?.getCharSequenceExtra(Intent.EXTRA_TEXT),
) ?: return
SharedTextRequest.tryRequest(sharedText)
}
private fun configureAssistantWindow(intent: Intent?) {
if (
intent?.getBooleanExtra(
com.hermesandroid.relay.assistant.AssistantSessionProtocol.EXTRA_ASSISTANT_SESSION,
false,
) == true ||
com.hermesandroid.relay.assistant.AssistantSessionPersistence.isActive(this)
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
@Suppress("DEPRECATION")
window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
}
}
private fun clearAssistantWindow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(false)
setTurnScreenOn(false)
} else {
@Suppress("DEPRECATION")
window.clearFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
}
override fun onResume() {
super.onResume()
// Returning to the app clears the one-slot "Hermes finished
@@ -21,6 +21,8 @@ import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.add
import kotlinx.serialization.json.put
/**
@@ -226,6 +228,7 @@ class BridgeStatusReporter(
val destructiveVerbsCount = safetySnapshot?.destructiveVerbs?.size ?: 0
val autoDisableMinutes = safetySnapshot?.autoDisableMinutes ?: 0
val autoDisableAtMs = safetyManager?.autoDisableAtMs?.value
val capabilityPolicy = safetyManager?.activeCapabilityPolicy?.value
val deviceName = Build.MODEL ?: "unknown"
@@ -281,6 +284,33 @@ class BridgeStatusReporter(
put("auto_disable_at_ms", autoDisableAtMs)
}
})
put("capabilities", buildJsonObject {
put("schema_version", capabilityPolicy?.schemaVersion ?: 1)
put("permanent", buildJsonArray {
capabilityPolicy?.permanentGrants
?.sortedBy { it.wireId }
?.forEach { add(it.wireId) }
})
put("timed", buildJsonObject {
capabilityPolicy?.timedExpiriesMs
?.filterValues {
it != com.hermesandroid.relay.bridge.BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
}
?.toSortedMap(compareBy { it.wireId })
?.forEach { (capability, expiry) ->
put(capability.wireId, expiry)
}
})
put("unlimited", buildJsonArray {
capabilityPolicy?.timedExpiriesMs
?.filterValues {
it == com.hermesandroid.relay.bridge.BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
}
?.keys
?.sortedBy { it.wireId }
?.forEach { add(it.wireId) }
})
})
// v0.4.1: unattended-access state so the agent can decide
// upfront whether commands will reach apps with the screen
@@ -41,7 +41,7 @@ import kotlinx.coroutines.launch
*
* The Android system toggle in `Settings → Accessibility → Hermes-Relay` is
* the hard switch — if it's off we never receive events. On top of that the
* user can flip a soft master in Settings (`bridge_master_enabled`); when
* user can flip a soft master in Settings (`bridge_master_enabled_v2`); when
* that's false we still run (Android requires it to stay connected) but we
* refuse to execute commands. [isMasterEnabled] is a StateFlow the UI
* observes and the command handler checks before dispatching actions.
@@ -61,7 +61,9 @@ class HermesAccessibilityService : AccessibilityService() {
private const val TAG = "HermesA11yService"
/** Master-enable DataStore key — read + toggled from Settings UI. */
val KEY_BRIDGE_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
val KEY_BRIDGE_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled_v2")
private val KEY_LEGACY_BRIDGE_MASTER_ENABLED =
booleanPreferencesKey("bridge_master_enabled")
/**
* Static reference to the live service instance, or null if the
@@ -92,6 +94,7 @@ class HermesAccessibilityService : AccessibilityService() {
suspend fun setMasterEnabled(context: Context, enabled: Boolean) {
context.applicationContext.relayDataStore.edit { prefs ->
prefs[KEY_BRIDGE_MASTER_ENABLED] = enabled
prefs[KEY_LEGACY_BRIDGE_MASTER_ENABLED] = false
}
}
}
@@ -152,12 +152,14 @@ class ScreenCapture(
// 13 and below but breaks the second /screenshot request on 14+.
//
// Fix: keep the VirtualDisplay + ImageReader + HandlerThread alive
// across captures, keyed by the MediaProjection instance. Rebuild only
// when the projection reference changes (fresh consent grant) or the
// dimensions change (orientation flip). The ImageReader's
// setOnImageAvailableListener drains the buffer continuously; each
// captureAndUpload() installs a one-shot [pendingCapture] callback
// that fires on the next frame.
// across captures, keyed by the MediaProjection instance. The reader
// surface is attached only while a request is waiting, then detached so
// SurfaceFlinger is not continuously mirroring into a drain-and-drop loop.
// Rebuild only when the projection reference changes (fresh consent
// grant). Orientation/size changes resize the existing VirtualDisplay and
// replace its detached ImageReader, preserving Android 14's single-create
// contract. Each captureAndUpload() installs a one-shot [pendingCapture]
// callback that fires on the next attached frame.
//
// Thread model:
// - `captureMutex` serializes concurrent captureAndUpload() calls
@@ -273,6 +275,7 @@ class ScreenCapture(
*/
fun releaseCache() {
synchronized(cacheLock) {
runCatching { cachedDisplay?.setSurface(null) }
runCatching { cachedDisplay?.release() }
runCatching { cachedReader?.close() }
runCatching { cachedThread?.quitSafely() }
@@ -326,6 +329,7 @@ class ScreenCapture(
}
return try {
attachCaptureSurface()
val timeoutMs = captureTimeoutMs()
kotlinx.coroutines.withTimeout(timeoutMs) { deferred.await() }
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
@@ -336,6 +340,24 @@ class ScreenCapture(
} catch (t: Throwable) {
pendingCaptureRef.compareAndSet(deferred, null)
throw t
} finally {
detachCaptureSurface()
}
}
private fun attachCaptureSurface() {
synchronized(cacheLock) {
val display = cachedDisplay ?: throw IOException("capture display unavailable")
val surface = cachedReader?.surface ?: throw IOException("capture surface unavailable")
display.setSurface(surface)
Log.d(TAG, "screen capture surface attached for pending frame")
}
}
private fun detachCaptureSurface() {
synchronized(cacheLock) {
runCatching { cachedDisplay?.setSurface(null) }
.onFailure { Log.v(TAG, "screen capture surface detach failed: ${it.message}") }
}
}
@@ -350,11 +372,12 @@ class ScreenCapture(
/**
* Build (or reuse) the cached VirtualDisplay + ImageReader + HandlerThread
* for this projection. Rebuilds when:
* for this projection. Rebuilds the display when:
*
* - The projection reference has changed (new consent grant landed)
* - The captured dimensions don't match the current display (orientation
* flipped, foldable opened/closed, display switched)
*
* Geometry changes resize that existing display and replace its detached
* consumer surface, as required for Android 14's one-display-per-token rule.
*
* Must be called while [captureMutex] is held so the cached fields
* aren't racing another capture.
@@ -368,52 +391,41 @@ class ScreenCapture(
synchronized(cacheLock) {
val projectionChanged = cachedProjection !== projection
val dimensionsChanged = width != cachedWidth || height != cachedHeight
if (!projectionChanged && !dimensionsChanged && cachedDisplay != null && cachedReader != null) {
val densityChanged = densityDpi != cachedDensity
if (!projectionChanged && !dimensionsChanged && !densityChanged &&
cachedDisplay != null && cachedReader != null
) {
return
}
// Android 14 permits only one createVirtualDisplay() call per
// MediaProjection. Resize the existing display and replace only
// its detached consumer surface when the device geometry changes.
if (!projectionChanged && cachedDisplay != null && cachedThread != null) {
val display = cachedDisplay ?: return
val thread = cachedThread ?: return
val handler = cachedHandler ?: Handler(thread.looper)
display.setSurface(null)
runCatching { cachedReader?.close() }
display.resize(width, height, densityDpi)
cachedReader = createImageReader(width, height, handler)
cachedHandler = handler
cachedWidth = width
cachedHeight = height
cachedDensity = densityDpi
Log.i(TAG, "screen capture pipeline resized ${width}x$height dpi=$densityDpi")
return
}
// Tear down any stale cache before building fresh.
runCatching { cachedDisplay?.setSurface(null) }
runCatching { cachedDisplay?.release() }
runCatching { cachedReader?.close() }
runCatching { cachedThread?.quitSafely() }
val thread = HandlerThread("HermesScreenCapture").apply { start() }
val handler = Handler(thread.looper)
val reader = ImageReader.newInstance(
width, height, PixelFormat.RGBA_8888, MAX_IMAGES
)
// Persistent listener — fires on every frame the VirtualDisplay
// produces. If there's a pending capture request, we encode
// the frame and complete it; otherwise we just drain the image
// so the ImageReader buffer stays clear.
reader.setOnImageAvailableListener({ r ->
val waiter = pendingCaptureRef.get()
if (waiter == null || !waiter.isActive) {
// Drain-and-drop — nobody's asking for a screenshot
// right now but frames are still arriving.
runCatching { r.acquireLatestImage() }.getOrNull()?.close()
return@setOnImageAvailableListener
}
var image: Image? = null
try {
image = r.acquireLatestImage()
?: return@setOnImageAvailableListener
val png = imageToPngBytes(image, width, height)
// Only complete the EXACT deferred we latched onto,
// so a stale listener firing after supersession doesn't
// resolve a new request.
if (pendingCaptureRef.compareAndSet(waiter, null)) {
waiter.complete(png)
}
} catch (t: Throwable) {
if (pendingCaptureRef.compareAndSet(waiter, null)) {
waiter.completeExceptionally(t)
}
} finally {
runCatching { image?.close() }
}
}, handler)
val reader = createImageReader(width, height, handler)
val display = try {
projection.createVirtualDisplay(
@@ -422,7 +434,7 @@ class ScreenCapture(
height,
densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
reader.surface,
null,
null,
handler,
)
@@ -461,6 +473,38 @@ class ScreenCapture(
}
}
private fun createImageReader(width: Int, height: Int, handler: Handler): ImageReader {
val reader = ImageReader.newInstance(
width, height, PixelFormat.RGBA_8888, MAX_IMAGES,
)
// The listener receives frames only while captureFrame() has attached
// this reader's surface. The empty-waiter branch drains a frame already
// queued at the detach boundary.
reader.setOnImageAvailableListener({ source ->
val waiter = pendingCaptureRef.get()
if (waiter == null || !waiter.isActive) {
runCatching { source.acquireLatestImage() }.getOrNull()?.close()
return@setOnImageAvailableListener
}
var image: Image? = null
try {
image = source.acquireLatestImage()
?: return@setOnImageAvailableListener
val png = imageToPngBytes(image, width, height)
if (pendingCaptureRef.compareAndSet(waiter, null)) {
waiter.complete(png)
}
} catch (t: Throwable) {
if (pendingCaptureRef.compareAndSet(waiter, null)) {
waiter.completeExceptionally(t)
}
} finally {
runCatching { image?.close() }
}
}, handler)
return reader
}
/**
* Convert an [Image] from `ImageReader` into a PNG byte array. The
* plane's `rowStride` may be wider than `width * 4` — we must crop
@@ -0,0 +1,426 @@
package com.hermesandroid.relay.assistant
import android.app.role.RoleManager
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.service.voice.VoiceInteractionService
import androidx.core.content.edit
import com.hermesandroid.relay.viewmodel.VoiceState
import com.hermesandroid.relay.viewmodel.VoiceUiState
import com.hermesandroid.relay.HermesRelayApp
import com.hermesandroid.relay.wake.WakeWordActivation
import com.hermesandroid.relay.wake.WakeWordActivationCoordinator
import com.hermesandroid.relay.wake.WakeWordActivationSource
import com.hermesandroid.relay.wake.WakeWordProfileRouting
import java.util.UUID
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
enum class AssistantRoleStatus {
Unavailable,
NotSelected,
Selected,
}
enum class AssistantSessionPhase {
Launching,
Listening,
Transcribing,
Thinking,
Speaking,
Idle,
Error,
Closed,
}
data class AssistantSessionSnapshot(
val phase: AssistantSessionPhase = AssistantSessionPhase.Launching,
val transcript: String? = null,
val response: String = "",
val error: String? = null,
)
object AssistantRole {
fun status(context: Context): AssistantRoleStatus {
val component = ComponentName(context, HermesVoiceInteractionService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val roles = context.getSystemService(RoleManager::class.java)
?: return AssistantRoleStatus.Unavailable
if (!roles.isRoleAvailable(RoleManager.ROLE_ASSISTANT)) {
return AssistantRoleStatus.Unavailable
}
return if (roles.isRoleHeld(RoleManager.ROLE_ASSISTANT) &&
VoiceInteractionService.isActiveService(context, component)
) {
AssistantRoleStatus.Selected
} else {
AssistantRoleStatus.NotSelected
}
}
return if (VoiceInteractionService.isActiveService(context, component)) {
AssistantRoleStatus.Selected
} else {
AssistantRoleStatus.NotSelected
}
}
fun selectionIntent(context: Context): Intent? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val roles = context.getSystemService(RoleManager::class.java)
if (roles?.isRoleAvailable(RoleManager.ROLE_ASSISTANT) == true) {
return roles.createRequestRoleIntent(RoleManager.ROLE_ASSISTANT)
}
}
return Intent(Settings.ACTION_VOICE_INPUT_SETTINGS)
.takeIf { it.resolveActivity(context.packageManager) != null }
}
fun managementIntent(context: Context): Intent? =
Intent(Settings.ACTION_VOICE_INPUT_SETTINGS)
.takeIf { it.resolveActivity(context.packageManager) != null }
?: selectionIntent(context)
}
/**
* Cross-process protocol between the system-owned assistant session process
* and the normal app process that owns the established voice pipeline.
*/
object AssistantSessionProtocol {
const val EXTRA_ASSISTANT_SESSION = "com.hermesandroid.relay.assistant.SESSION"
const val EXTRA_ACTIVATION_ID = "com.hermesandroid.relay.assistant.ACTIVATION_ID"
const val EXTRA_START_NEW_SESSION =
"com.hermesandroid.relay.assistant.START_NEW_SESSION"
const val EXTRA_HANDOFF_ONLY = "com.hermesandroid.relay.assistant.HANDOFF_ONLY"
private const val ACTION_STATUS = "com.hermesandroid.relay.assistant.STATUS"
private const val ACTION_FINISH = "com.hermesandroid.relay.assistant.FINISH"
private const val ACTION_START = "com.hermesandroid.relay.assistant.START"
private const val ACTION_ACTIVATE = "com.hermesandroid.relay.assistant.ACTIVATE"
private const val EXTRA_PHASE = "phase"
private const val EXTRA_TRANSCRIPT = "transcript"
private const val EXTRA_RESPONSE = "response"
private const val EXTRA_ERROR = "error"
private const val EXTRA_CANCEL_VOICE = "cancel_voice"
fun prepareAssistActivation(intent: Intent?) {
val assistIntent = intent ?: return
if (!isAssistAction(assistIntent.action)) return
if (assistIntent.getBooleanExtra(EXTRA_HANDOFF_ONLY, false)) return
assistIntent.putExtra(EXTRA_ASSISTANT_SESSION, true)
}
internal fun isAssistAction(action: String?): Boolean = action == Intent.ACTION_ASSIST
fun activationIntent(
context: Context,
activationId: String = UUID.randomUUID().toString(),
startNewSession: Boolean = true,
) =
Intent(context, com.hermesandroid.relay.MainActivity::class.java).apply {
action = Intent.ACTION_ASSIST
putExtra(EXTRA_ASSISTANT_SESSION, true)
putExtra(EXTRA_ACTIVATION_ID, activationId)
putExtra(EXTRA_START_NEW_SESSION, startNewSession)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
fun fullVoiceIntent(context: Context) =
Intent(context, com.hermesandroid.relay.MainActivity::class.java).apply {
action = Intent.ACTION_ASSIST
addCategory(Intent.CATEGORY_VOICE)
putExtra(EXTRA_HANDOFF_ONLY, true)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
fun activate(
context: Context,
activationId: String = UUID.randomUUID().toString(),
startNewSession: Boolean = true,
) {
context.sendBroadcast(
Intent(context, AssistantSessionLifecycleReceiver::class.java).apply {
action = ACTION_ACTIVATE
putExtra(EXTRA_ACTIVATION_ID, activationId)
putExtra(EXTRA_START_NEW_SESSION, startNewSession)
}
)
}
fun consumeActivation(context: Context, intent: Intent?): Boolean {
if (intent?.getBooleanExtra(EXTRA_HANDOFF_ONLY, false) == true) {
intent.removeExtra(EXTRA_HANDOFF_ONLY)
com.hermesandroid.relay.util.NavRouteRequest.tryRequest("chat")
return true
}
if (intent?.getBooleanExtra(EXTRA_ASSISTANT_SESSION, false) != true) return false
val id = intent.getStringExtra(EXTRA_ACTIVATION_ID) ?: UUID.randomUUID().toString()
val startNewSession = intent.getBooleanExtra(EXTRA_START_NEW_SESSION, true)
AssistantSessionPersistence.setActivation(context, id, startNewSession)
WakeWordActivationCoordinator.request(
WakeWordActivation(
id = id,
startNewSession = startNewSession,
profileRouting = WakeWordProfileRouting(),
source = WakeWordActivationSource.SystemAssistant,
)
)
AssistantAppSessionState.setActive(true)
intent.removeExtra(EXTRA_ASSISTANT_SESSION)
intent.removeExtra(EXTRA_ACTIVATION_ID)
intent.removeExtra(EXTRA_START_NEW_SESSION)
return true
}
fun restoreActivation(context: Context): Boolean {
if (AssistantAppSessionState.active.value) return false
val activation = AssistantSessionPersistence.restoreActivation(context) ?: return false
AssistantAppSessionState.setActive(true)
HermesVoiceInteractionService.setVoiceSessionActive(true)
val application = context.applicationContext as HermesRelayApp
application.runtime.requestVoiceActivation(
activationId = activation.id,
startNewSession = activation.startNewSession,
onFailure = { failure ->
publish(
application,
AssistantSessionSnapshot(
phase = AssistantSessionPhase.Error,
error = failure.message ?: "Hermes voice could not start",
),
)
},
)
return true
}
fun publish(context: Context, snapshot: AssistantSessionSnapshot) {
context.sendBroadcast(
Intent(context, AssistantSessionStateReceiver::class.java).apply {
action = ACTION_STATUS
putExtra(EXTRA_PHASE, snapshot.phase.name)
putExtra(EXTRA_TRANSCRIPT, snapshot.transcript)
putExtra(EXTRA_RESPONSE, snapshot.response)
putExtra(EXTRA_ERROR, snapshot.error)
}
)
if (shouldFinishLifecycleOnSnapshot(snapshot)) {
// The session UI runs in a separate process. Reconcile the app-owned
// lifecycle directly as well so a reclaimed hidden UI process cannot
// leave wake listening paused after full Voice closes.
finish(context, cancelVoice = false)
}
}
fun publish(context: Context, state: VoiceUiState) {
publish(context, snapshotFromVoiceState(state))
}
internal fun snapshotFromVoiceState(state: VoiceUiState): AssistantSessionSnapshot {
val phase = when {
!state.voiceMode -> AssistantSessionPhase.Closed
state.state == VoiceState.Listening -> AssistantSessionPhase.Listening
state.state == VoiceState.Transcribing -> AssistantSessionPhase.Transcribing
state.state == VoiceState.Thinking -> AssistantSessionPhase.Thinking
state.state == VoiceState.Speaking -> AssistantSessionPhase.Speaking
state.state == VoiceState.Error -> AssistantSessionPhase.Error
else -> AssistantSessionPhase.Idle
}
return AssistantSessionSnapshot(
phase = phase,
transcript = state.transcribedText?.take(MAX_SESSION_TEXT_CHARS),
response = state.responseText.take(MAX_SESSION_TEXT_CHARS),
error = state.error?.take(MAX_SESSION_ERROR_CHARS),
)
}
internal fun shouldFinishLifecycleOnSnapshot(snapshot: AssistantSessionSnapshot): Boolean =
snapshot.phase == AssistantSessionPhase.Closed
fun finish(context: Context, cancelVoice: Boolean) {
context.sendBroadcast(
Intent(context, AssistantSessionLifecycleReceiver::class.java).apply {
action = ACTION_FINISH
putExtra(EXTRA_CANCEL_VOICE, cancelVoice)
}
)
}
fun started(context: Context) {
context.sendBroadcast(
Intent(context, AssistantSessionLifecycleReceiver::class.java).setAction(ACTION_START)
)
}
internal fun isFinishAction(action: String?): Boolean = action == ACTION_FINISH
internal fun isStartAction(action: String?): Boolean = action == ACTION_START
internal fun isActivateAction(action: String?): Boolean = action == ACTION_ACTIVATE
internal fun shouldCancelVoice(intent: Intent): Boolean =
intent.getBooleanExtra(EXTRA_CANCEL_VOICE, false)
internal fun readSnapshot(intent: Intent): AssistantSessionSnapshot {
val phase = runCatching {
AssistantSessionPhase.valueOf(
intent.getStringExtra(EXTRA_PHASE) ?: AssistantSessionPhase.Launching.name
)
}.getOrDefault(AssistantSessionPhase.Error)
return AssistantSessionSnapshot(
phase = phase,
transcript = intent.getStringExtra(EXTRA_TRANSCRIPT),
response = intent.getStringExtra(EXTRA_RESPONSE).orEmpty(),
error = intent.getStringExtra(EXTRA_ERROR),
)
}
private const val MAX_SESSION_TEXT_CHARS = 4_000
private const val MAX_SESSION_ERROR_CHARS = 1_000
}
object AssistantSessionState {
private val _snapshot = MutableStateFlow(AssistantSessionSnapshot())
val snapshot: StateFlow<AssistantSessionSnapshot> = _snapshot.asStateFlow()
internal fun update(snapshot: AssistantSessionSnapshot) {
_snapshot.value = snapshot
}
internal fun reset() {
_snapshot.value = AssistantSessionSnapshot()
}
}
class AssistantSessionStateReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AssistantSessionState.update(AssistantSessionProtocol.readSnapshot(intent))
}
}
class AssistantSessionLifecycleReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (AssistantSessionProtocol.isActivateAction(intent.action)) {
val id = intent.getStringExtra(AssistantSessionProtocol.EXTRA_ACTIVATION_ID)
?: UUID.randomUUID().toString()
val startNewSession = intent.getBooleanExtra(
AssistantSessionProtocol.EXTRA_START_NEW_SESSION,
true,
)
AssistantSessionPersistence.setActive(context, true)
AssistantSessionPersistence.setActivation(context, id, startNewSession)
AssistantAppSessionState.setActive(true)
HermesVoiceInteractionService.setVoiceSessionActive(true)
val application = context.applicationContext as HermesRelayApp
// Dispatch into the process-owned scope and return from the receiver
// immediately. Cold readiness can take longer than a broadcast's
// execution budget.
application.runtime.requestVoiceActivation(
activationId = id,
startNewSession = startNewSession,
onFailure = { failure ->
AssistantSessionProtocol.publish(
application,
AssistantSessionSnapshot(
phase = AssistantSessionPhase.Error,
error = failure.message ?: "Hermes voice could not start",
),
)
},
)
return
}
if (AssistantSessionProtocol.isStartAction(intent.action)) {
AssistantSessionPersistence.setActive(context, true)
HermesVoiceInteractionService.setVoiceSessionActive(true)
return
}
if (!AssistantSessionProtocol.isFinishAction(intent.action)) return
AssistantSessionPersistence.setActive(context, false)
if (AssistantSessionProtocol.shouldCancelVoice(intent)) {
val application = context.applicationContext as HermesRelayApp
application.runtime.cancelVoice()
}
AssistantAppSessionState.setActive(false)
HermesVoiceInteractionService.setVoiceSessionActive(false)
}
}
object AssistantSessionPersistence {
private const val STORE = "assistant_session_lifecycle"
private const val KEY_ACTIVE_SINCE = "active_since"
private const val KEY_ACTIVATION_ID = "activation_id"
private const val KEY_START_NEW_SESSION = "start_new_session"
private const val STALE_AFTER_MS = 30 * 60 * 1_000L
fun setActive(context: Context, active: Boolean) {
context.getSharedPreferences(STORE, Context.MODE_PRIVATE).edit(commit = true) {
putLong(KEY_ACTIVE_SINCE, if (active) System.currentTimeMillis() else 0L)
if (!active) {
remove(KEY_ACTIVATION_ID)
}
}
}
fun setActivation(context: Context, id: String, startNewSession: Boolean) {
context.getSharedPreferences(STORE, Context.MODE_PRIVATE).edit(commit = true) {
putString(KEY_ACTIVATION_ID, id)
putBoolean(KEY_START_NEW_SESSION, startNewSession)
}
}
fun restoreActivation(context: Context): WakeWordActivation? {
if (!isActive(context)) return null
val store = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
val id = store.getString(KEY_ACTIVATION_ID, null) ?: return null
return WakeWordActivation(
id = id,
startNewSession = store.getBoolean(KEY_START_NEW_SESSION, true),
profileRouting = WakeWordProfileRouting(),
source = WakeWordActivationSource.SystemAssistant,
)
}
fun isActive(context: Context, nowMs: Long = System.currentTimeMillis()): Boolean {
val since = context.getSharedPreferences(STORE, Context.MODE_PRIVATE)
.getLong(KEY_ACTIVE_SINCE, 0L)
return isFresh(since, nowMs)
}
internal fun isFresh(sinceMs: Long, nowMs: Long): Boolean =
sinceMs > 0L && nowMs - sinceMs in 0..STALE_AFTER_MS
}
object AssistantAppSessionState {
private val _active = MutableStateFlow(false)
val active: StateFlow<Boolean> = _active.asStateFlow()
@Volatile private var voiceStarted = false
internal fun setActive(active: Boolean) {
if (active && !_active.value) voiceStarted = false
if (!active) voiceStarted = false
_active.value = active
}
fun markVoiceStarted() {
voiceStarted = true
}
fun hasVoiceStarted(): Boolean = voiceStarted
}
object AssistantVoiceCommandCoordinator {
private val _cancelRequest = MutableStateFlow<String?>(null)
val cancelRequest: StateFlow<String?> = _cancelRequest.asStateFlow()
fun requestCancel() {
_cancelRequest.value = UUID.randomUUID().toString()
}
fun consume(id: String): Boolean {
if (_cancelRequest.value != id) return false
_cancelRequest.value = null
return true
}
}
@@ -0,0 +1,26 @@
package com.hermesandroid.relay.assistant
import android.content.Intent
import android.speech.RecognitionService
import android.speech.SpeechRecognizer
/**
* Platform-required recognition component for the Hermes voice interactor.
*
* Assistant sessions deliberately use the existing Hermes transcription
* pipeline so wake detection, session capture, and active voice never compete
* for the microphone. Direct SpeechRecognizer clients are therefore rejected
* instead of opening a second recorder.
*/
class HermesRecognitionService : RecognitionService() {
override fun onStartListening(
recognizerIntent: Intent,
listener: Callback,
) {
listener.error(SpeechRecognizer.ERROR_CLIENT)
}
override fun onStopListening(listener: Callback) = Unit
override fun onCancel(listener: Callback) = Unit
}
@@ -0,0 +1,299 @@
package com.hermesandroid.relay.assistant
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.service.voice.VoiceInteractionService
import android.util.Log
import androidx.core.content.ContextCompat
import com.hermesandroid.relay.wake.MicrophoneLease
import com.hermesandroid.relay.wake.MicrophoneOwner
import com.hermesandroid.relay.wake.MicrophoneOwnershipCoordinator
import com.hermesandroid.relay.wake.SherpaWakeWordDetector
import com.hermesandroid.relay.wake.WakeWordModelInstaller
import com.hermesandroid.relay.wake.WakeWordPreferences
import com.hermesandroid.relay.wake.WakeWordPreferencesRepository
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
enum class AssistantWakeRuntimeState {
Stopped,
Starting,
Listening,
PausedForVoice,
AwaitingSession,
Error,
}
/**
* Opt-in Android Digital Assistant service. Android keeps the selected service
* available in the background; all pre-activation audio is evaluated locally.
*/
class HermesVoiceInteractionService : VoiceInteractionService() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val mainHandler = Handler(Looper.getMainLooper())
private val stopRequested = AtomicBoolean(false)
private val resourceLock = Any()
private var preferencesJob: Job? = null
private var recognitionJob: Job? = null
private var recorder: AudioRecord? = null
private var detector: SherpaWakeWordDetector? = null
private var microphoneLease: MicrophoneLease? = null
@Volatile private var latestPreferences = WakeWordPreferences()
@Volatile private var voiceSessionActive = false
override fun onCreate() {
super.onCreate()
runningInstance = this
}
override fun onReady() {
super.onReady()
if (runningInstance !== this) return
voiceSessionActive = AssistantSessionPersistence.isActive(this)
preferencesJob?.cancel()
preferencesJob = scope.launch {
WakeWordPreferencesRepository(applicationContext).flow.collectLatest { prefs ->
latestPreferences = prefs
if (prefs.assistantEnabled && !voiceSessionActive) {
restartRecognition(prefs)
} else {
stopRecognition()
setRuntimeState(
if (voiceSessionActive) {
AssistantWakeRuntimeState.PausedForVoice
} else {
AssistantWakeRuntimeState.Stopped
}
)
}
}
}
}
override fun onLaunchVoiceAssistFromKeyguard() {
val activationId = java.util.UUID.randomUUID().toString()
showAssistantSession(
fromKeyguard = true,
activationId = activationId,
)
}
override fun onShutdown() {
stopRecognition()
preferencesJob?.cancel()
setRuntimeState(AssistantWakeRuntimeState.Stopped)
super.onShutdown()
}
override fun onDestroy() {
stopRecognition()
preferencesJob?.cancel()
if (runningInstance === this) runningInstance = null
scope.cancel()
super.onDestroy()
}
private suspend fun restartRecognition(preferences: WakeWordPreferences) {
val previous = recognitionJob
stopRecognition()
previous?.join()
if (!voiceSessionActive && preferences.assistantEnabled) {
startRecognition(preferences)
}
}
@SuppressLint("MissingPermission")
private fun startRecognition(preferences: WakeWordPreferences) {
if (voiceSessionActive || recognitionJob?.isActive == true) return
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) !=
PackageManager.PERMISSION_GRANTED
) {
setRuntimeState(AssistantWakeRuntimeState.Error)
return
}
val files = WakeWordModelInstaller(this).installedFiles()
if (files == null) {
setRuntimeState(AssistantWakeRuntimeState.Error)
return
}
val lease = MicrophoneOwnershipCoordinator.tryAcquire(MicrophoneOwner.WakeWord)
if (lease == null) {
setRuntimeState(AssistantWakeRuntimeState.PausedForVoice)
scheduleRetry()
return
}
microphoneLease = lease
stopRequested.set(false)
setRuntimeState(AssistantWakeRuntimeState.Starting)
recognitionJob = scope.launch {
var detected = false
var unattachedDetector: SherpaWakeWordDetector? = null
try {
val createdDetector = SherpaWakeWordDetector(
files,
preferences.sensitivity,
preferences.confirmationFrames,
)
unattachedDetector = createdDetector
val minBuffer = AudioRecord.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(SAMPLE_RATE / 5 * 2)
val createdRecorder = AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION)
.setAudioFormat(
AudioFormat.Builder()
.setSampleRate(SAMPLE_RATE)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer * 2)
.build()
if (createdRecorder.state != AudioRecord.STATE_INITIALIZED) {
createdRecorder.release()
error("Assistant wake microphone failed to initialize")
}
synchronized(resourceLock) {
if (stopRequested.get()) {
createdRecorder.release()
return@launch
}
recorder = createdRecorder
detector = createdDetector
unattachedDetector = null
}
createdRecorder.startRecording()
setRuntimeState(AssistantWakeRuntimeState.Listening)
val samples = ShortArray(FRAME_SAMPLES)
while (!stopRequested.get()) {
val count = createdRecorder.read(samples, 0, samples.size)
if (count < 0) error("Assistant wake microphone read failed: $count")
if (count > 0 && createdDetector.accept(samples, count)) {
detected = true
break
}
}
} catch (t: Throwable) {
if (!stopRequested.get()) {
Log.w(TAG, "Assistant wake listening failed", t)
setRuntimeState(AssistantWakeRuntimeState.Error)
}
} finally {
runCatching { unattachedDetector?.close() }
releaseResources()
recognitionJob = null
}
if (detected && !stopRequested.get()) {
setRuntimeState(AssistantWakeRuntimeState.AwaitingSession)
val keyguard = getSystemService(android.app.KeyguardManager::class.java)
mainHandler.post {
showAssistantSession(fromKeyguard = keyguard?.isKeyguardLocked == true)
}
}
}
}
private fun showAssistantSession(fromKeyguard: Boolean, activationId: String? = null) {
voiceSessionActive = true
stopRecognition()
setRuntimeState(AssistantWakeRuntimeState.AwaitingSession)
showSession(
Bundle().apply {
putBoolean(EXTRA_FROM_KEYGUARD, fromKeyguard)
activationId?.let { putString(AssistantSessionProtocol.EXTRA_ACTIVATION_ID, it) }
putBoolean(
AssistantSessionProtocol.EXTRA_START_NEW_SESSION,
latestPreferences.startNewSession,
)
},
0,
)
}
private fun setVoiceSessionActiveInternal(active: Boolean) {
voiceSessionActive = active
if (active) {
stopRecognition()
setRuntimeState(AssistantWakeRuntimeState.PausedForVoice)
} else if (latestPreferences.assistantEnabled) {
scheduleRetry()
} else {
setRuntimeState(AssistantWakeRuntimeState.Stopped)
}
}
private fun scheduleRetry() {
if (recognitionJob?.isActive == true || voiceSessionActive) return
recognitionJob = scope.launch {
delay(RETRY_DELAY_MS)
recognitionJob = null
if (!voiceSessionActive && latestPreferences.assistantEnabled) {
startRecognition(latestPreferences)
}
}
}
private fun stopRecognition() {
stopRequested.set(true)
synchronized(resourceLock) {
runCatching { recorder?.stop() }
runCatching { recorder?.release() }
recorder = null
microphoneLease?.let(MicrophoneOwnershipCoordinator::release)
microphoneLease = null
}
recognitionJob?.cancel()
}
private fun releaseResources() {
synchronized(resourceLock) {
runCatching { recorder?.stop() }
runCatching { recorder?.release() }
recorder = null
runCatching { detector?.close() }
detector = null
microphoneLease?.let(MicrophoneOwnershipCoordinator::release)
microphoneLease = null
}
}
private fun setRuntimeState(state: AssistantWakeRuntimeState) {
_runtimeState.value = state
}
companion object {
private const val TAG = "HermesAssistant"
private const val SAMPLE_RATE = 16_000
private const val FRAME_SAMPLES = 1_600
private const val RETRY_DELAY_MS = 500L
const val EXTRA_FROM_KEYGUARD = "from_keyguard"
private val _runtimeState = kotlinx.coroutines.flow.MutableStateFlow(
AssistantWakeRuntimeState.Stopped
)
val runtimeState = _runtimeState.asStateFlow()
@Volatile private var runningInstance: HermesVoiceInteractionService? = null
fun setVoiceSessionActive(active: Boolean) {
runningInstance?.setVoiceSessionActiveInternal(active)
}
}
}
@@ -0,0 +1,629 @@
package com.hermesandroid.relay.assistant
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.service.voice.VoiceInteractionSession
import android.service.voice.VoiceInteractionSessionService
import android.view.View
import android.view.WindowManager
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
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.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.hermesandroid.relay.R
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
import java.util.UUID
import kotlin.math.max
import kotlin.math.roundToInt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
class HermesVoiceInteractionSessionService : VoiceInteractionSessionService() {
override fun onNewSession(args: Bundle?): VoiceInteractionSession =
HermesVoiceInteractionSession(this)
}
internal enum class AssistantSessionPresentation {
Inactive,
Overlay,
FullVoice,
}
internal fun shouldCancelVoiceWhenSessionUiEnds(
presentation: AssistantSessionPresentation,
): Boolean = presentation == AssistantSessionPresentation.Overlay
private class HermesVoiceInteractionSession(
private val service: HermesVoiceInteractionSessionService,
) : VoiceInteractionSession(service) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val viewOwner = AssistantSessionViewOwner().also { it.start() }
private var presentation = AssistantSessionPresentation.Inactive
private val assistantSurfaceBounds = android.graphics.Rect()
private var surfaceExpanded by mutableStateOf(false)
init {
scope.launch {
AssistantSessionState.snapshot.collect { snapshot ->
if (presentation != AssistantSessionPresentation.Inactive &&
snapshot.phase == AssistantSessionPhase.Closed
) {
finishSession(cancelVoice = false)
}
}
}
}
override fun onCreate() {
super.onCreate()
window.window?.apply {
setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
setDimAmount(0f)
}
}
override fun onCreateContentView(): View = ComposeView(service).apply {
setBackgroundColor(android.graphics.Color.TRANSPARENT)
setViewTreeLifecycleOwner(viewOwner)
setViewTreeViewModelStoreOwner(viewOwner)
setViewTreeSavedStateRegistryOwner(viewOwner)
setContent {
HermesRelayTheme {
AssistantSessionSurface(
expanded = surfaceExpanded,
onExpandedChange = { surfaceExpanded = it },
onCancel = { finishSession(cancelVoice = true) },
onRetry = { launchVoice(startNewSession = true) },
onOpenFullVoice = {
if (presentation == AssistantSessionPresentation.Overlay) {
openFullVoice()
}
},
onSurfaceBoundsChanged = { bounds ->
if (assistantSurfaceBounds != bounds) {
assistantSurfaceBounds.set(bounds)
window.window?.decorView?.requestLayout()
}
},
)
}
}
}
override fun onShow(args: Bundle?, showFlags: Int) {
super.onShow(args, showFlags)
if (args?.getBoolean(HermesVoiceInteractionService.EXTRA_FROM_KEYGUARD, false) == true) {
window.window?.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
setUiEnabled(true)
val startsNewLifecycle = presentation == AssistantSessionPresentation.Inactive
presentation = AssistantSessionPresentation.Overlay
if (!startsNewLifecycle) return
surfaceExpanded = false
AssistantSessionState.reset()
launchVoice(
activationId = args?.getString(AssistantSessionProtocol.EXTRA_ACTIVATION_ID)
?: UUID.randomUUID().toString(),
startNewSession = args?.getBoolean(
AssistantSessionProtocol.EXTRA_START_NEW_SESSION,
true,
) ?: true,
)
}
override fun onComputeInsets(outInsets: Insets) {
super.onComputeInsets(outInsets)
outInsets.touchableInsets = Insets.TOUCHABLE_INSETS_REGION
outInsets.touchableRegion.set(assistantSurfaceBounds)
}
override fun onBackPressed() {
if (presentation == AssistantSessionPresentation.Overlay && surfaceExpanded) {
surfaceExpanded = false
return
}
super.onBackPressed()
}
override fun onHide() {
if (shouldCancelVoiceWhenSessionUiEnds(presentation)) {
finishSession(cancelVoice = true)
}
super.onHide()
}
override fun onDestroy() {
if (shouldCancelVoiceWhenSessionUiEnds(presentation)) {
AssistantSessionProtocol.finish(service, cancelVoice = true)
}
presentation = AssistantSessionPresentation.Inactive
viewOwner.stop()
scope.cancel()
super.onDestroy()
}
private fun launchVoice(
activationId: String = UUID.randomUUID().toString(),
startNewSession: Boolean,
) {
runCatching {
AssistantSessionProtocol.activate(
service,
activationId = activationId,
startNewSession = startNewSession,
)
}.onFailure {
AssistantSessionState.update(
AssistantSessionSnapshot(
phase = AssistantSessionPhase.Error,
error = it.message ?: "Hermes could not open the voice session.",
)
)
}
}
private fun openFullVoice() {
runCatching {
startVoiceActivity(AssistantSessionProtocol.fullVoiceIntent(service))
presentation = AssistantSessionPresentation.FullVoice
setUiEnabled(false)
}.onFailure {
AssistantSessionState.update(
AssistantSessionSnapshot(
phase = AssistantSessionPhase.Error,
error = it.message ?: "Hermes could not open full voice.",
)
)
}
}
private fun finishSession(cancelVoice: Boolean) {
if (presentation == AssistantSessionPresentation.Inactive) return
presentation = AssistantSessionPresentation.Inactive
AssistantSessionProtocol.finish(service, cancelVoice)
finish()
}
}
private class AssistantSessionViewOwner :
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner {
private val lifecycleRegistry = LifecycleRegistry(this)
private val store = ViewModelStore()
private val savedStateController = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle get() = lifecycleRegistry
override val viewModelStore: ViewModelStore get() = store
override val savedStateRegistry: SavedStateRegistry
get() = savedStateController.savedStateRegistry
fun start() {
savedStateController.performRestore(null)
lifecycleRegistry.currentState = Lifecycle.State.CREATED
lifecycleRegistry.currentState = Lifecycle.State.RESUMED
}
fun stop() {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
store.clear()
}
}
@Composable
private fun AssistantSessionSurface(
expanded: Boolean,
onExpandedChange: (Boolean) -> Unit,
onCancel: () -> Unit,
onRetry: () -> Unit,
onOpenFullVoice: () -> Unit,
onSurfaceBoundsChanged: (android.graphics.Rect) -> Unit,
) {
val snapshot by AssistantSessionState.snapshot.collectAsState()
val status = assistantStatus(snapshot.phase)
Box(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 12.dp, vertical = 12.dp)
.navigationBarsPadding(),
contentAlignment = Alignment.BottomCenter,
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.animateContentSize()
.onGloballyPositioned { coordinates ->
val bounds = coordinates.boundsInWindow()
onSurfaceBoundsChanged(
android.graphics.Rect(
bounds.left.roundToInt(),
bounds.top.roundToInt(),
bounds.right.roundToInt(),
bounds.bottom.roundToInt(),
)
)
},
shape = RoundedCornerShape(if (expanded) 30.dp else 28.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh.copy(alpha = 0.98f),
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 10.dp,
shadowElevation = 12.dp,
) {
if (expanded) {
ExpandedAssistantSurface(
snapshot = snapshot,
status = status,
onCollapse = { onExpandedChange(false) },
onCancel = onCancel,
onRetry = onRetry,
onOpenFullVoice = onOpenFullVoice,
)
} else {
CompactAssistantSurface(
snapshot = snapshot,
status = status,
onExpand = { onExpandedChange(true) },
onCancel = onCancel,
)
}
}
}
}
@Composable
private fun CompactAssistantSurface(
snapshot: AssistantSessionSnapshot,
status: String,
onExpand: () -> Unit,
onCancel: () -> Unit,
) {
Row(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
AssistantOrb(snapshot.phase)
Column(modifier = Modifier.weight(1f)) {
Text(
text = status,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold,
)
Text(
text = compactAssistantText(snapshot),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(
onClick = onExpand,
modifier = Modifier.size(40.dp),
) {
Icon(
imageVector = Icons.Filled.ExpandLess,
contentDescription = stringResource(R.string.assistant_session_expand),
)
}
AssistantStopButton(onClick = onCancel, compact = true)
}
}
@Composable
private fun ExpandedAssistantSurface(
snapshot: AssistantSessionSnapshot,
status: String,
onCollapse: () -> Unit,
onCancel: () -> Unit,
onRetry: () -> Unit,
onOpenFullVoice: () -> Unit,
) {
Column(
modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.width(38.dp)
.height(4.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f))
.align(Alignment.CenterHorizontally),
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
AssistantOrb(snapshot.phase, size = 38)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.app_name),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Text(
text = status,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
IconButton(onClick = onCollapse) {
Icon(
imageVector = Icons.Filled.ExpandMore,
contentDescription = stringResource(R.string.assistant_session_collapse),
)
}
}
AssistantWaveform(snapshot.phase)
snapshot.transcript?.takeIf { it.isNotBlank() }?.let { transcript ->
AssistantTextRow(
icon = Icons.Filled.Person,
text = transcript,
color = MaterialTheme.colorScheme.primary,
)
}
snapshot.response.takeIf { it.isNotBlank() }?.let { response ->
AssistantTextRow(
icon = Icons.Filled.AutoAwesome,
text = response,
color = MaterialTheme.colorScheme.onSurface,
)
}
snapshot.error?.let { error ->
Text(
text = error,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium,
)
}
if (snapshot.phase == AssistantSessionPhase.Transcribing ||
snapshot.phase == AssistantSessionPhase.Thinking
) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
AssistantStopButton(onClick = onCancel, compact = false)
Spacer(Modifier.weight(1f))
if (snapshot.phase == AssistantSessionPhase.Error) {
TextButton(onClick = onRetry) {
Text(stringResource(R.string.assistant_session_retry))
}
}
OutlinedButton(onClick = onOpenFullVoice) {
Text(stringResource(R.string.assistant_session_open_full_voice))
}
}
}
}
@Composable
private fun AssistantOrb(
phase: AssistantSessionPhase,
size: Int = 52,
) {
val active = phase == AssistantSessionPhase.Listening ||
phase == AssistantSessionPhase.Transcribing ||
phase == AssistantSessionPhase.Thinking ||
phase == AssistantSessionPhase.Speaking
Box(
modifier = Modifier
.size(size.dp)
.clip(CircleShape)
.background(
if (active) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant
}
),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Filled.GraphicEq,
contentDescription = null,
tint = if (active) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.size((size * 0.5f).dp),
)
}
}
@Composable
private fun AssistantWaveform(phase: AssistantSessionPhase) {
val active = phase == AssistantSessionPhase.Listening ||
phase == AssistantSessionPhase.Speaking
val primary = if (active) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.55f)
}
Canvas(
modifier = Modifier
.fillMaxWidth()
.height(28.dp),
) {
val centerY = size.height / 2f
val bars = 33
val spacing = size.width / bars
repeat(bars) { index ->
val distance = kotlin.math.abs(index - bars / 2f) / (bars / 2f)
val envelope = max(0.18f, 1f - distance)
val pattern = 0.45f + ((index * 17) % 11) / 20f
val halfHeight = size.height * 0.46f * envelope * pattern
val x = spacing * (index + 0.5f)
drawLine(
color = primary,
start = Offset(x, centerY - halfHeight),
end = Offset(x, centerY + halfHeight),
strokeWidth = max(2f, spacing * 0.28f),
cap = StrokeCap.Round,
)
}
}
}
@Composable
private fun AssistantTextRow(
icon: androidx.compose.ui.graphics.vector.ImageVector,
text: String,
color: Color,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.Top,
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = color,
modifier = Modifier.size(20.dp),
)
Text(
text = text,
style = MaterialTheme.typography.bodyLarge,
color = color,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
)
}
}
@Composable
private fun AssistantStopButton(
onClick: () -> Unit,
compact: Boolean,
) {
if (compact) {
IconButton(
onClick = onClick,
modifier = Modifier
.size(44.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.errorContainer),
) {
Icon(
imageVector = Icons.Filled.Stop,
contentDescription = stringResource(R.string.assistant_session_cancel),
tint = MaterialTheme.colorScheme.error,
)
}
} else {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.error,
),
) {
Icon(
imageVector = Icons.Filled.Stop,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.assistant_session_stop))
}
}
}
@Composable
private fun assistantStatus(phase: AssistantSessionPhase): String = when (phase) {
AssistantSessionPhase.Launching -> stringResource(R.string.assistant_session_launching)
AssistantSessionPhase.Listening -> stringResource(R.string.assistant_session_listening)
AssistantSessionPhase.Transcribing -> stringResource(R.string.assistant_session_transcribing)
AssistantSessionPhase.Thinking -> stringResource(R.string.assistant_session_thinking)
AssistantSessionPhase.Speaking -> stringResource(R.string.assistant_session_speaking)
AssistantSessionPhase.Idle -> stringResource(R.string.assistant_session_ready)
AssistantSessionPhase.Error -> stringResource(R.string.assistant_session_error)
AssistantSessionPhase.Closed -> stringResource(R.string.assistant_session_closing)
}
@Composable
private fun compactAssistantText(snapshot: AssistantSessionSnapshot): String =
snapshot.transcript?.takeIf { it.isNotBlank() }
?: snapshot.response.takeIf { it.isNotBlank() }
?: snapshot.error?.takeIf { it.isNotBlank() }
?: assistantStatus(snapshot.phase)
@@ -8,11 +8,16 @@ import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.media.audiofx.NoiseSuppressor
import android.util.Log
import com.hermesandroid.relay.wake.MicrophoneLease
import com.hermesandroid.relay.wake.MicrophoneOwner
import com.hermesandroid.relay.wake.MicrophoneOwnershipCoordinator
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -22,40 +27,37 @@ import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import kotlin.math.max
/**
* Duplex audio capture for voice barge-in (plan unit B3).
*
* While TTS is playing, this listener continuously pulls 32 ms / 512-sample
* PCM frames off the microphone and feeds them to [VadEngine]. It emits two
* SharedFlows that B4 will wire into the voice state machine:
* During response generation and playback, this listener continuously pulls
* 32 ms / 512-sample PCM frames off the microphone and feeds them to
* [VadEngine]. One instance owns the full active turn. It emits two
* SharedFlows wired into the voice state machine:
*
* - [maybeSpeech] fires on the **first** positive raw-VAD frame — before the
* second-layer debouncer latches. B4 uses this to softly [VoicePlayer.duck]
* the TTS so the user's voice has acoustic headroom while we decide whether
* to cut off.
*
* - [bargeInDetected] fires when [VadEngine] confirms speech post-hysteresis.
* B4 uses this to call `interruptSpeaking()` and flip state to Listening.
* - [bargeInDetected] fires when [VadEngine] confirms speech post-hysteresis
* and the calibrated RMS majority gate accepts it. The owner uses this to
* interrupt generation/playback and flip state to Listening.
*
* ### Acoustic echo cancellation
*
* We configure [AudioRecord] with [MediaRecorder.AudioSource.VOICE_COMMUNICATION]
* so the platform's voice-call AEC pipeline is in play, and additionally try
* to attach [AcousticEchoCanceler] + [NoiseSuppressor] keyed to the ExoPlayer
* audio session id so TTS audio is cancelled from the mic stream specifically.
* to attach [AcousticEchoCanceler] + [NoiseSuppressor] to the capture
* [AudioRecord] session. Android audio preprocessors belong to the capture
* path; a playback session is not a valid attachment target for AEC/NS.
* Without AEC, the device's own speaker output would trip the VAD the moment
* TTS started and we'd interrupt ourselves.
*
* The ExoPlayer audio session id is not stable at the moment we want to start
* listening — Media3 allocates the underlying AudioTrack lazily on first
* playback, and callers may hit [start] before that's happened (e.g. the very
* first sentence of a turn). We poll [audioSessionIdProvider] for up to 1 s
* before giving up on AEC and proceeding with the mic-hardware AEC alone.
* See the `AEC_SESSION_POLL_*` constants below.
*
* ### Graceful degradation
*
* - `AudioRecord.getState() != STATE_INITIALIZED` → log WARN, emit nothing,
@@ -85,8 +87,8 @@ import kotlin.math.max
class BargeInListener internal constructor(
private val audioSource: AudioFrameSource,
private val vadEngine: VadEngine,
private val audioSessionIdProvider: () -> Int,
private val readerDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val nowMsProvider: () -> Long = System::currentTimeMillis,
) {
companion object {
@@ -100,12 +102,6 @@ class BargeInListener internal constructor(
* brief delay (GC pause, dispatcher contention). */
private const val AUDIO_BUFFER_FRAMES = 4
/** ExoPlayer may return `0` for its audio session id until its
* AudioTrack is first allocated (on playback start). Poll the
* provider briefly before giving up on AEC and proceeding without. */
private const val AEC_SESSION_POLL_INTERVAL_MS = 50L
private const val AEC_SESSION_POLL_TIMEOUT_MS = 1_000L
/**
* Factory for the production path. Builds an [AudioRecordSource] from
* a `Context` and wires it to the listener. The returned listener has
@@ -114,11 +110,9 @@ class BargeInListener internal constructor(
fun create(
context: Context,
vadEngine: VadEngine,
audioSessionIdProvider: () -> Int,
): BargeInListener = BargeInListener(
audioSource = AudioRecordSource(context.applicationContext),
vadEngine = vadEngine,
audioSessionIdProvider = audioSessionIdProvider,
)
}
@@ -140,8 +134,43 @@ class BargeInListener internal constructor(
private val frameBuffer: ShortArray = ShortArray(VadEngine.FRAME_SIZE_SAMPLES)
@Volatile private var readerJob: Job? = null
@Volatile private var microphoneLease: MicrophoneLease? = null
@Volatile private var aec: AcousticEchoCanceler? = null
@Volatile private var noiseSuppressor: NoiseSuppressor? = null
private val rmsGate = RmsBargeInGate()
@Volatile private var playbackGraceMs: Long = RmsBargeInGate.DEFAULT_PLAYBACK_GRACE_MS
@Volatile private var playbackActiveProvider: (() -> Boolean)? = null
@Volatile private var diagnosticsEnabled: Boolean = false
private var wasCalibrating: Boolean = false
/** Apply the user-facing barge-in sensitivity to the quiet-room RMS gate. */
fun setThresholdMultiplier(multiplier: Float) {
rmsGate.thresholdMultiplier = multiplier
}
fun setDiagnosticsEnabled(enabled: Boolean) {
diagnosticsEnabled = enabled
}
/** Supplies the renderer's current playback phase for upstream-style gaps. */
fun setPlaybackActiveProvider(provider: () -> Boolean) {
playbackActiveProvider = provider
}
/**
* Freeze quiet-room calibration and begin the playback-only grace window.
* Idempotent so every renderer may call it at its first audible chunk.
*/
fun markPlaybackStarted(
nowMs: Long = System.currentTimeMillis(),
graceMs: Long = RmsBargeInGate.DEFAULT_PLAYBACK_GRACE_MS,
) {
playbackGraceMs = graceMs.coerceAtLeast(0L)
rmsGate.markPlaybackStarted(nowMs)
if (diagnosticsEnabled) {
Log.d(TAG, "voice-vad playback started; grace=${playbackGraceMs}ms")
}
}
/**
* Allocate the audio pipeline and begin reading frames into [vadEngine].
@@ -163,6 +192,12 @@ class BargeInListener internal constructor(
return
}
val lease = MicrophoneOwnershipCoordinator.tryAcquire(MicrophoneOwner.BargeIn)
if (lease == null) {
Log.i(TAG, "Barge-in listener inactive — microphone is owned by another voice surface")
return
}
microphoneLease = lease
if (!audioSource.initialize()) {
Log.w(
TAG,
@@ -170,11 +205,16 @@ class BargeInListener internal constructor(
"(missing RECORD_AUDIO permission or mic busy) — listener inactive",
)
_aecAttached.value = false
MicrophoneOwnershipCoordinator.release(lease)
microphoneLease = null
return
}
_aecAttached.value = false
rmsGate.reset()
wasCalibrating = true
readerJob = scope.launch(readerDispatcher) {
var effectsJob: Job? = null
try {
try {
audioSource.start()
@@ -185,7 +225,9 @@ class BargeInListener internal constructor(
return@launch
}
Log.i(TAG, "Barge-in AudioRecord reader started")
maybeAttachEffects()
// Effects attach beside the reader so capture can begin even
// on devices that reject or omit the optional preprocessors.
effectsJob = launch { maybeAttachEffects() }
while (isActive) {
val read = try {
@@ -222,10 +264,41 @@ class BargeInListener internal constructor(
Log.w(TAG, "VadEngine.analyze failed; stopping reader: ${t.message}")
break
}
if (result.probability > 0f) {
val gated = rmsGate.observe(
frame = frameBuffer,
rawSpeech = result.probability > 0f,
nowMs = nowMsProvider(),
playbackGraceMs = playbackGraceMs,
confirmedSpeech = result.isSpeech,
playbackActiveOverride = playbackActiveProvider?.invoke(),
)
if (diagnosticsEnabled) {
if (wasCalibrating && !gated.calibrating) {
Log.d(
TAG,
"voice-vad calibrated quiet floor=${gated.floor.toInt()} " +
"mult=${rmsGate.thresholdMultiplier}",
)
}
wasCalibrating = gated.calibrating
if (
gated.detected || gated.playbackGrace ||
gated.rms >= gated.threshold * 0.5f
) {
Log.d(
TAG,
"voice-vad rms=${gated.rms.toInt()} floor=${gated.floor.toInt()} " +
"trigger=${gated.threshold.toInt()} raw=${result.probability > 0f} " +
"confirmed=${result.isSpeech} detected=${gated.detected} " +
"grace=${gated.playbackGrace} " +
"phase=${if (gated.playback) "playback" else "generation"}",
)
}
}
if (gated.maybeSpeech) {
_maybeSpeech.tryEmit(Unit)
}
if (result.isSpeech) {
if (gated.detected) {
_bargeInDetected.tryEmit(Unit)
}
// Give the dispatcher a chance to observe cancellation
@@ -237,11 +310,19 @@ class BargeInListener internal constructor(
yield()
}
} finally {
// The reader reaches this block with its Job cancelled.
// Teardown still has to wait for the sibling AEC poll before
// releasing the AudioRecord and microphone lease.
withContext(NonCancellable) {
effectsJob?.cancelAndJoin()
}
// Release effects + AudioRecord in the reverse of attach order
// so the AudioSessionId is still valid when AEC teardown runs.
releaseEffects()
runCatching { audioSource.stop() }
runCatching { audioSource.release() }
microphoneLease?.let(MicrophoneOwnershipCoordinator::release)
microphoneLease = null
_aecAttached.value = false
}
}
@@ -258,20 +339,26 @@ class BargeInListener internal constructor(
if (job?.isActive == true) {
Log.i(TAG, "Stopping barge-in AudioRecord reader")
}
// AudioRecord.read() may be blocked in native code, so stop the source
// before cancellation to make the reader observe shutdown promptly.
runCatching { audioSource.stop() }
job?.cancel()
readerJob = null
if (job == null) {
runCatching { audioSource.release() }
microphoneLease?.let(MicrophoneOwnershipCoordinator::release)
microphoneLease = null
}
return job
}
private suspend fun maybeAttachEffects() {
val sessionId = awaitNonZeroSessionId()
val sessionId = audioSource.audioSessionId
if (sessionId == 0) {
Log.i(
TAG,
"AEC not attached — ExoPlayer audio session id was still 0 " +
"after ${AEC_SESSION_POLL_TIMEOUT_MS}ms poll; continuing " +
"without effects (mic-hardware AEC from VOICE_COMMUNICATION " +
"still in play)",
"AEC not attached — AudioRecord capture session id is 0; " +
"continuing without optional effects",
)
return
}
@@ -307,20 +394,6 @@ class BargeInListener internal constructor(
}
}
private suspend fun awaitNonZeroSessionId(): Int {
val immediate = audioSessionIdProvider()
if (immediate != 0) return immediate
var waited = 0L
while (waited < AEC_SESSION_POLL_TIMEOUT_MS) {
delay(AEC_SESSION_POLL_INTERVAL_MS)
waited += AEC_SESSION_POLL_INTERVAL_MS
val id = audioSessionIdProvider()
if (id != 0) return id
}
return 0
}
private fun releaseEffects() {
aec?.let {
runCatching { it.enabled = false }
@@ -341,6 +414,9 @@ class BargeInListener internal constructor(
* reader coroutine.
*/
internal interface AudioFrameSource {
/** Capture-session id used by Android audio preprocessors. */
val audioSessionId: Int
/**
* Allocate underlying native resources. Returns true on success.
* Returning false from here short-circuits the listener without any
@@ -377,6 +453,9 @@ class BargeInListener internal constructor(
private class AudioRecordSource(context: Context) : AudioFrameSource {
private var record: AudioRecord? = null
override val audioSessionId: Int
get() = record?.audioSessionId ?: 0
@SuppressLint("MissingPermission")
override fun initialize(): Boolean {
val sampleRate = 16_000
@@ -4,6 +4,8 @@ import android.annotation.SuppressLint
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import com.hermesandroid.relay.wake.MicrophoneOwner
import com.hermesandroid.relay.wake.MicrophoneOwnershipCoordinator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
@@ -40,24 +42,37 @@ class RealtimePcmRecorder(
maxDurationMs: Long = 15_000,
onLevel: ((Float) -> Unit)? = null,
): ByteArray = withContext(Dispatchers.IO) {
val minBuffer = AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(sampleRate / 10 * 2)
val microphoneLease =
MicrophoneOwnershipCoordinator.tryAcquire(MicrophoneOwner.RealtimeDiagnostics)
?: error("Microphone is in use by another voice feature")
val minBuffer = try {
AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(sampleRate / 10 * 2)
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(microphoneLease)
throw t
}
val maxBytes = ((sampleRate * maxDurationMs) / 1000L * 2L).toInt()
val recorder = AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer)
.build()
val recorder = try {
AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer)
.build()
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(microphoneLease)
throw t
}
val out = ByteArrayOutputStream(minBuffer * 4)
val buffer = ByteArray(minBuffer)
@@ -77,32 +92,46 @@ class RealtimePcmRecorder(
capturing = false
try { recorder.stop() } catch (_: Exception) { }
recorder.release()
MicrophoneOwnershipCoordinator.release(microphoneLease)
}
out.toByteArray()
}
@SuppressLint("MissingPermission")
suspend fun capture(durationMs: Long = 800): ByteArray = withContext(Dispatchers.IO) {
val minBuffer = AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(sampleRate / 10 * 2)
val microphoneLease =
MicrophoneOwnershipCoordinator.tryAcquire(MicrophoneOwner.RealtimeDiagnostics)
?: error("Microphone is in use by another voice feature")
val minBuffer = try {
AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(sampleRate / 10 * 2)
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(microphoneLease)
throw t
}
val targetBytes = ((sampleRate * durationMs) / 1000L * 2L)
.toInt()
.coerceAtLeast(minBuffer)
val recorder = AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer)
.build()
val recorder = try {
AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer)
.build()
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(microphoneLease)
throw t
}
val out = ByteArrayOutputStream(targetBytes)
val buffer = ByteArray(minBuffer)
@@ -123,6 +152,7 @@ class RealtimePcmRecorder(
} finally {
try { recorder.stop() } catch (_: Exception) { }
recorder.release()
MicrophoneOwnershipCoordinator.release(microphoneLease)
}
out.toByteArray()
}
@@ -0,0 +1,216 @@
package com.hermesandroid.relay.audio
import kotlin.math.ceil
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Turn-scoped RMS gate layered in front of the model VAD.
*
* The first quiet frames establish a room floor before playback. That floor is
* frozen as soon as playback begins so speaker output can never teach the gate
* to ignore the user. Detection uses a majority window rather than requiring
* perfectly consecutive frames, which tolerates short consonant/syllable dips.
*/
internal class RmsBargeInGate(
private val calibrationFrames: Int = DEFAULT_CALIBRATION_FRAMES,
private val decisionWindowFrames: Int = DEFAULT_DECISION_WINDOW_FRAMES,
private val requiredWindowRatio: Float = DEFAULT_REQUIRED_WINDOW_RATIO,
) {
private val ambient = ArrayDeque<Float>(MAX_AMBIENT_FRAMES)
private val decisions = ArrayDeque<Boolean>(decisionWindowFrames)
private var quietFloor: Float = DEFAULT_QUIET_FLOOR_RMS
private var calibrated = false
private var playbackActive = false
private var playbackStartedAtMs: Long? = null
private var playbackStoppedAtMs: Long? = null
var thresholdMultiplier: Float = DEFAULT_THRESHOLD_MULTIPLIER
set(value) {
field = value.coerceIn(MIN_THRESHOLD_MULTIPLIER, MAX_THRESHOLD_MULTIPLIER)
}
fun reset() {
ambient.clear()
decisions.clear()
quietFloor = DEFAULT_QUIET_FLOOR_RMS
calibrated = false
playbackActive = false
playbackStartedAtMs = null
playbackStoppedAtMs = null
}
fun markPlaybackStarted(nowMs: Long) {
updatePlaybackPhase(active = true, nowMs = nowMs)
}
fun observe(
frame: ShortArray,
rawSpeech: Boolean,
nowMs: Long,
playbackGraceMs: Long,
confirmedSpeech: Boolean = rawSpeech,
playbackActiveOverride: Boolean? = null,
): RmsGateResult {
val rms = rms(frame)
playbackActiveOverride?.let { reportedActive ->
// A renderer marks playback just before its first write so speaker
// output cannot enter calibration. Do not let a provider that has
// not observed the first audible frame yet undo that protection
// during the configured grace window.
val withinStartupGrace = playbackActive && playbackStartedAtMs?.let {
nowMs - it < playbackGraceMs
} == true
if (reportedActive || !withinStartupGrace) {
updatePlaybackPhase(active = reportedActive, nowMs = nowMs)
}
}
val playback = playbackActive
var justCalibrated = false
if (!playback && !calibrated) {
addAmbient(rms)
if (ambient.size >= calibrationFrames) {
freezeCalibration()
justCalibrated = true
}
}
if (!playback && (!calibrated || justCalibrated)) {
return RmsGateResult(
maybeSpeech = false,
detected = false,
rms = rms,
floor = quietFloor,
threshold = (quietFloor * thresholdMultiplier).coerceIn(
MIN_GENERATION_THRESHOLD_RMS,
MAX_THRESHOLD_RMS,
),
calibrating = !calibrated,
playbackGrace = false,
playback = false,
)
}
var threshold = if (playback) {
(quietFloor * thresholdMultiplier).coerceIn(
MIN_PLAYBACK_THRESHOLD_RMS,
MAX_THRESHOLD_RMS,
)
} else {
(quietFloor * thresholdMultiplier).coerceIn(
MIN_GENERATION_THRESHOLD_RMS,
MAX_THRESHOLD_RMS,
)
}
// Match upstream ambient drift: after initial calibration, keep the
// 90th-percentile floor current only while the room is quiet and no
// playback can contaminate it.
if (!playback && calibrated && !justCalibrated && rms < threshold) {
addAmbient(rms)
quietFloor = robustFloor(ambient)
threshold = (quietFloor * thresholdMultiplier).coerceIn(
MIN_GENERATION_THRESHOLD_RMS,
MAX_THRESHOLD_RMS,
)
}
val inPlaybackGrace = playbackStartedAtMs?.let { nowMs - it < playbackGraceMs } == true
val aboveRaw = rawSpeech && rms >= threshold && !inPlaybackGrace
val aboveConfirmed = confirmedSpeech && rms >= threshold && !inPlaybackGrace
decisions.addLast(aboveConfirmed)
while (decisions.size > decisionWindowFrames) decisions.removeAt(0)
val required = (decisionWindowFrames * requiredWindowRatio).roundToInt().coerceAtLeast(1)
val detected = aboveConfirmed && decisions.count { it } >= required
return RmsGateResult(
maybeSpeech = aboveRaw,
detected = detected,
rms = rms,
floor = quietFloor,
threshold = threshold,
calibrating = !playback && !calibrated,
playbackGrace = inPlaybackGrace,
playback = playback,
)
}
private fun freezeCalibration() {
if (!calibrated) {
quietFloor = robustFloor(ambient)
calibrated = true
}
}
private fun updatePlaybackPhase(active: Boolean, nowMs: Long) {
if (active == playbackActive) return
if (active) {
freezeCalibration()
val gapMs = playbackStoppedAtMs?.let { nowMs - it }
playbackStartedAtMs = if (gapMs == null || gapMs >= PLAYBACK_GRACE_REARM_GAP_MS) {
nowMs
} else {
null
}
playbackActive = true
decisions.clear()
} else {
playbackActive = false
playbackStartedAtMs = null
playbackStoppedAtMs = nowMs
decisions.clear()
}
}
private fun addAmbient(rms: Float) {
ambient.addLast(rms)
while (ambient.size > MAX_AMBIENT_FRAMES) ambient.removeAt(0)
}
private fun robustFloor(values: Collection<Float>): Float {
if (values.isEmpty()) return DEFAULT_QUIET_FLOOR_RMS
val sorted = values.sorted()
val percentileIndex = (ceil(sorted.size * 0.9).toInt() - 1).coerceIn(sorted.indices)
return sorted[percentileIndex].coerceAtLeast(MIN_QUIET_FLOOR_RMS)
}
private fun rms(frame: ShortArray): Float {
if (frame.isEmpty()) return 0f
var sum = 0.0
frame.forEach { sample ->
val value = sample.toDouble()
sum += value * value
}
return sqrt(sum / frame.size).toFloat()
}
companion object {
const val DEFAULT_THRESHOLD_MULTIPLIER = 3f
const val DEFAULT_PLAYBACK_GRACE_MS = 500L
internal const val DEFAULT_CALIBRATION_FRAMES = 14
internal const val DEFAULT_DECISION_WINDOW_FRAMES = 10
internal const val DEFAULT_REQUIRED_WINDOW_RATIO = 0.8f
internal const val MIN_PLAYBACK_THRESHOLD_RMS = 1_500f
internal const val MAX_THRESHOLD_RMS = 4_000f
internal const val MIN_GENERATION_THRESHOLD_RMS = 400f
internal const val DEFAULT_QUIET_FLOOR_RMS = 200f
internal const val MIN_QUIET_FLOOR_RMS = 200f
internal const val MAX_AMBIENT_FRAMES = 100
internal const val PLAYBACK_GRACE_REARM_GAP_MS = 1_000L
internal const val MIN_THRESHOLD_MULTIPLIER = 1f
internal const val MAX_THRESHOLD_MULTIPLIER = 8f
}
}
internal data class RmsGateResult(
val maybeSpeech: Boolean,
val detected: Boolean,
val rms: Float,
val floor: Float,
val threshold: Float,
val calibrating: Boolean,
val playbackGrace: Boolean,
val playback: Boolean,
)
@@ -8,6 +8,9 @@ import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.media.audiofx.NoiseSuppressor
import android.util.Log
import com.hermesandroid.relay.wake.MicrophoneLease
import com.hermesandroid.relay.wake.MicrophoneOwner
import com.hermesandroid.relay.wake.MicrophoneOwnershipCoordinator
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -57,6 +60,7 @@ class VoiceRecorder(
private val bufferLock = Any()
private val stopRequested = AtomicBoolean(false)
private var audioRecord: AudioRecord? = null
private var microphoneLease: MicrophoneLease? = null
private var echoCanceler: AcousticEchoCanceler? = null
private var noiseSuppressor: NoiseSuppressor? = null
private var currentOutputFile: File? = null
@@ -79,12 +83,21 @@ class VoiceRecorder(
releaseRecorder()
}
}
val lease = MicrophoneOwnershipCoordinator.tryAcquire(MicrophoneOwner.VoiceCapture)
?: throw IllegalStateException("Microphone is in use by another voice feature")
microphoneLease = lease
val minBuffer = AudioRecord.getMinBufferSize(
val minBuffer = try {
AudioRecord.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(SAMPLE_RATE / 10 * BYTES_PER_SAMPLE)
).coerceAtLeast(SAMPLE_RATE / 10 * BYTES_PER_SAMPLE)
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(lease)
microphoneLease = null
throw t
}
val outFile = File(context.cacheDir, "voice_rec_${System.currentTimeMillis()}.wav")
currentOutputFile = outFile
@@ -95,21 +108,29 @@ class VoiceRecorder(
stopRequested.set(false)
_amplitude.value = 0f
val recorder = AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer * 2)
.build()
val recorder = try {
AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build()
)
.setBufferSizeInBytes(minBuffer * 2)
.build()
} catch (t: Throwable) {
MicrophoneOwnershipCoordinator.release(lease)
microphoneLease = null
throw t
}
if (recorder.state != AudioRecord.STATE_INITIALIZED) {
recorder.release()
currentOutputFile = null
MicrophoneOwnershipCoordinator.release(lease)
microphoneLease = null
throw IllegalStateException("AudioRecord failed to initialize")
}
@@ -118,6 +139,8 @@ class VoiceRecorder(
} catch (e: Exception) {
recorder.release()
currentOutputFile = null
MicrophoneOwnershipCoordinator.release(lease)
microphoneLease = null
throw e
}
@@ -281,6 +304,8 @@ class VoiceRecorder(
try { record.release() } catch (_: Exception) { }
}
audioRecord = null
microphoneLease?.let(MicrophoneOwnershipCoordinator::release)
microphoneLease = null
readThread = null
readDone = null
}
@@ -1,24 +1,35 @@
package com.hermesandroid.relay.auth
import android.content.Context
import android.provider.Settings
import android.util.Log
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.BrokerEndpoint
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.replaceHermesReachCredential
import com.hermesandroid.relay.data.sameBrokerAuthority
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.isSafeProfileUiMeta
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
import com.hermesandroid.relay.network.relay.models.Envelope
import com.hermesandroid.relay.network.shared.InvalidCredentialException
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
@@ -48,6 +59,7 @@ data class ConnectionAuthSecrets(
val refreshToken: String? = null,
val deviceId: String? = null,
val apiKey: String? = null,
val profileApiKeys: Map<String, String> = emptyMap(),
val pairedSessionMetaJson: String? = null,
)
@@ -114,6 +126,7 @@ class AuthManager(
private const val KEY_REFRESH_TOKEN = "refresh_token"
private const val KEY_DEVICE_ID = "device_id"
private const val KEY_API_KEY = "api_server_key"
private const val KEY_PROFILE_API_KEYS = "profile_api_server_keys"
private const val HINT_API_KEY_PRESENT = "api_key_present"
private const val KEY_PAIRED_META = "paired_session_meta_json"
// Marker (in the connection-0 token store) recording that the one-shot
@@ -132,6 +145,29 @@ class AuthManager(
*/
const val CONNECTION_ID_LEGACY: String = "legacy"
internal fun encodeProfileApiKeys(keys: Map<String, String>): String =
Json.encodeToString(
keys.mapNotNull { (profile, key) ->
val normalizedProfile = profile.trim()
val normalizedKey = key.trim()
if (normalizedProfile.isBlank() || normalizedKey.isBlank()) null
else normalizedProfile to normalizedKey
}.toMap(),
)
internal fun decodeProfileApiKeys(raw: String?): Map<String, String> {
if (raw.isNullOrBlank()) return emptyMap()
return runCatching { Json.decodeFromString<Map<String, String>>(raw) }
.getOrDefault(emptyMap())
.mapNotNull { (profile, key) ->
val normalizedProfile = profile.trim()
val normalizedKey = key.trim()
if (normalizedProfile.isBlank() || normalizedKey.isBlank()) null
else normalizedProfile to normalizedKey
}
.toMap()
}
internal fun shouldPreservePairedSessionOnAuthFail(
currentState: AuthState,
rawReason: String,
@@ -173,6 +209,7 @@ class AuthManager(
refreshToken = store.getString(KEY_REFRESH_TOKEN),
deviceId = store.getString(KEY_DEVICE_ID),
apiKey = store.getString(KEY_API_KEY),
profileApiKeys = decodeProfileApiKeys(store.getString(KEY_PROFILE_API_KEYS)),
pairedSessionMetaJson = store.getString(KEY_PAIRED_META),
)
}
@@ -182,16 +219,47 @@ class AuthManager(
tokenStoreKey: String,
secrets: ConnectionAuthSecrets,
) {
val normalized = normalizeStoredSecrets(secrets)
withContext(Dispatchers.IO) {
val store = tokenStoreForBackup(context, tokenStoreKey)
writeOrRemove(store, KEY_SESSION_TOKEN, secrets.sessionToken)
writeOrRemove(store, KEY_REFRESH_TOKEN, secrets.refreshToken)
writeOrRemove(store, KEY_DEVICE_ID, secrets.deviceId)
writeOrRemove(store, KEY_API_KEY, secrets.apiKey)
writeOrRemove(store, KEY_PAIRED_META, secrets.pairedSessionMetaJson)
writeOrRemove(store, KEY_SESSION_TOKEN, normalized.sessionToken)
writeOrRemove(store, KEY_REFRESH_TOKEN, normalized.refreshToken)
writeOrRemove(store, KEY_DEVICE_ID, normalized.deviceId)
writeOrRemove(store, KEY_API_KEY, normalized.apiKey)
writeOrRemove(
store,
KEY_PROFILE_API_KEYS,
normalized.profileApiKeys
.takeIf { it.isNotEmpty() }
?.let(::encodeProfileApiKeys),
)
writeOrRemove(store, KEY_PAIRED_META, normalized.pairedSessionMetaJson)
}
}
/** Validate a backup fully before any existing encrypted state is replaced. */
fun validateStoredSecrets(secrets: ConnectionAuthSecrets) {
normalizeStoredSecrets(secrets)
}
private fun normalizeStoredSecrets(secrets: ConnectionAuthSecrets): ConnectionAuthSecrets =
secrets.copy(
sessionToken = secrets.sessionToken?.let {
normalizeCredentialForHeader(it, "Relay session credential")
}?.takeIf { it.isNotEmpty() },
refreshToken = secrets.refreshToken?.let {
normalizeCredentialForHeader(it, "Relay refresh credential")
}?.takeIf { it.isNotEmpty() },
apiKey = secrets.apiKey?.let {
normalizeCredentialForHeader(it, "API credential")
}?.takeIf { it.isNotEmpty() },
profileApiKeys = secrets.profileApiKeys
.mapValues { (_, value) ->
normalizeCredentialForHeader(value, "Profile API credential")
}
.filterValues { it.isNotEmpty() },
)
private fun tokenStoreForBackup(
context: Context,
tokenStoreKey: String,
@@ -247,6 +315,7 @@ class AuthManager(
?: return@mapNotNull null
val model = obj["model"]?.jsonPrimitive?.contentOrNull
?: "unknown"
val provider = obj["provider"]?.jsonPrimitive?.contentOrNull.orEmpty()
val description = obj["description"]?.jsonPrimitive?.contentOrNull
?: ""
val systemMessage = obj["system_message"]?.jsonPrimitive?.contentOrNull
@@ -266,9 +335,15 @@ class AuthManager(
?.jsonPrimitive?.intOrNull
val apiServerKeyPresent = obj["api_server_key_present"]
?.jsonPrimitive?.booleanOrNull ?: false
val isDefault = obj["is_default"]?.jsonPrimitive?.booleanOrNull ?: false
val hasAvatar = obj["has_avatar"]?.jsonPrimitive?.booleanOrNull ?: false
val uiMeta = (obj["ui_meta"] as? JsonObject)
?.takeIf(::isSafeProfileUiMeta)
?: JsonObject(emptyMap())
Profile(
name = name,
model = model,
provider = provider,
description = description,
systemMessage = systemMessage,
gatewayRunning = gatewayRunning,
@@ -279,6 +354,9 @@ class AuthManager(
apiServerHost = apiServerHost,
apiServerPort = apiServerPort,
apiServerKeyPresent = apiServerKeyPresent,
isDefault = isDefault,
hasAvatar = hasAvatar,
uiMeta = uiMeta,
)
}
}
@@ -290,6 +368,7 @@ class AuthManager(
private var _store: SessionTokenStore? = null
private val storeMutex = Mutex()
private val profileApiKeysMutex = Mutex()
/**
* The encrypted-store filename for this connection — shared by [store]
@@ -416,6 +495,7 @@ class AuthManager(
KEY_REFRESH_TOKEN,
KEY_DEVICE_ID,
KEY_API_KEY,
KEY_PROFILE_API_KEYS,
KEY_PAIRED_META,
)
var migrated = false
@@ -522,6 +602,12 @@ class AuthManager(
* Either way, we leave the previously-persisted list untouched.
*/
private var pendingEndpoints: List<EndpointCandidate>? = null
private var activeEndpointProvider: () -> EndpointCandidate? = { null }
/** Bind auth.ok route credentials to the transport that actually carried them. */
fun setActiveEndpointProvider(provider: () -> EndpointCandidate?) {
activeEndpointProvider = provider
}
/**
* Server-advertised agent profiles from the `auth.ok` payload's
@@ -549,6 +635,8 @@ class AuthManager(
*/
private val _apiKeyPresent = MutableStateFlow(false)
val apiKeyPresent: StateFlow<Boolean> = _apiKeyPresent.asStateFlow()
private val _apiKeyError = MutableStateFlow<String?>(null)
val apiKeyError: StateFlow<String?> = _apiKeyError.asStateFlow()
init {
// Register as system channel handler for auth messages
@@ -568,19 +656,40 @@ class AuthManager(
val s = store()
val existingToken = s.getString(KEY_SESSION_TOKEN)
if (existingToken != null) {
_authState.value = AuthState.Paired(existingToken)
_currentPairedSession.value = loadStoredMetadata(existingToken)
Log.i(
TAG,
"init: hydrated existing session_token=${existingToken.take(8)}… " +
"→ authState=Paired (stale-at-startup unless this is a real continuous session)"
)
runCatching {
normalizeCredentialForHeader(existingToken, "Relay session credential")
.also { require(it.isNotEmpty()) }
}.onSuccess { normalized ->
if (normalized != existingToken) s.putString(KEY_SESSION_TOKEN, normalized)
_authState.value = AuthState.Paired(normalized)
_currentPairedSession.value = loadStoredMetadata(normalized)
Log.i(TAG, "init: hydrated existing session credential")
}.onFailure {
_authState.value = AuthState.Failed(
"Saved Relay credential is malformed. Re-pair this connection.",
)
Log.w(TAG, "init: rejected malformed saved Relay credential")
}
} else {
Log.i(TAG, "init: no stored session_token → authState stays Unpaired")
}
// Converge the plain api-key-present hint with the decrypted
// truth (also repairs a hint that predates legacy migration).
recordApiKeyHint(!s.getString(KEY_API_KEY).isNullOrBlank())
val storedApiKey = s.getString(KEY_API_KEY)
if (storedApiKey != null) {
runCatching {
normalizeCredentialForHeader(storedApiKey, "API credential")
.also { require(it.isNotEmpty()) }
}.onSuccess { normalized ->
if (normalized != storedApiKey) s.putString(KEY_API_KEY, normalized)
_apiKeyError.value = null
}.onFailure {
_apiKeyError.value =
"Saved API credential is malformed. Replace or clear it."
Log.w(TAG, "init: rejected malformed saved API credential")
}
}
recordApiKeyHint(!storedApiKey.isNullOrBlank())
}
}
}
@@ -596,7 +705,7 @@ class AuthManager(
val now = System.currentTimeMillis() / 1000L
val defaults = PairedSession(
token = token,
deviceName = android.os.Build.MODEL,
deviceName = relayDeviceName(),
expiresAt = null,
grants = emptyMap(),
transportHint = null,
@@ -616,7 +725,7 @@ class AuthManager(
val transportHint = obj["transport_hint"]?.jsonPrimitive?.contentOrNull
val firstSeen = obj["first_seen"]?.jsonPrimitive?.longOrNull ?: now
val deviceName = obj["device_name"]?.jsonPrimitive?.contentOrNull
?: android.os.Build.MODEL
?: relayDeviceName()
PairedSession(
token = token,
@@ -715,6 +824,26 @@ class AuthManager(
})
}
private fun JsonObjectBuilder.putRelayDeviceIdentity() {
val model = android.os.Build.MODEL.orEmpty().ifBlank { "Android device" }
val deviceName = relayDeviceName()
put("device_name", deviceName)
put("device_hostname", deviceName)
put("device_model", model)
put("device_platform", "Android ${android.os.Build.VERSION.RELEASE}")
put("client_surface", "android")
put("device_form_factor", "phone")
}
private fun relayDeviceName(): String {
val configured = runCatching {
Settings.Global.getString(context.contentResolver, "device_name")
}.getOrNull()?.trim().orEmpty()
return configured.ifBlank {
android.os.Build.MODEL.orEmpty().ifBlank { "Android device" }
}
}
/**
* Send auth envelope when connection is established.
*
@@ -737,10 +866,20 @@ class AuthManager(
val deviceId = getDeviceId()
val payload = when (currentState) {
is AuthState.Paired -> {
val refreshToken = store().getString(KEY_REFRESH_TOKEN)
val refreshToken = store().getString(KEY_REFRESH_TOKEN)?.let { raw ->
runCatching {
normalizeCredentialForHeader(raw, "Relay refresh credential")
}.getOrElse {
_authState.value = AuthState.Failed(
"Saved Relay credential is malformed. Re-pair this connection.",
)
Log.w(TAG, "authenticate: rejected malformed refresh credential")
return@launch
}
}
Log.i(
TAG,
"authenticate: sending session_token (state=Paired, token=${currentState.token.take(8)}…, " +
"authenticate: sending saved session credential (state=Paired, " +
"refresh=${!refreshToken.isNullOrBlank()})"
)
buildJsonObject {
@@ -749,7 +888,7 @@ class AuthManager(
put("refresh_token", refreshToken)
}
put("device_id", deviceId)
put("device_name", android.os.Build.MODEL)
putRelayDeviceIdentity()
putRelayClientSupports()
}
}
@@ -765,7 +904,7 @@ class AuthManager(
buildJsonObject {
put("pairing_code", codeToSend)
put("device_id", deviceId)
put("device_name", android.os.Build.MODEL)
putRelayDeviceIdentity()
putRelayClientSupports()
pendingTtlSeconds?.let { put("ttl_seconds", it) }
pendingGrants?.let { grants ->
@@ -928,10 +1067,26 @@ class AuthManager(
// --- API Key storage (for direct Hermes API Server auth) ---
suspend fun getApiKey(): String? = store().getString(KEY_API_KEY)
suspend fun getApiKey(): String? {
val raw = store().getString(KEY_API_KEY) ?: return null
return runCatching {
normalizeCredentialForHeader(raw, "API credential")
.takeIf { it.isNotEmpty() }
}.onSuccess {
_apiKeyError.value = null
}.onFailure {
_apiKeyError.value = "Saved API credential is malformed. Replace or clear it."
Log.w(TAG, "getApiKey: rejected malformed saved API credential")
}.getOrNull()
}
suspend fun setApiKey(key: String) {
val trimmed = key.trim()
val trimmed = runCatching {
normalizeCredentialForHeader(key, "API credential")
}.getOrElse {
_apiKeyError.value = "API credentials must be a single line."
throw it
}
val s = store()
if (trimmed.isBlank()) {
s.remove(KEY_API_KEY)
@@ -940,11 +1095,34 @@ class AuthManager(
s.putString(KEY_API_KEY, trimmed)
recordApiKeyHint(true)
}
_apiKeyError.value = null
}
suspend fun clearApiKey() {
store().remove(KEY_API_KEY)
recordApiKeyHint(false)
_apiKeyError.value = null
}
suspend fun getProfileApiKey(profileName: String): String? =
decodeProfileApiKeys(store().getString(KEY_PROFILE_API_KEYS))[profileName.trim()]
suspend fun setProfileApiKey(profileName: String, key: String) {
val normalizedProfile = profileName.trim()
require(normalizedProfile.isNotBlank()) { "Profile name must not be blank" }
profileApiKeysMutex.withLock {
val tokenStore = store()
val keys = decodeProfileApiKeys(tokenStore.getString(KEY_PROFILE_API_KEYS)).toMutableMap()
val normalizedKey = normalizeCredentialForHeader(key, "Profile API credential")
if (normalizedKey.isBlank()) keys.remove(normalizedProfile)
else keys[normalizedProfile] = normalizedKey
if (keys.isEmpty()) tokenStore.remove(KEY_PROFILE_API_KEYS)
else tokenStore.putString(KEY_PROFILE_API_KEYS, encodeProfileApiKeys(keys))
}
}
suspend fun clearProfileApiKey(profileName: String) {
setProfileApiKey(profileName, "")
}
val isPaired: Boolean
@@ -954,7 +1132,10 @@ class AuthManager(
scope.launch {
try {
val payload = envelope.payload
val token = payload["session_token"]?.jsonPrimitive?.contentOrNull
val token = payload["session_token"]?.jsonPrimitive?.contentOrNull?.let { raw ->
normalizeCredentialForHeader(raw, "Relay session credential")
.takeIf { it.isNotEmpty() }
}
if (token == null) {
Log.w(
@@ -965,18 +1146,20 @@ class AuthManager(
}
if (token != null) {
applyBrokerRouteCredential(payload)
val s = store()
s.putString(KEY_SESSION_TOKEN, token)
val refreshToken = payload["refresh_token"]
?.jsonPrimitive
?.contentOrNull
?.takeIf { it.isNotBlank() }
?.let { normalizeCredentialForHeader(it, "Relay refresh credential") }
?.takeIf { it.isNotEmpty() }
if (refreshToken != null) {
s.putString(KEY_REFRESH_TOKEN, refreshToken)
Log.i(TAG, "handleAuthOk: stored rotated refresh token")
}
_authState.value = AuthState.Paired(token)
Log.i(TAG, "handleAuthOk: Paired(token=${token.take(8)}…)")
Log.i(TAG, "handleAuthOk: paired with server-issued session credential")
// Per-connection signal for socket-scoped consumers (e.g.
// re-sending proactive.subscribe). Fires on every auth.ok.
_authOkEvents.tryEmit(Unit)
@@ -1010,7 +1193,7 @@ class AuthManager(
val paired = PairedSession(
token = token,
deviceName = android.os.Build.MODEL,
deviceName = relayDeviceName(),
expiresAt = expiresAt,
grants = grantsMap,
transportHint = transportHint,
@@ -1069,10 +1252,56 @@ class AuthManager(
// handler is exactly why the broken `_sessionLabels` parser
// (stringifying object entries) sat undetected for so long.
Log.w(TAG, "auth.ok parse failed: ${e.message}", e)
if (e is InvalidCredentialException) {
_authState.value = AuthState.Failed(
"Relay returned a malformed credential. Re-pair this connection.",
)
}
}
}
}
private suspend fun applyBrokerRouteCredential(payload: JsonObject) {
val active = activeEndpointProvider()?.takeIf { it.hasHermesReach() } ?: return
val current = active.broker ?: return
// Fresh pairing is scoped by pendingEndpoints; reconnect rotation is
// accepted only by this connection-scoped AuthManager's live session.
if (pendingEndpoints == null && _authState.value !is AuthState.Paired) return
val credential = payload["route_credential"] as? JsonObject ?: return
if (credential["kind"]?.jsonPrimitive?.contentOrNull != "broker_route") return
val brokerUrl = credential["broker_url"]?.jsonPrimitive?.contentOrNull ?: return
val hostId = credential["host_id"]?.jsonPrimitive?.contentOrNull ?: return
if (!sameBrokerAuthority(brokerUrl, current.url) || hostId != current.hostId) {
Log.w(TAG, "Ignoring broker route credential that does not match the active paired route")
return
}
val replacement = BrokerEndpoint(
url = current.url,
protocolVersion = current.protocolVersion,
hostId = current.hostId,
credentialKind = "route",
token = credential["token"]?.jsonPrimitive?.contentOrNull?.let {
runCatching {
normalizeCredentialForHeader(it, "Hermes Reach credential")
}.getOrElse {
Log.w(TAG, "Ignoring malformed Hermes Reach route credential")
return
}
} ?: return,
expiresAt = credential["expires_at"]?.jsonPrimitive?.longOrNull,
)
val validated = active.copy(broker = replacement).takeIf { it.hasHermesReach() } ?: return
val deviceId = getDeviceId()
val source = pendingEndpoints
?: PairingPreferences.getDeviceEndpoints(context, deviceId).first()
val updated = replaceHermesReachCredential(source, current, validated)
if (updated == source) return
if (pendingEndpoints != null) pendingEndpoints = updated
else PairingPreferences.setDeviceEndpoints(context, deviceId, updated)
Log.i(TAG, "Accepted a durable Hermes Reach route credential for the active paired route")
}
private fun handleAuthFail(envelope: Envelope) {
try {
val rawReason = envelope.payload["reason"]?.jsonPrimitive?.contentOrNull
@@ -90,12 +90,28 @@ class CertPinStore(private val context: Context) {
if (pins.isEmpty()) return CertificatePinner.DEFAULT
val builder = CertificatePinner.Builder()
for ((hostPort, pin) in pins) {
val host = hostPort.substringBefore(':')
val host = hostPort.substringBeforeLast(':')
builder.add(host, pin)
}
return builder.build()
}
/**
* Build a pinner for one exact URL authority. CertificatePinner keys by
* hostname only, so adding every stored host:port entry to one client
* accidentally lets a pin learned on one port govern another port.
*/
fun buildPinnerSnapshotFor(url: String): CertificatePinner {
val hostPort = hostPortFromUrl(url) ?: return CertificatePinner.DEFAULT
val pin = getPinsBlocking()[hostPort] ?: return CertificatePinner.DEFAULT
val host = runCatching { URI(url.trim()).host }.getOrNull()
?.takeIf { it.isNotBlank() }
?: return CertificatePinner.DEFAULT
return CertificatePinner.Builder()
.add(host, pin)
.build()
}
/**
* Record a pin for a host. Called from the WebSocket listener's `onOpen`
* when we have a successful connection and can read the peer certs from
@@ -74,6 +74,14 @@ data class PairedDeviceInfo(
val deviceName: String = "",
@SerialName("device_id")
val deviceId: String = "",
@SerialName("device_model")
val deviceModel: String = "",
@SerialName("device_platform")
val devicePlatform: String = "",
@SerialName("client_surface")
val clientSurface: String = "",
@SerialName("device_form_factor")
val deviceFormFactor: String = "",
@SerialName("created_at")
val createdAt: Double? = null,
@SerialName("last_seen")
@@ -15,25 +15,22 @@ import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.hermesandroid.relay.MainActivity
import com.hermesandroid.relay.R
import com.hermesandroid.relay.accessibility.HermesAccessibilityService
/**
* Phase 3 — safety-rails `bridge-safety-rails`
*
* Canonical "turn the bridge off after idle" unit of work. Not a real
* Canonical timed-screen-expiry notification unit. Not a real
* `androidx.work.CoroutineWorker` — the project intentionally does not
* depend on androidx.work — but its shape mirrors one exactly: a single
* suspend [run] method that performs the work and returns.
*
* Why this pattern instead of dropping a WorkManager dep:
* - Auto-disable is a pure in-memory decision: the toggle lives in our
* own DataStore, no inter-process scheduling is required.
* - Capability expiry is persisted as absolute wall-clock timestamps;
* the in-process job exists only to prune promptly and notify.
* - Android's AlarmManager / WorkManager are needed when the work must
* survive process death. For bridge, process death already implies
* the service is disconnected and the master toggle re-evaluates
* fresh on the next launch. So a coroutine-owned `delay` does it.
* - Every command reschedules the timer, so the idle window is always
* reset against wall clock. No drift concerns.
* survive process death. Authorization itself does survive because the
* command boundary compares persisted expiry with the current clock.
* - Only timed screen inspection/control commands reset the timer.
*
* When WorkManager is added later (say, if notif-listener needs background-posted
* notifications on a schedule), this file is a natural upgrade point:
@@ -51,17 +48,10 @@ class AutoDisableWorker(private val context: Context) {
}
/**
* Execute the auto-disable: flip the master toggle off and post a
* one-shot "bridge paused" notification. Idempotent — safe to call
* twice (the second call just re-writes the same DataStore value
* and overrides the existing notification).
* Post a one-shot notification after timed screen authority is revoked.
* Idempotent — a repeated call replaces the existing notification.
*/
suspend fun run() {
try {
HermesAccessibilityService.setMasterEnabled(context, false)
} catch (t: Throwable) {
Log.w(TAG, "run: failed to flip master toggle", t)
}
postNotification()
}
@@ -92,8 +82,7 @@ class AutoDisableWorker(private val context: Context) {
.setContentTitle(context.getString(R.string.bridge_notification_auto_disabled_title))
.setContentText(context.getString(R.string.bridge_notification_auto_disabled_body))
.setStyle(NotificationCompat.BigTextStyle().bigText(
"Hermes bridge was idle for too long, so device control has been turned off " +
"automatically. Open the Bridge tab to turn it back on if you still need it."
context.getString(R.string.bridge_notification_auto_disabled_body)
))
.setContentIntent(tapPending)
.setAutoCancel(true)
@@ -115,7 +104,7 @@ class AutoDisableWorker(private val context: Context) {
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT,
).apply {
description = "Fires once when the bridge auto-disables after being idle."
description = "Fires once when timed Bridge screen access expires after idle."
setShowBadge(false)
}
nm.createNotificationChannel(channel)
@@ -0,0 +1,113 @@
package com.hermesandroid.relay.bridge
import kotlinx.serialization.Serializable
/** Stable, auditable authority groups for every phone-side Bridge command. */
@Serializable
enum class BridgeCapability(val wireId: String, val timed: Boolean) {
DEVICE_INFO("device_info", false),
CONTACTS_READ("contacts_read", false),
LOCATION_READ("location_read", false),
CLIPBOARD_READ("clipboard_read", false),
CLIPBOARD_WRITE("clipboard_write", false),
MEDIA_CONTROL("media_control", false),
COMMUNICATIONS("communications", false),
OUTBOUND_SHARING("outbound_sharing", false),
SCREEN_INSPECTION("screen_inspection", true),
SCREEN_CONTROL("screen_control", true),
}
enum class BridgeCapabilityGrant { EXEMPT, PERMANENT, TIMED }
data class BridgeCommandAuthority(
val capability: BridgeCapability? = null,
val grant: BridgeCapabilityGrant,
)
/**
* Closed command registry. Authorization is resolved from both path and HTTP
* method so method-split commands such as clipboard read/write cannot share a
* grant accidentally. Unknown paths and method combinations return null and
* must be denied by the command boundary.
*
* Composite Python tools (android_navigate/android_macro) do not get a broad
* grant: every primitive route they dispatch is checked here independently.
*/
object BridgeCommandRegistry {
private data class Key(val method: String, val path: String)
private fun permanent(capability: BridgeCapability) =
BridgeCommandAuthority(capability, BridgeCapabilityGrant.PERMANENT)
private fun timed(capability: BridgeCapability) =
BridgeCommandAuthority(capability, BridgeCapabilityGrant.TIMED)
private val exempt = BridgeCommandAuthority(grant = BridgeCapabilityGrant.EXEMPT)
private val routes: Map<Key, BridgeCommandAuthority> = buildMap {
fun route(method: String, path: String, authority: BridgeCommandAuthority) {
put(Key(method, path), authority)
}
route("GET", "/ping", exempt)
route("POST", "/setup", exempt)
route("POST", "/wait", exempt)
route("GET", "/current_app", permanent(BridgeCapability.DEVICE_INFO))
route("GET", "/get_apps", permanent(BridgeCapability.DEVICE_INFO))
route("GET", "/apps", permanent(BridgeCapability.DEVICE_INFO))
route("POST", "/search_contacts", permanent(BridgeCapability.CONTACTS_READ))
route("GET", "/location", permanent(BridgeCapability.LOCATION_READ))
route("GET", "/clipboard", permanent(BridgeCapability.CLIPBOARD_READ))
route("POST", "/clipboard", permanent(BridgeCapability.CLIPBOARD_WRITE))
route("POST", "/media", permanent(BridgeCapability.MEDIA_CONTROL))
route("POST", "/call", permanent(BridgeCapability.COMMUNICATIONS))
route("POST", "/send_sms", permanent(BridgeCapability.COMMUNICATIONS))
route("POST", "/share_media", permanent(BridgeCapability.OUTBOUND_SHARING))
route("POST", "/send_mms", permanent(BridgeCapability.OUTBOUND_SHARING))
listOf("/screen", "/screenshot", "/screen_hash", "/events").forEach {
route("GET", it, timed(BridgeCapability.SCREEN_INSPECTION))
}
listOf("/find_nodes", "/describe_node", "/diff_screen", "/events/stream").forEach {
route("POST", it, timed(BridgeCapability.SCREEN_INSPECTION))
}
listOf(
"/tap", "/tap_text", "/long_press", "/type", "/swipe", "/drag",
"/scroll", "/press_key", "/open_app", "/return_to_hermes",
"/send_intent", "/broadcast",
).forEach { route("POST", it, timed(BridgeCapability.SCREEN_CONTROL)) }
}
fun resolve(path: String, method: String): BridgeCommandAuthority? =
routes[Key(method.trim().uppercase(), path.trim())]
fun registeredRoutes(): Set<Pair<String, String>> =
routes.keys.mapTo(linkedSetOf()) { it.method to it.path }
}
@Serializable
data class BridgeCapabilityPolicy(
val schemaVersion: Int = CURRENT_SCHEMA_VERSION,
val permanentGrants: Set<BridgeCapability> = emptySet(),
val timedExpiriesMs: Map<BridgeCapability, Long> = emptyMap(),
) {
companion object {
const val CURRENT_SCHEMA_VERSION = 1
/** Explicit sentinel for a user-selected "Until turned off" lease. */
const val NEVER_EXPIRES_AT_MS: Long = Long.MAX_VALUE
}
fun allows(capability: BridgeCapability, nowMs: Long): Boolean =
if (capability.timed) {
(timedExpiriesMs[capability] ?: 0L) > nowMs
} else {
capability in permanentGrants
}
fun expiryFor(capability: BridgeCapability): Long? = timedExpiriesMs[capability]
fun isUnlimited(capability: BridgeCapability): Boolean =
timedExpiriesMs[capability] == NEVER_EXPIRES_AT_MS
}
@@ -4,6 +4,7 @@ import android.content.Context
import android.util.Log
import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
import com.hermesandroid.relay.data.BridgeSafetySettings
import com.hermesandroid.relay.data.BridgeCapabilityPolicyRepository
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -14,6 +15,8 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
@@ -25,8 +28,8 @@ import java.util.concurrent.atomic.AtomicLong
/**
* Phase 3 — safety-rails `bridge-safety-rails`
*
* Central enforcement point for Tier 5 safety: per-app blocklist, destructive
* verb confirmation, and idle-based auto-disable. Owned as a singleton-per-
* Central enforcement point for Tier 5 safety: connection-scoped capabilities,
* per-app blocklist, destructive confirmation, and timed screen access. Owned as a singleton-per-
* process by [ConnectionViewModel] and injected into [BridgeCommandHandler].
*
* # Integration surface
@@ -47,9 +50,9 @@ import java.util.concurrent.atomic.AtomicLong
* reacts, which is exactly the UX we want (the server sees a slow
* response, not a denial race).
*
* - [rescheduleAutoDisable] — every accepted command bumps the idle timer
* forward; after [BridgeSafetySettings.autoDisableMinutes] of silence
* the master toggle flips off and a one-shot notification fires.
* - [rescheduleAutoDisable] — accepted timed screen commands bump the idle
* expiry forward; after [BridgeSafetySettings.autoDisableMinutes] of
* silence only timed screen authority is revoked and a notification fires.
* [cancelAutoDisable] cancels the pending timer (called when the master
* toggle flips off manually, so we don't race the timer against the
* user).
@@ -71,15 +74,14 @@ import java.util.concurrent.atomic.AtomicLong
* The Android app does not depend on androidx.work. [AutoDisableWorker]
* documents the canonical pattern, but the live path is a coroutine
* `Job` owned by this manager, delayed by the configured minutes. This is
* acceptable because we are the in-memory owner of the master-toggle flow
* — no inter-process or cross-restart scheduling is needed. On process
* death the master toggle is simply evaluated fresh from DataStore, and
* any command not explicitly sent within the idle window never actually
* happens because the app isn't running.
* acceptable because authorization stores an absolute expiry in DataStore.
* After process death or reconnect, the command boundary compares that expiry
* to wall clock and denies stale authority even if the notification job did not run.
*/
class BridgeSafetyManager(
context: Context,
private val scope: CoroutineScope,
private val activeConnectionId: StateFlow<String?>,
) {
companion object {
private const val TAG = "BridgeSafetyMgr"
@@ -94,10 +96,14 @@ class BridgeSafetyManager(
*/
fun peek(): BridgeSafetyManager? = INSTANCE
fun install(context: Context, scope: CoroutineScope): BridgeSafetyManager {
fun install(
context: Context,
scope: CoroutineScope,
activeConnectionId: StateFlow<String?>,
): BridgeSafetyManager {
val existing = INSTANCE
if (existing != null) return existing
val created = BridgeSafetyManager(context.applicationContext, scope)
val created = BridgeSafetyManager(context.applicationContext, scope, activeConnectionId)
INSTANCE = created
return created
}
@@ -105,6 +111,10 @@ class BridgeSafetyManager(
private val appContext: Context = context.applicationContext
private val prefsRepo = BridgeSafetyPreferencesRepository(appContext)
private val capabilityRepo = BridgeCapabilityPolicyRepository(appContext)
private val _activeCapabilityPolicy = MutableStateFlow(BridgeCapabilityPolicy())
val activeCapabilityPolicy: StateFlow<BridgeCapabilityPolicy> =
_activeCapabilityPolicy.asStateFlow()
/** Latest settings snapshot — UI + checks read this via [settings]. */
private val _settings = MutableStateFlow(BridgeSafetySettings())
@@ -140,12 +150,12 @@ class BridgeSafetyManager(
private val pendingConfirmations = ConcurrentHashMap<Long, PendingConfirmation>()
private val nextRequestId = AtomicLong(0L)
/** Coroutine job that fires auto-disable after idle. */
/** Coroutine job that prunes timed screen authority after idle. */
@Volatile
private var autoDisableJob: Job? = null
/**
* Remaining time (epoch millis) for the current auto-disable job, or
* Remaining time (epoch millis) for current timed screen authority, or
* null when idle. BridgeSafetySummaryCard reads this as a countdown.
*/
private val _autoDisableAtMs = MutableStateFlow<Long?>(null)
@@ -167,6 +177,100 @@ class BridgeSafetyManager(
trustedHydrated = true
}
}
scope.launch {
activeConnectionId.collectLatest { connectionId ->
schedulePersistedExpiry(connectionId)
capabilityRepo.policy(connectionId).collect { policy ->
_activeCapabilityPolicy.value = policy
}
}
}
}
data class CapabilityAuthorization(
val allowed: Boolean,
val authority: BridgeCommandAuthority? = null,
val errorCode: String? = null,
)
fun capabilityPolicy(connectionId: String?): Flow<BridgeCapabilityPolicy> =
capabilityRepo.policy(connectionId)
suspend fun authorizeCapability(
path: String,
method: String,
nowMs: Long = System.currentTimeMillis(),
): CapabilityAuthorization {
val authority = BridgeCommandRegistry.resolve(path, method)
?: return CapabilityAuthorization(false, errorCode = "unknown_bridge_command")
if (authority.grant == BridgeCapabilityGrant.EXEMPT) {
return CapabilityAuthorization(true, authority)
}
val connectionId = activeConnectionId.value
?: return CapabilityAuthorization(false, authority, "bridge_policy_unbound")
val capability = authority.capability
?: return CapabilityAuthorization(false, authority, "bridge_policy_invalid")
val policy = capabilityRepo.snapshot(connectionId)
return if (policy.allows(capability, nowMs)) {
CapabilityAuthorization(true, authority)
} else {
CapabilityAuthorization(
false,
authority,
if (capability.timed) "bridge_capability_expired" else "bridge_capability_denied",
)
}
}
suspend fun setPermanentCapability(
connectionId: String?,
capability: BridgeCapability,
allowed: Boolean,
) {
capabilityRepo.setPermanent(connectionId, capability, allowed)
}
suspend fun replacePermanentCapabilities(
connectionId: String?,
capabilities: Set<BridgeCapability>,
) {
capabilityRepo.replacePermanent(connectionId, capabilities)
}
suspend fun setTimedCapability(
connectionId: String?,
capability: BridgeCapability,
allowed: Boolean,
) {
if (!allowed) {
capabilityRepo.revoke(connectionId, capability)
if (capability == BridgeCapability.SCREEN_CONTROL) {
prefsRepo.setUnattendedAccessEnabled(false)
}
schedulePersistedExpiry(connectionId)
return
}
val fireAt = System.currentTimeMillis() + currentSettings().autoDisableMinutes * 60_000L
capabilityRepo.grantTimed(connectionId, capability, fireAt)
schedulePersistedExpiry(connectionId)
}
suspend fun replaceTimedCapabilities(
connectionId: String?,
capabilities: Set<BridgeCapability>,
durationMinutes: Int,
unlimited: Boolean = false,
) {
val fireAt = if (unlimited) {
BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
} else {
System.currentTimeMillis() + durationMinutes * 60_000L
}
capabilityRepo.replaceTimed(connectionId, capabilities, fireAt)
if (BridgeCapability.SCREEN_CONTROL !in capabilities) {
prefsRepo.setUnattendedAccessEnabled(false)
}
schedulePersistedExpiry(connectionId)
}
// ── Blocklist ────────────────────────────────────────────────────────
@@ -307,26 +411,35 @@ class BridgeSafetyManager(
pending.deferred.complete(allowed)
}
// ── Auto-disable timer ───────────────────────────────────────────────
// ── Timed screen-access expiry ──────────────────────────────────────
/**
* Cancel any pending timer and arm a fresh one. Called on every accepted
* bridge command — an actively-used bridge never auto-disables.
* Refresh active timed grants and arm their shared idle expiry. Permanent
* capability activity never calls this method.
*/
fun rescheduleAutoDisable() {
val connectionId = activeConnectionId.value ?: return
val minutes = _settings.value.autoDisableMinutes
val delayMs = minutes * 60_000L
val fireAt = System.currentTimeMillis() + delayMs
val fireAt = System.currentTimeMillis() + minutes * 60_000L
autoDisableJob?.cancel()
_autoDisableAtMs.value = fireAt
autoDisableJob = (scope + SupervisorJob()).launch {
try {
val snapshot = capabilityRepo.snapshot(connectionId)
val nowMs = System.currentTimeMillis()
val finite = snapshot.timedExpiriesMs.filterValues {
it != BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS && it > nowMs
}
if (finite.isEmpty()) {
_autoDisableAtMs.value = null
return@launch
}
capabilityRepo.refreshActiveTimed(connectionId, fireAt)
_autoDisableAtMs.value = fireAt
val delayMs = (fireAt - System.currentTimeMillis()).coerceAtLeast(0L)
delay(delayMs)
Log.i(TAG, "Auto-disable fired after $minutes min of idle")
// Hand off to the canonical worker so both code paths look
// identical from a behavioral standpoint (notification +
// master-toggle flip).
Log.i(TAG, "Timed Bridge capabilities expired after $minutes min of idle")
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
clearUnattendedIfControlEnded(connectionId)
AutoDisableWorker(appContext).run()
} catch (_: Throwable) {
// Cancellation is expected on reschedule — swallow quietly.
@@ -342,6 +455,48 @@ class BridgeSafetyManager(
_autoDisableAtMs.value = null
}
fun revokeTimedCapabilities() {
val connectionId = activeConnectionId.value ?: return
cancelAutoDisable()
scope.launch {
capabilityRepo.revokeTimed(connectionId)
prefsRepo.setUnattendedAccessEnabled(false)
}
}
private suspend fun schedulePersistedExpiry(connectionId: String?) {
autoDisableJob?.cancel()
val policy = capabilityRepo.snapshot(connectionId)
val nextExpiry = policy.timedExpiriesMs.values
.filter { it != BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS }
.maxOrNull()
if (nextExpiry == null) {
_autoDisableAtMs.value = null
return
}
if (nextExpiry <= System.currentTimeMillis()) {
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
clearUnattendedIfControlEnded(connectionId)
_autoDisableAtMs.value = null
return
}
_autoDisableAtMs.value = nextExpiry
autoDisableJob = (scope + SupervisorJob()).launch {
delay((nextExpiry - System.currentTimeMillis()).coerceAtLeast(0L))
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
clearUnattendedIfControlEnded(connectionId)
AutoDisableWorker(appContext).run()
if (activeConnectionId.value == connectionId) _autoDisableAtMs.value = null
}
}
private suspend fun clearUnattendedIfControlEnded(connectionId: String?) {
val policy = capabilityRepo.snapshot(connectionId)
if (!policy.allows(BridgeCapability.SCREEN_CONTROL, System.currentTimeMillis())) {
prefsRepo.setUnattendedAccessEnabled(false)
}
}
// ── Internals ────────────────────────────────────────────────────────
/**
@@ -242,11 +242,9 @@ object UnattendedAccessManager {
* returns [WakeOutcome.Success] / [SuccessNoKeyguardChange] /
* [KeyguardBlocked] depending on the dismiss attempt outcome.
*
* The wake lock auto-releases via the platform's 30s timeout — we
* don't release explicitly per call because the bridge command may
* take several gestures to complete and we want one continuous
* wake-up, not a stutter. [release] is provided for the master
* toggle off path.
* The caller must pair each successful acquire with [releaseAfterAction].
* The platform's 30s timeout remains a crash/stall backstop, not the normal
* lifetime. Nested or concurrent commands share the ref-counted lock.
*
* # Compatibility shim
*
@@ -300,6 +298,22 @@ object UnattendedAccessManager {
return requestDismiss()
}
/** Release one command's ownership without disturbing concurrent actions. */
fun releaseAfterAction() {
synchronized(countLock) {
if (lockCount <= 0) return
lockCount -= 1
if (lockCount == 0) {
val lock = wakeLock ?: return
try {
if (lock.isHeld) lock.release()
} catch (t: Throwable) {
Log.w(TAG, "wakeLock.release threw: ${t.message}")
}
}
}
}
/**
* Synchronous keyguard dismiss attempt. Returns:
* - [WakeOutcome.SuccessNoKeyguardChange] when there's no keyguard
@@ -3,10 +3,10 @@ package com.hermesandroid.relay.data
/**
* Shared profile/personality display and request identity helpers.
*
* A null profile name is the app's explicit "Server default" state. The
* relay also advertises the root Hermes config as a synthetic profile named
* "default"; for request/session identity that row is an alias of server
* default so it does not split chat, voice, or session scope.
* A null profile name is the app's explicit "Server default" state. It is
* intentionally distinct from a real profile whose name is literally
* `default`: the former follows the server's sticky default, while the latter
* explicitly addresses the root profile.
*/
object AgentDisplay {
const val SERVER_DEFAULT_PROFILE_KEY: String = "__server_default__"
@@ -16,17 +16,16 @@ object AgentDisplay {
"hermes agent",
)
// Only an EXPLICIT pick drives request/session identity. The advertised
// "default" profile is an alias for server default, so falling back to it
// here would split chat, voice, or session scope.
// Only an explicit pick drives request identity. Server default is the null
// selection; a named `default` profile is an ordinary explicit pick.
@Suppress("UNUSED_PARAMETER")
fun effectiveProfile(
selectedProfile: Profile?,
profiles: List<Profile>,
): Profile? = selectedProfile
// Display can use the synthetic default profile's metadata without making
// it a request/session override. Verbose SOUL summaries are filtered by
// Display can use the root default profile's metadata without making it a
// request/session override. Verbose SOUL summaries are filtered by
// profileDisplayName below, so this is safe for headers/cards.
fun effectiveDisplayProfile(
selectedProfile: Profile?,
@@ -39,7 +38,7 @@ object AgentDisplay {
?.let { activeName ->
profiles.firstOrNull { it.name.equals(activeName, ignoreCase = true) }
}
?: profiles.firstOrNull { isServerDefaultAlias(it.name) }
?: profiles.firstOrNull { it.name.equals("default", ignoreCase = true) }
}
// The NAME goes in the name slot. Non-default profiles use their profile
@@ -48,7 +47,7 @@ object AgentDisplay {
// verbose SOUL summary.
fun profileDisplayName(profile: Profile?): String? {
if (profile == null) return null
if (isServerDefaultAlias(profile.name)) {
if (profile.name.equals("default", ignoreCase = true)) {
return defaultProfileDisplayName(profile)
}
return when {
@@ -135,22 +134,18 @@ object AgentDisplay {
?.takeIf { it.isNotEmpty() }
?.takeUnless { it.lowercase() in GENERIC_MODEL_ALIASES }
fun isServerDefaultAlias(profileName: String?): Boolean =
profileName?.trim()?.equals("default", ignoreCase = true) == true
fun normalizeSelection(profile: Profile?): Profile? =
if (isServerDefaultAlias(profile?.name)) null else profile
fun normalizeSelection(profile: Profile?): Profile? = profile
fun profileRequestName(profileName: String?): String? =
profileName
?.trim()
?.takeIf { it.isNotEmpty() && !isServerDefaultAlias(it) }
?.takeIf { it.isNotEmpty() && it != SERVER_DEFAULT_PROFILE_KEY }
/**
* The profile name that owns chat sessions for the current UI selection.
*
* [selectedProfileName] is null (or the synthetic `default` alias) for the
* "Server default" row. That UI sentinel must remain distinct from the
* [selectedProfileName] is null for the "Server default" row. That UI
* sentinel must remain distinct from the
* server's sticky active profile: a dashboard launched under the root home
* may still report `active=victor`, in which case upstream Gateway and
* dashboard session calls must explicitly target `victor`. The resolved
@@ -12,6 +12,7 @@ enum class AppLanguage(val languageTag: String) {
JAPANESE("ja"),
SIMPLIFIED_CHINESE("zh-Hans"),
SPANISH("es"),
RUSSIAN("ru"),
;
fun toLocaleList(): LocaleListCompat = if (languageTag.isEmpty()) {
@@ -35,6 +36,7 @@ enum class AppLanguage(val languageTag: String) {
"es" -> SPANISH
"ja" -> JAPANESE
"pt" -> BRAZILIAN_PORTUGUESE
"ru" -> RUSSIAN
"zh" -> {
val simplified = locale.script.equals("Hans", ignoreCase = true) ||
locale.script.isEmpty() ||
@@ -5,6 +5,8 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -15,15 +17,14 @@ import kotlinx.coroutines.flow.map
*
* Phase V follow-on — owned by the voice-barge-in plan (Wave 1 / unit B1).
*
* Barge-in lets the user interrupt TTS playback by speaking. The three knobs
* Barge-in lets the user interrupt generation or TTS playback by speaking.
* here back the Voice Settings "Interruption" section added by B5 and are
* consumed by [com.hermesandroid.relay.viewmodel.VoiceViewModel] (wired in
* B4):
*
* - [enabled] — master toggle for the whole barge-in path. When false, the
* listener never starts and TTS plays uninterrupted. Default off at launch
* on both flavors so existing users aren't surprised by mic activation
* during a speaking turn.
* listener never starts and TTS plays uninterrupted. Default on matches
* upstream Hermes full-duplex voice; users can opt out here.
*
* - [sensitivity] — maps to Silero VAD threshold + hysteresis tuning inside
* [com.hermesandroid.relay.audio.VadEngine]. [BargeInSensitivity.Off] is
@@ -36,6 +37,12 @@ import kotlinx.coroutines.flow.map
* barge-in behaves like a hard cancel, which is more abrupt than most
* conversational UX expects.
*
* - [thresholdMultiplier] / [playbackGraceMs] — upstream-compatible RMS
* tuning. Defaults are 3x over the calibrated quiet floor and 500 ms.
*
* - [debugDiagnostics] — opt-in per-block VAD decision logging for logcat,
* equivalent to upstream's HERMES_VOICE_DEBUG switch.
*
* Matches the [BridgePreferences] / [VoicePreferences] / [MediaSettings] style:
* single shared DataStore (`relayDataStore`), one key per scalar field, enum
* stored as its `name` (cheap + schema-evolvable via fall-back to default on
@@ -45,6 +52,9 @@ data class BargeInPreferences(
val enabled: Boolean = DEFAULT_ENABLED,
val sensitivity: BargeInSensitivity = DEFAULT_SENSITIVITY,
val resumeAfterInterruption: Boolean = DEFAULT_RESUME_AFTER_INTERRUPTION,
val thresholdMultiplier: Float = DEFAULT_THRESHOLD_MULTIPLIER,
val playbackGraceMs: Long = DEFAULT_PLAYBACK_GRACE_MS,
val debugDiagnostics: Boolean = DEFAULT_DEBUG_DIAGNOSTICS,
)
/**
@@ -62,9 +72,12 @@ enum class BargeInSensitivity {
High,
}
const val DEFAULT_ENABLED: Boolean = false
const val DEFAULT_ENABLED: Boolean = true
val DEFAULT_SENSITIVITY: BargeInSensitivity = BargeInSensitivity.Default
const val DEFAULT_RESUME_AFTER_INTERRUPTION: Boolean = true
const val DEFAULT_THRESHOLD_MULTIPLIER: Float = 3f
const val DEFAULT_PLAYBACK_GRACE_MS: Long = 500L
const val DEFAULT_DEBUG_DIAGNOSTICS: Boolean = false
/**
* DataStore-backed repository for [BargeInPreferences].
@@ -86,6 +99,10 @@ class BargeInPreferencesRepository(
internal val KEY_SENSITIVITY = stringPreferencesKey("barge_in_sensitivity")
internal val KEY_RESUME_AFTER_INTERRUPTION =
booleanPreferencesKey("barge_in_resume_after_interruption")
internal val KEY_THRESHOLD_MULTIPLIER =
floatPreferencesKey("barge_in_threshold_multiplier")
internal val KEY_PLAYBACK_GRACE_MS = longPreferencesKey("barge_in_playback_grace_ms")
internal val KEY_DEBUG_DIAGNOSTICS = booleanPreferencesKey("barge_in_debug_diagnostics")
}
val flow: Flow<BargeInPreferences> = dataStore.data
@@ -96,6 +113,14 @@ class BargeInPreferencesRepository(
?: DEFAULT_SENSITIVITY,
resumeAfterInterruption = prefs[KEY_RESUME_AFTER_INTERRUPTION]
?: DEFAULT_RESUME_AFTER_INTERRUPTION,
thresholdMultiplier = prefs[KEY_THRESHOLD_MULTIPLIER]
?.coerceIn(MIN_THRESHOLD_MULTIPLIER, MAX_THRESHOLD_MULTIPLIER)
?: DEFAULT_THRESHOLD_MULTIPLIER,
playbackGraceMs = prefs[KEY_PLAYBACK_GRACE_MS]
?.coerceIn(MIN_PLAYBACK_GRACE_MS, MAX_PLAYBACK_GRACE_MS)
?: DEFAULT_PLAYBACK_GRACE_MS,
debugDiagnostics = prefs[KEY_DEBUG_DIAGNOSTICS]
?: DEFAULT_DEBUG_DIAGNOSTICS,
)
}
.distinctUntilChanged()
@@ -112,6 +137,33 @@ class BargeInPreferencesRepository(
dataStore.edit { it[KEY_RESUME_AFTER_INTERRUPTION] = value }
}
suspend fun setThresholdMultiplier(value: Float) {
dataStore.edit {
it[KEY_THRESHOLD_MULTIPLIER] = value.coerceIn(
MIN_THRESHOLD_MULTIPLIER,
MAX_THRESHOLD_MULTIPLIER,
)
}
}
suspend fun setPlaybackGraceMs(value: Long) {
dataStore.edit {
it[KEY_PLAYBACK_GRACE_MS] = value.coerceIn(
MIN_PLAYBACK_GRACE_MS,
MAX_PLAYBACK_GRACE_MS,
)
}
}
suspend fun setDebugDiagnostics(value: Boolean) {
dataStore.edit { it[KEY_DEBUG_DIAGNOSTICS] = value }
}
private fun decodeSensitivity(raw: String): BargeInSensitivity =
runCatching { BargeInSensitivity.valueOf(raw) }.getOrDefault(DEFAULT_SENSITIVITY)
}
private const val MIN_THRESHOLD_MULTIPLIER = 1f
private const val MAX_THRESHOLD_MULTIPLIER = 8f
private const val MIN_PLAYBACK_GRACE_MS = 0L
private const val MAX_PLAYBACK_GRACE_MS = 3_000L
@@ -0,0 +1,182 @@
package com.hermesandroid.relay.data
import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import com.hermesandroid.relay.bridge.BridgeCapability
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.File
import java.util.UUID
/** Connection-scoped Bridge authority. Missing, malformed, or future schemas deny all. */
class BridgeCapabilityPolicyRepository(private val context: Context) {
companion object {
private val KEY_POLICIES = stringPreferencesKey("bridge_capability_policies_v1")
}
@Serializable
private data class StoredPolicies(
val schemaVersion: Int = BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION,
val installId: String = "",
val byConnection: Map<String, BridgeCapabilityPolicy> = emptyMap(),
)
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
private val installId: String = localInstallId(context)
fun policy(connectionId: String?): Flow<BridgeCapabilityPolicy> =
context.relayDataStore.data.map { prefs ->
readPolicies(prefs[KEY_POLICIES])[connectionId.normalizedPolicyKey()]
?.takeIf { it.schemaVersion == BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION }
?: BridgeCapabilityPolicy()
}
suspend fun snapshot(connectionId: String?): BridgeCapabilityPolicy =
policy(connectionId).first()
suspend fun setPermanent(connectionId: String?, capability: BridgeCapability, allowed: Boolean) {
require(!capability.timed) { "Timed capabilities require an expiry" }
update(connectionId) { current ->
current.copy(
permanentGrants = if (allowed) {
current.permanentGrants + capability
} else {
current.permanentGrants - capability
},
)
}
}
suspend fun replacePermanent(
connectionId: String?,
capabilities: Set<BridgeCapability>,
) {
require(capabilities.none { it.timed }) { "Timed capabilities require an expiry" }
update(connectionId) { current -> current.copy(permanentGrants = capabilities) }
}
suspend fun grantTimed(
connectionId: String?,
capability: BridgeCapability,
expiresAtMs: Long,
nowMs: Long = System.currentTimeMillis(),
) {
require(capability.timed) { "Permanent capabilities do not accept an expiry" }
update(connectionId) { current ->
current.copy(
timedExpiriesMs = (
current.timedExpiriesMs.filterValues { it > nowMs }.keys + capability
)
.associateWith { expiresAtMs },
)
}
}
suspend fun revoke(connectionId: String?, capability: BridgeCapability) {
update(connectionId) { current ->
current.copy(
permanentGrants = current.permanentGrants - capability,
timedExpiriesMs = current.timedExpiriesMs - capability,
)
}
}
suspend fun revokeTimed(connectionId: String?) {
update(connectionId) { it.copy(timedExpiriesMs = emptyMap()) }
}
suspend fun replaceTimed(
connectionId: String?,
capabilities: Set<BridgeCapability>,
expiresAtMs: Long,
) {
require(capabilities.all { it.timed }) { "Permanent capabilities cannot be timed" }
update(connectionId) { current ->
current.copy(timedExpiriesMs = capabilities.associateWith { expiresAtMs })
}
}
suspend fun refreshActiveTimed(connectionId: String?, expiresAtMs: Long) {
update(connectionId) { current ->
current.copy(
timedExpiriesMs = current.timedExpiriesMs.mapNotNull { (capability, currentExpiry) ->
when {
currentExpiry == BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS ->
capability to currentExpiry
currentExpiry > System.currentTimeMillis() -> capability to expiresAtMs
else -> null
}
}.toMap(),
)
}
}
suspend fun pruneExpired(connectionId: String?, nowMs: Long) {
update(connectionId) { current ->
current.copy(timedExpiriesMs = current.timedExpiriesMs.filterValues { it > nowMs })
}
}
suspend fun clearConnection(connectionId: String) {
val key = connectionId.normalizedPolicyKey()
context.relayDataStore.edit { prefs ->
val current = readPolicies(prefs[KEY_POLICIES]).toMutableMap()
current.remove(key)
prefs[KEY_POLICIES] = json.encodeToString(
StoredPolicies(installId = installId, byConnection = current),
)
}
}
private suspend fun update(
connectionId: String?,
transform: (BridgeCapabilityPolicy) -> BridgeCapabilityPolicy,
) {
val key = connectionId.normalizedPolicyKey()
context.relayDataStore.edit { prefs ->
val current = readPolicies(prefs[KEY_POLICIES]).toMutableMap()
current[key] = transform(current[key] ?: BridgeCapabilityPolicy())
prefs[KEY_POLICIES] = json.encodeToString(
StoredPolicies(installId = installId, byConnection = current),
)
}
}
private fun readPolicies(raw: String?): Map<String, BridgeCapabilityPolicy> {
if (raw.isNullOrBlank()) return emptyMap()
val stored = runCatching { json.decodeFromString<StoredPolicies>(raw) }.getOrNull()
?: return emptyMap()
if (stored.schemaVersion != BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION ||
stored.installId != installId
) return emptyMap()
return stored.byConnection
}
private fun String?.normalizedPolicyKey(): String =
this?.trim()?.takeIf { it.isNotEmpty() } ?: "__unbound__"
private fun localInstallId(context: Context): String {
val file = File(context.noBackupFilesDir, "bridge-policy-install-id")
return runCatching {
if (file.isFile) {
file.readText().trim().takeIf { it.isNotEmpty() }
} else {
null
} ?: UUID.randomUUID().toString().also { id ->
file.parentFile?.mkdirs()
file.writeText(id)
}
}.getOrElse {
// An unavailable no-backup fence must never make restored grants
// usable. This process-only value causes every persisted read to
// mismatch and therefore deny.
"unavailable-${UUID.randomUUID()}"
}
}
}
@@ -70,7 +70,11 @@ data class BridgeSettings(
class BridgePreferencesRepository(private val context: Context) {
companion object {
private val KEY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
// v2 is deliberately separate. Older APKs know only the legacy key
// and therefore remain disabled after a downgrade instead of treating
// the new granular grants as blanket authority.
private val KEY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled_v2")
private val KEY_LEGACY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
private val KEY_ACTIVITY_LOG = stringPreferencesKey("bridge_activity_log")
/** Hard cap on persisted entries. See file-level KDoc for rationale. */
@@ -99,7 +103,10 @@ class BridgePreferencesRepository(private val context: Context) {
}
suspend fun setMasterEnabled(enabled: Boolean) {
context.relayDataStore.edit { it[KEY_MASTER_ENABLED] = enabled }
context.relayDataStore.edit {
it[KEY_MASTER_ENABLED] = enabled
it[KEY_LEGACY_MASTER_ENABLED] = false
}
}
/**
@@ -29,10 +29,9 @@ import kotlinx.serialization.json.Json
* appear in `/tap_text` or `/type` payloads. Seeded with a set of verbs
* that carry irreversible or high-stakes consequences. Editable.
*
* - [autoDisableMinutes] — idle timeout after which the master toggle
* auto-flips to false. Rescheduled on every command so an active agent
* never triggers it; a runaway agent that stops sending commands for
* this long loses bridge access automatically.
* - [autoDisableMinutes] — idle timeout for timed screen inspection and
* control grants. Only accepted timed commands refresh it; permanent
* read/action grants neither expire nor keep screen authority alive.
*
* - [statusOverlayEnabled] — opt-in floating-dot indicator (like the
* screen-recording red dot) that's visible while bridge is active.
@@ -0,0 +1,492 @@
package com.hermesandroid.relay.data
import java.io.File
import java.io.FileOutputStream
import java.security.MessageDigest
import java.util.Base64
import java.util.WeakHashMap
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
/**
* Immutable owner of one composer draft.
*
* Callers must supply stable ids rather than display labels. [sessionId] may be
* a server id or a stable client-generated id for a not-yet-created session.
* [draftId] separates the primary composer from any future named draft slot.
*/
data class ChatComposerDraftKey(
val connectionId: String,
val profileId: String,
val sessionId: String,
val draftId: String = PRIMARY_DRAFT_ID,
) {
init {
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
require(profileId.isNotBlank()) { "profileId must not be blank" }
require(sessionId.isNotBlank()) { "sessionId must not be blank" }
require(draftId.isNotBlank()) { "draftId must not be blank" }
}
companion object {
const val PRIMARY_DRAFT_ID = "primary"
const val DEFAULT_PROFILE_ID = "default"
}
}
/** Message references associated with composer content. */
data class ChatComposerDraftContext(
val quotedMessageId: String? = null,
val editingMessageId: String? = null,
) {
internal fun normalized(): ChatComposerDraftContext = copy(
quotedMessageId = quotedMessageId?.takeIf(String::isNotBlank),
editingMessageId = editingMessageId?.takeIf(String::isNotBlank),
)
}
/**
* Complete restorable state for one composer.
*
* Selection offsets use the same start-inclusive/end-exclusive convention as
* Compose text fields. The store clamps them whenever the text changes so a
* restored selection can never address outside the restored string.
*/
data class ChatComposerDraft(
val text: String = "",
val selectionStart: Int = text.length,
val selectionEnd: Int = selectionStart,
val context: ChatComposerDraftContext = ChatComposerDraftContext(),
val attachments: List<Attachment> = emptyList(),
) {
val isEmpty: Boolean
get() = text.isEmpty() &&
context.quotedMessageId == null &&
context.editingMessageId == null &&
attachments.isEmpty()
internal fun normalized(): ChatComposerDraft {
val normalizedStart = selectionStart.coerceIn(0, text.length)
val normalizedEnd = selectionEnd.coerceIn(0, text.length)
return copy(
selectionStart = minOf(normalizedStart, normalizedEnd),
selectionEnd = maxOf(normalizedStart, normalizedEnd),
context = context.normalized(),
attachments = attachments.toList(),
)
}
}
/**
* Session-owned composer state.
*
* This store is deliberately memory-only: outbound [Attachment.content] can
* contain large Base64 payloads and must not enter Preferences DataStore. Keep
* one instance in the chat owner (normally its ViewModel) so drafts survive
* navigation and Activity recreation. Process death starts with empty drafts;
* a future durable implementation should persist URI grants, not attachment
* bytes.
*/
interface ChatComposerDraftStore {
fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft>
suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
suspend fun update(
key: ChatComposerDraftKey,
transform: (ChatComposerDraft) -> ChatComposerDraft,
)
suspend fun remove(key: ChatComposerDraftKey)
suspend fun removeSession(connectionId: String, profileId: String, sessionId: String)
suspend fun clear()
}
class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
private val drafts = MutableStateFlow<Map<ChatComposerDraftKey, ChatComposerDraft>>(emptyMap())
override fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft> =
drafts
.map { it[key] ?: ChatComposerDraft() }
.distinctUntilChanged()
override suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
drafts.value[key] ?: ChatComposerDraft()
override suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
synchronized(drafts) {
val normalized = draft.normalized()
drafts.value = if (normalized.isEmpty) {
drafts.value - key
} else {
drafts.value + (key to normalized)
}
}
}
override suspend fun update(
key: ChatComposerDraftKey,
transform: (ChatComposerDraft) -> ChatComposerDraft,
) {
save(key, transform(snapshot(key)))
}
override suspend fun remove(key: ChatComposerDraftKey) {
synchronized(drafts) {
drafts.value = drafts.value - key
}
}
override suspend fun removeSession(connectionId: String, profileId: String, sessionId: String) {
synchronized(drafts) {
drafts.value = drafts.value.filterKeys { key ->
key.connectionId != connectionId ||
key.profileId != profileId ||
key.sessionId != sessionId
}
}
}
override suspend fun clear() {
synchronized(drafts) {
drafts.value = emptyMap()
}
}
}
/**
* App-private durable composer storage.
*
* The caller supplies a directory under `noBackupFilesDir`: drafts survive
* process death and ordinary app exits but never enter Android cloud backup.
* Metadata stays small JSON while attachment bytes are content-addressed blobs,
* so typing does not repeatedly rewrite Base64 payloads.
*/
class PersistentChatComposerDraftStore(
private val root: File,
) : ChatComposerDraftStore {
private val mutex = Mutex()
private val updates = MutableSharedFlow<ChatComposerDraftKey>(extraBufferCapacity = 64)
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
private val draftsDir = File(root, "drafts")
private val blobsDir = File(root, "blobs")
private val contentBlobIds = WeakHashMap<String, String>()
override fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft> = flow {
emit(snapshot(key))
emitAll(
updates
.filter { it == key }
.map { snapshot(key) }
.distinctUntilChanged(),
)
}.distinctUntilChanged()
override suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft = withContext(Dispatchers.IO) {
mutex.withLock { readDraft(key) }
}
override suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
withContext(Dispatchers.IO) {
mutex.withLock {
val normalized = draft.normalized()
if (normalized.isEmpty) {
draftFile(key).delete()
} else {
ensureDirectories()
val persisted = normalized.toPersisted(key)
atomicWrite(
draftFile(key),
json.encodeToString(PersistedDraft.serializer(), persisted)
.toByteArray(Charsets.UTF_8),
)
}
pruneAndCollect(except = key)
}
}
updates.tryEmit(key)
}
override suspend fun update(
key: ChatComposerDraftKey,
transform: (ChatComposerDraft) -> ChatComposerDraft,
) {
withContext(Dispatchers.IO) {
mutex.withLock {
val normalized = transform(readDraft(key)).normalized()
if (normalized.isEmpty) {
draftFile(key).delete()
} else {
ensureDirectories()
atomicWrite(
draftFile(key),
json.encodeToString(
PersistedDraft.serializer(),
normalized.toPersisted(key),
).toByteArray(Charsets.UTF_8),
)
}
pruneAndCollect(except = key)
}
}
updates.tryEmit(key)
}
override suspend fun remove(key: ChatComposerDraftKey) {
withContext(Dispatchers.IO) {
mutex.withLock {
draftFile(key).delete()
collectOrphanBlobs()
}
}
updates.tryEmit(key)
}
override suspend fun removeSession(connectionId: String, profileId: String, sessionId: String) {
val removed = mutableListOf<ChatComposerDraftKey>()
withContext(Dispatchers.IO) {
mutex.withLock {
draftFiles().forEach { file ->
val persisted = readPersisted(file) ?: return@forEach
val key = persisted.key.toDomain()
if (
key.connectionId == connectionId &&
key.profileId == profileId &&
key.sessionId == sessionId
) {
file.delete()
removed += key
}
}
collectOrphanBlobs()
}
}
removed.forEach(updates::tryEmit)
}
override suspend fun clear() {
withContext(Dispatchers.IO) {
mutex.withLock {
root.listFiles().orEmpty().forEach(File::deleteRecursively)
contentBlobIds.clear()
}
}
}
private fun ChatComposerDraft.toPersisted(key: ChatComposerDraftKey): PersistedDraft =
PersistedDraft(
key = PersistedKey.from(key),
text = text,
selectionStart = selectionStart,
selectionEnd = selectionEnd,
quotedMessageId = context.quotedMessageId,
editingMessageId = context.editingMessageId,
attachments = attachments.mapNotNull(::persistAttachment),
savedAtEpochMs = System.currentTimeMillis(),
)
private fun persistAttachment(attachment: Attachment): PersistedAttachment? {
val rawBytes = attachment.composerRawText
?.takeIf { attachment.isLargePaste }
?.toByteArray(Charsets.UTF_8)
val cachedBlobId = if (rawBytes == null) contentBlobIds[attachment.content] else null
val cachedBlob = cachedBlobId?.let { File(blobsDir, "$it.blob") }
if (cachedBlobId != null && cachedBlob?.exists() == true) {
return attachment.toPersistedAttachment(cachedBlobId)
}
val bytes = rawBytes
?: runCatching { Base64.getDecoder().decode(attachment.content) }.getOrNull()
?: return null
if (bytes.isEmpty()) return null
val blobId = sha256(bytes)
val blob = File(blobsDir, "$blobId.blob")
if (!blob.exists()) atomicWrite(blob, bytes)
if (rawBytes == null) contentBlobIds[attachment.content] = blobId
return attachment.toPersistedAttachment(blobId)
}
private fun Attachment.toPersistedAttachment(blobId: String): PersistedAttachment =
PersistedAttachment(
contentType = contentType,
blobId = blobId,
fileName = fileName,
fileSize = fileSize,
sensitive = sensitive,
isLargePaste = isLargePaste,
composerId = composerId,
)
private fun readDraft(key: ChatComposerDraftKey): ChatComposerDraft {
val persisted = readPersisted(draftFile(key)) ?: return ChatComposerDraft()
if (persisted.key.toDomain() != key) return ChatComposerDraft()
return ChatComposerDraft(
text = persisted.text,
selectionStart = persisted.selectionStart,
selectionEnd = persisted.selectionEnd,
context = ChatComposerDraftContext(
quotedMessageId = persisted.quotedMessageId,
editingMessageId = persisted.editingMessageId,
),
attachments = persisted.attachments.mapNotNull { attachment ->
val blob = File(blobsDir, "${attachment.blobId}.blob")
val bytes = runCatching { blob.readBytes() }.getOrNull()
?.takeIf(ByteArray::isNotEmpty) ?: return@mapNotNull null
val content = Base64.getEncoder().encodeToString(bytes)
contentBlobIds[content] = attachment.blobId
Attachment(
contentType = attachment.contentType,
content = content,
fileName = attachment.fileName,
fileSize = attachment.fileSize ?: bytes.size.toLong(),
sensitive = attachment.sensitive,
isLargePaste = attachment.isLargePaste,
composerId = attachment.composerId,
)
},
).normalized()
}
private fun readPersisted(file: File): PersistedDraft? = runCatching {
json.decodeFromString(PersistedDraft.serializer(), file.readText(Charsets.UTF_8))
}.getOrNull()
private fun pruneAndCollect(except: ChatComposerDraftKey) {
val exceptFile = draftFile(except)
val candidates = draftFiles()
.filterNot { it == exceptFile }
.sortedBy(File::lastModified)
candidates
.take((draftFiles().size - MAX_DRAFTS).coerceAtLeast(0))
.forEach { it.delete() }
collectOrphanBlobs()
for (oldest in candidates) {
if (blobsDir.listFiles().orEmpty().sumOf(File::length) <= MAX_BLOB_BYTES) break
if (oldest.exists()) {
oldest.delete()
collectOrphanBlobs()
}
}
}
private fun collectOrphanBlobs() {
val referenced = draftFiles()
.mapNotNull(::readPersisted)
.flatMap { draft -> draft.attachments.map(PersistedAttachment::blobId) }
.toSet()
blobsDir.listFiles().orEmpty()
.filter { it.isFile && it.extension == "blob" && it.nameWithoutExtension !in referenced }
.forEach(File::delete)
}
private fun ensureDirectories() {
check(draftsDir.exists() || draftsDir.mkdirs()) { "Could not create composer draft directory" }
check(blobsDir.exists() || blobsDir.mkdirs()) { "Could not create composer blob directory" }
}
private fun draftFiles(): List<File> = draftsDir.listFiles().orEmpty()
.filter { it.isFile && it.extension == "json" }
private fun draftFile(key: ChatComposerDraftKey): File =
File(draftsDir, "${sha256(key.storageIdentity().toByteArray(Charsets.UTF_8))}.json")
private fun atomicWrite(target: File, bytes: ByteArray) {
target.parentFile?.let { parent ->
check(parent.exists() || parent.mkdirs()) { "Could not create composer storage directory" }
}
val temporary = File(target.parentFile, ".${target.name}.${System.nanoTime()}.tmp")
try {
FileOutputStream(temporary).use { output ->
output.write(bytes)
output.fd.sync()
}
try {
Files.move(
temporary.toPath(),
target.toPath(),
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING,
)
} catch (_: AtomicMoveNotSupportedException) {
Files.move(
temporary.toPath(),
target.toPath(),
StandardCopyOption.REPLACE_EXISTING,
)
}
} finally {
temporary.delete()
}
}
private fun ChatComposerDraftKey.storageIdentity(): String =
listOf(connectionId, profileId, sessionId, draftId).joinToString("\u0000")
private fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256")
.digest(bytes)
.joinToString("") { byte -> "%02x".format(byte) }
companion object {
private const val MAX_DRAFTS = 64
private const val MAX_BLOB_BYTES = 128L * 1024L * 1024L
}
}
@Serializable
private data class PersistedDraft(
val key: PersistedKey,
val text: String,
val selectionStart: Int,
val selectionEnd: Int,
val quotedMessageId: String? = null,
val editingMessageId: String? = null,
val attachments: List<PersistedAttachment> = emptyList(),
val savedAtEpochMs: Long,
)
@Serializable
private data class PersistedKey(
val connectionId: String,
val profileId: String,
val sessionId: String,
val draftId: String,
) {
fun toDomain(): ChatComposerDraftKey = ChatComposerDraftKey(
connectionId = connectionId,
profileId = profileId,
sessionId = sessionId,
draftId = draftId,
)
companion object {
fun from(key: ChatComposerDraftKey): PersistedKey = PersistedKey(
connectionId = key.connectionId,
profileId = key.profileId,
sessionId = key.sessionId,
draftId = key.draftId,
)
}
}
@Serializable
private data class PersistedAttachment(
val contentType: String,
val blobId: String,
val fileName: String? = null,
val fileSize: Long? = null,
val sensitive: Boolean = false,
val isLargePaste: Boolean = false,
val composerId: String? = null,
)
@@ -0,0 +1,61 @@
package com.hermesandroid.relay.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
/** Phone-local behavior for a physical keyboard's unmodified Enter key. */
enum class PhysicalKeyboardEnterBehavior(val storedValue: String) {
SendMessage("send_message"),
InsertNewline("insert_newline"),
;
companion object {
fun fromStoredValue(value: String?): PhysicalKeyboardEnterBehavior =
entries.firstOrNull { it.storedValue == value } ?: SendMessage
}
}
/** Device-level chat input preferences shared by every Hermes profile. */
class ChatInputPreferencesRepository(
private val dataStore: DataStore<Preferences>,
) {
constructor(context: Context) : this(context.relayDataStore)
companion object {
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
stringPreferencesKey("physical_keyboard_enter_behavior")
internal val KEY_CONVERT_LARGE_PASTES =
booleanPreferencesKey("convert_large_pastes_to_attachments")
}
val physicalKeyboardEnterBehavior: Flow<PhysicalKeyboardEnterBehavior> = dataStore.data
.map { preferences ->
PhysicalKeyboardEnterBehavior.fromStoredValue(
preferences[KEY_PHYSICAL_KEYBOARD_ENTER],
)
}
.distinctUntilChanged()
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
.distinctUntilChanged()
suspend fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
dataStore.edit { preferences ->
preferences[KEY_PHYSICAL_KEYBOARD_ENTER] = behavior.storedValue
}
}
suspend fun setConvertLargePastesToAttachments(enabled: Boolean) {
dataStore.edit { preferences ->
preferences[KEY_CONVERT_LARGE_PASTES] = enabled
}
}
}
@@ -0,0 +1,44 @@
package com.hermesandroid.relay.data
import java.util.Base64
const val LARGE_PASTE_THRESHOLD_CHARS = 5_000
data class TextTransportAttachments(
val message: String,
val attachments: List<Attachment>,
)
fun largePasteAttachment(text: String, composerId: String? = null): Attachment {
val bytes = text.toByteArray(Charsets.UTF_8)
return Attachment(
contentType = "text/plain; charset=utf-8",
content = Base64.getEncoder().encodeToString(bytes),
fileName = "pasted-text.txt",
fileSize = bytes.size.toLong(),
isLargePaste = true,
composerId = composerId,
)
}
fun prepareTextTransportAttachments(
message: String,
attachments: List<Attachment>,
): TextTransportAttachments {
val largePastes = attachments.filter(Attachment::isLargePaste)
if (largePastes.isEmpty()) return TextTransportAttachments(message, attachments)
val materialized = largePastes.mapNotNull { attachment ->
runCatching {
val text = String(Base64.getDecoder().decode(attachment.content), Charsets.UTF_8)
val name = attachment.fileName?.takeIf(String::isNotBlank) ?: "pasted text"
"--- $name ---\n$text"
}.getOrNull()
}
return TextTransportAttachments(
message = (listOf(message) + materialized)
.filter(String::isNotBlank)
.joinToString("\n\n"),
attachments = attachments.filterNot(Attachment::isLargePaste),
)
}
@@ -112,12 +112,11 @@ data class ChatMessage(
*/
val clientOnly: Boolean = false,
/**
* Delivery state for a message the user sends into an agent **Thread** over
* the relay proactive channel ([com.hermesandroid.relay.viewmodel.ChatViewModel]
* routes `source=phone` sessions here instead of the normal chat send).
* `SENDING` until the relay acks (`proactive.reply.ack`) → `DELIVERED`;
* `FAILED` on a send error. Null for ordinary chat messages — those render
* no status affix.
* Delivery state for a user-authored message. Agent **Thread** replies use
* `SENDING` until the relay acks (`proactive.reply.ack`) → `DELIVERED`,
* with `FAILED` on a send error. Ordinary chat may additionally use
* `QUEUED` and `STEERED` to make active-turn routing visible. Null keeps the
* legacy behavior of rendering no status affix.
*/
val deliveryStatus: MessageDeliveryStatus? = null,
/**
@@ -142,6 +141,18 @@ data class ChatMessage(
* through `copy`, while [id] remains the authoritative lookup/wire id.
*/
val uiKey: String = id,
/**
* Durable Gateway transcript row identity for rewind/edit-regenerate.
* This is server-owned and can change after a truncating rewrite; it is
* never used as a Compose key or synthesized client-side.
*/
val rowId: Long? = null,
/**
* Durable iOS-style tapbacks attached to this server message. Hermes keeps
* one reaction per author in the message's display metadata; the UI also
* updates this list optimistically while a reaction write is in flight.
*/
val reactions: List<MessageReaction> = emptyList(),
/**
* Mixture-of-Agents advisor responses surfaced during the live turn.
* Unavailable advisors retain only neutral state, never their raw failure
@@ -151,6 +162,29 @@ data class ChatMessage(
val moaReferences: List<MoaReference> = emptyList(),
)
data class MessageReaction(
val emoji: String,
val author: String,
/** Epoch seconds, matching the Gateway/Desktop contract. */
val at: Double,
)
/** Apply Hermes' one-reaction-per-author, re-tap-to-retract semantics. */
internal fun applyMessageReaction(
reactions: List<MessageReaction>,
emoji: String?,
author: String = "user",
at: Double = System.currentTimeMillis() / 1000.0,
): List<MessageReaction> {
val previous = reactions.firstOrNull { it.author == author }
val withoutAuthor = reactions.filterNot { it.author == author }
return if (emoji.isNullOrBlank() || previous?.emoji == emoji) {
withoutAuthor
} else {
withoutAuthor + MessageReaction(emoji = emoji, author = author, at = at)
}
}
data class MoaReference(
val index: Int,
val count: Int?,
@@ -294,7 +328,13 @@ data class Attachment(
* existing outbound/inbound call site stays valid and unflagged media
* renders exactly as before.
*/
val sensitive: Boolean = false
val sensitive: Boolean = false,
/** Local composer metadata; never serialized onto the Hermes wire. */
val isLargePaste: Boolean = false,
/** Stable id for an asynchronous composer preparation; never sent to Hermes. */
val composerId: String? = null,
/** Raw UTF-8 text retained only while a large-paste attachment is preparing. */
val composerRawText: String? = null,
) {
val isImage: Boolean get() = contentType.startsWith("image/")
@@ -367,12 +407,20 @@ data class ToolCall(
* header can render without a separate lane registry.
*/
val taskLabel: String? = null,
/** Live upstream child id used by subagent.steer while this lane runs. */
val subagentId: String? = null,
/** Deterministic non-low output risk reported by upstream for this call. */
val outputRisk: String? = null,
/** Human-readable deterministic findings; rendered as untrusted metadata. */
val outputRiskFindings: List<String> = emptyList(),
/** Upstream removed sensitive spans before emitting the findings. */
val outputRiskRedacted: Boolean = false,
/**
* Stable UI identity retained when a generating placeholder adopts its
* gateway tool ID. This keeps per-card interaction state attached to the
* logical call across streaming reconciliation and list updates.
*/
val uiKey: String = id ?: "$name:$startedAt",
)
enum class MessageRole {
@@ -382,21 +430,28 @@ enum class MessageRole {
}
/**
* Delivery state of a user reply sent into an agent Thread over the relay
* proactive channel. Only set on Thread replies; ordinary chat messages leave
* it null and show no status affix.
* Delivery state of a user-authored message. Thread replies use the relay ack
* lifecycle; ordinary chat can additionally expose queue and steer outcomes.
* Null preserves the legacy behavior of rendering no status affix.
*
* - [SENDING] handed to the relay; awaiting the per-reply ack.
* - [QUEUED] held client-side until the active turn completes.
* - [STEERED] accepted as a correction to the active turn.
* - [DELIVERED] the relay acked (`proactive.reply.ack`) — buffered for the agent.
* - [FAILED] the send errored (e.g. relay disconnected).
*/
enum class MessageDeliveryStatus { SENDING, DELIVERED, FAILED }
enum class MessageDeliveryStatus { SENDING, QUEUED, STEERED, DELIVERED, FAILED }
data class ChatSession(
val sessionId: String,
val title: String?,
val model: String?,
val messageCount: Int = 0,
val inputTokens: Int = 0,
val outputTokens: Int = 0,
val actualCostUsd: Double? = null,
val estimatedCostUsd: Double? = null,
val isActive: Boolean = false,
val updatedAt: Long = 0L,
val startedAt: Long = 0L,
val lastActivityAt: Long = 0L,
@@ -409,7 +464,24 @@ data class ChatSession(
val source: String? = null,
/** Server reports a persisted session runtime/model binding. */
val hasModelConfig: Boolean = false,
/** Durable upstream session metadata, scoped by the owning connection/profile DB. */
val pinned: Boolean = false,
val archived: Boolean = false,
/** Optional newer-upstream workspace context; absent on legacy/API-only hosts. */
val workingDirectory: String? = null,
val gitBranch: String? = null,
val gitRepoRoot: String? = null,
val pullRequestNumber: Int? = null,
val pullRequestUrl: String? = null,
val pullRequestState: String? = null,
val pullRequestDraft: Boolean = false,
) {
val totalTokens: Int
get() = inputTokens + outputTokens
val costUsd: Double
get() = actualCostUsd ?: estimatedCostUsd ?: 0.0
val activityTimestamp: Long
get() = firstPositive(lastActivityAt, updatedAt, startedAt)
@@ -0,0 +1,66 @@
package com.hermesandroid.relay.data
import java.nio.charset.StandardCharsets
import java.util.Base64
/** Structured identity and preview for a quoted chat message. */
data class ChatQuoteReference(
val messageId: String,
val authorLabel: String,
val excerpt: String,
)
/** Parsed transport envelope: Android renders [reference] separately from [body]. */
data class ChatQuoteEnvelope(
val reference: ChatQuoteReference,
val body: String,
)
/**
* Serialize a structured quote as ordinary Markdown for unmodified Hermes clients.
* Android parses the same envelope back into a quote chip, while Desktop/TUI see
* a readable linked attribution instead of an Android-only marker.
*/
fun buildChatQuotedPrompt(body: String, reference: ChatQuoteReference?): String {
if (reference == null) return body
val encodedId = Base64.getUrlEncoder().withoutPadding().encodeToString(
reference.messageId.toByteArray(StandardCharsets.UTF_8),
)
val author = reference.authorLabel.normalizedQuoteText(MAX_AUTHOR_CHARS)
val excerpt = reference.excerpt.normalizedQuoteText(MAX_EXCERPT_CHARS)
if (encodedId.isBlank() || author.isBlank() || excerpt.isBlank()) return body
return "> **Replying to [@$author](hermes-message://$encodedId):** $excerpt\n\n$body"
}
/** Parse only the exact bounded envelope emitted by [buildChatQuotedPrompt]. */
fun parseChatQuotedPrompt(content: String): ChatQuoteEnvelope? {
val match = QUOTE_ENVELOPE.matchEntire(content) ?: return null
val author = match.groupValues[1]
val encodedId = match.groupValues[2]
val excerpt = match.groupValues[3]
val body = match.groupValues[4]
val messageId = runCatching {
String(Base64.getUrlDecoder().decode(encodedId), StandardCharsets.UTF_8)
}.getOrNull()?.takeIf { it.isNotBlank() && it.length <= MAX_MESSAGE_ID_CHARS } ?: return null
return ChatQuoteEnvelope(
reference = ChatQuoteReference(messageId, author, excerpt),
body = body,
)
}
private fun String.normalizedQuoteText(maxChars: Int): String =
replace(Regex("[\\p{Cc}\\s]+"), " ")
.replace("\\", "")
.replace("]", "")
.trim()
.take(maxChars)
private val QUOTE_ENVELOPE = Regex(
pattern = "^> \\*\\*Replying to \\[@([^]\\r\\n]{1,$MAX_AUTHOR_CHARS})]" +
"\\(hermes-message://([A-Za-z0-9_-]{1,512})\\):\\*\\* " +
"([^\\r\\n]{1,$MAX_EXCERPT_CHARS})\\n\\n([\\s\\S]*)$",
)
private const val MAX_AUTHOR_CHARS = 40
private const val MAX_EXCERPT_CHARS = 240
private const val MAX_MESSAGE_ID_CHARS = 512
@@ -32,6 +32,7 @@ data class ChatTurnCheckpoint(
val priorUserMessageCount: Int,
val baselineAssistantCount: Int,
val pendingAsk: ChatTurnAskCheckpoint? = null,
val queuedMessages: List<ChatQueuedMessageCheckpoint> = emptyList(),
val startedAt: Long,
val updatedAt: Long,
) {
@@ -41,6 +42,17 @@ data class ChatTurnCheckpoint(
}
}
@Serializable
data class ChatQueuedMessageCheckpoint(
val id: String,
val text: String,
val transport: String,
val ownerRunId: String,
val interfaceContextPrompt: String? = null,
/** Attachment bytes are intentionally not copied into Preferences DataStore. */
val hadAttachments: Boolean = false,
)
@Serializable
data class ChatTurnUserCheckpoint(
val id: String,
@@ -117,6 +129,7 @@ data class ChatTurnAskCheckpoint(
val requestId: String? = null,
val text: String,
val choices: List<String>? = null,
val multiSelect: Boolean = false,
val smartDenied: Boolean = false,
val envVar: String? = null,
val timeoutSeconds: Int,
@@ -14,6 +14,9 @@ data class DashboardConnectionStatus(
val gatewayTicketAvailable: Boolean? = null,
val message: String? = null,
val gatewayMode: String? = null,
/** Profiles positively advertised by the live multiplex gateway. */
val servedProfiles: List<String> = emptyList(),
/** Installed profiles reported by the dashboard; never routing authority. */
val profiles: List<String> = emptyList(),
)
@@ -134,7 +137,7 @@ data class Connection(
* than to crash).
*/
fun extractDefaultLabel(apiServerUrl: String): String =
extractHost(apiServerUrl) ?: apiServerUrl
extractHost(apiServerUrl)?.let(::defaultLabelFromHost) ?: apiServerUrl
/** Preserve explicit labels while upgrading an auto-generated IP label to a discovered host name. */
fun chooseDiscoveredLabel(
@@ -160,7 +163,25 @@ data class Connection(
val primary = dashboardUrl?.trim()?.takeIf { it.isNotBlank() }
?: apiServerUrl.trim().takeIf { it.isNotBlank() }
?: relayUrl.trim()
return extractHost(primary) ?: primary
return extractHost(primary)?.let(::defaultLabelFromHost) ?: primary
}
/**
* Nous-hosted agent gateways use the stable
* `<slug>.agents.nousresearch.com` origin contract. The public Hermes
* status response deliberately carries no tenant/agent display name,
* so a URL-only connection uses that exact single-label slug as its
* least-surprising default. Portal's human-readable agent name is only
* available through its separately authenticated discovery API.
*
* Match the complete suffix and exactly one leading DNS label. This
* avoids shortening lookalike or operator-controlled hostnames.
*/
private fun defaultLabelFromHost(host: String): String {
val suffix = ".agents.nousresearch.com"
if (!host.endsWith(suffix, ignoreCase = true)) return host
val slug = host.dropLast(suffix.length)
return slug.takeIf { it.isNotBlank() && '.' !in it } ?: host
}
private fun extractHost(url: String): String? = try {
@@ -247,6 +268,7 @@ data class Connection(
apiServerUrl: String,
relayUrl: String,
extraApiUrls: List<Pair<String, String>> = emptyList(),
dashboardUrl: String? = null,
): List<EndpointCandidate> {
val routes = buildList {
endpointCandidateFromApiUrl(
@@ -255,6 +277,7 @@ data class Connection(
apiServerUrl = apiServerUrl,
relayUrl = relayUrl.takeIf { it.isNotBlank() }
?: deriveDefaultRelayUrl(apiServerUrl).orEmpty(),
dashboardUrl = dashboardUrl,
)?.let(::add)
extraApiUrls
@@ -266,6 +289,7 @@ data class Connection(
priority = index + 1,
apiServerUrl = url,
relayUrl = deriveDefaultRelayUrl(url).orEmpty(),
dashboardUrl = dashboardUrl,
)?.let(::add)
}
}
@@ -340,6 +364,7 @@ data class Connection(
priority: Int,
apiServerUrl: String,
relayUrl: String,
dashboardUrl: String? = null,
): EndpointCandidate? {
val uri = runCatching { URI(apiServerUrl.trim().trimEnd('/')) }.getOrNull()
?: return null
@@ -363,12 +388,62 @@ data class Connection(
role = role.ifBlank { inferRouteRole(apiServerUrl) },
priority = priority,
api = ApiEndpoint(host = host, port = port, tls = tls),
dashboard = deriveDefaultDashboardUrl(apiServerUrl)
dashboard = dashboardUrl
?.trim()
?.trimEnd('/')
?.takeIf { it.isNotBlank() && urlsShareHost(it, apiServerUrl) }
?.let { DashboardEndpoint(url = it) }
?: deriveDefaultDashboardUrl(apiServerUrl)
?.let { DashboardEndpoint(url = it) },
relay = RelayEndpoint(url = resolvedRelayUrl, transportHint = transportHint),
)
}
/**
* Reconcile stored API-derived routes with the Dashboard origin that
* was actually verified during setup. Older app versions synthesized
* `:9119` for every API route, even when the same host was reached
* through an HTTPS reverse proxy on 443. Replace only that conventional
* synthesized value (or a missing value); preserve explicit and
* different-host LAN/Tailscale routes.
*/
fun reconcileDashboardRoutes(
dashboardUrl: String?,
candidates: List<EndpointCandidate>,
): List<EndpointCandidate> {
val explicitDashboard = dashboardUrl
?.trim()
?.trimEnd('/')
?.takeIf { it.isNotBlank() }
?: return candidates
return candidates.map { candidate ->
val apiUrl = candidate.api?.url ?: return@map candidate
if (!urlsShareHost(explicitDashboard, apiUrl)) return@map candidate
val currentDashboard = candidate.dashboard?.url
val derivedDashboard = deriveDefaultDashboardUrl(apiUrl)
val canReplace = currentDashboard.isNullOrBlank() ||
(
derivedDashboard != null &&
currentDashboard.trim().trimEnd('/')
.equals(derivedDashboard, ignoreCase = true)
)
if (canReplace) {
candidate.copy(dashboard = DashboardEndpoint(url = explicitDashboard))
} else {
candidate
}
}
}
fun urlsShareHost(leftUrl: String, rightUrl: String): Boolean {
val leftHost = runCatching { URI(leftUrl.trim()) }.getOrNull()?.host
val rightHost = runCatching { URI(rightUrl.trim()) }.getOrNull()?.host
return !leftHost.isNullOrBlank() &&
!rightHost.isNullOrBlank() &&
leftHost.equals(rightHost, ignoreCase = true)
}
/**
* De-duplication identity for rebuilding stored routes. Prefer the
* legacy API authority when present so an older API-only candidate and
@@ -63,12 +63,8 @@ fun EndpointCandidate?.isEncryptedOverlayRoute(isTailscaleDetected: Boolean): Bo
val hint = security.orEmpty().lowercase()
return r == "tailscale" ||
(isTailscaleDetected && hint.contains("tailscale")) ||
r == "plugin_proxy" ||
r == "plugin-proxy" ||
hasSecureProxy() ||
hint.contains("wireguard") ||
hint.contains("https") ||
hint.contains("tls")
(!hasSecureProxy() && (hint.contains("https") || hint.contains("tls")))
}
/** Human label for the overlay mechanism encrypting a route. */
@@ -78,7 +74,6 @@ fun EndpointCandidate?.overlayMechanism(isTailscaleDetected: Boolean): String {
val hint = security.orEmpty().lowercase()
return when {
r == "tailscale" || (isTailscaleDetected && hint.contains("tailscale")) -> "Tailscale"
r == "plugin_proxy" || r == "plugin-proxy" || hasSecureProxy() -> "Proxy"
hint.contains("wireguard") -> "WireGuard"
hint.contains("https") || hint.contains("tls") -> "TLS"
else -> "Encrypted"
@@ -92,7 +87,10 @@ fun classifySurfaceSecurity(
activeEndpoint: EndpointCandidate?,
isTailscaleDetected: Boolean,
): SurfaceSecurity {
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
val (kind, mechanism) = when {
secureLinkProtected -> SurfaceSecurityKind.Tls to
if (activeEndpoint?.hasHermesReach() == true) "Hermes Reach" else "Hermes Secure Link"
isTlsUrl(url) -> SurfaceSecurityKind.Tls to "TLS"
activeEndpoint.isEncryptedOverlayRoute(isTailscaleDetected) ->
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
@@ -101,6 +99,33 @@ fun classifySurfaceSecurity(
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
}
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
val candidate = this ?: return false
val routes = candidate.proxy?.takeIf { candidate.hasSecureProxy() }
?.let { proxy ->
val base = proxy.url.trim().trimEnd('/')
Triple(
"$base/dashboard",
"$base/api",
"wss://${base.substringAfter("://")}/relay/ws",
)
} ?: return false
val normalized = url.trim().trimEnd('/')
val service = when (label) {
"Chat & Manage" -> "dashboard"
"API / sessions" -> "api"
"Relay tools" -> "relay"
else -> return false
}
if (service !in candidate.secureLinkServices()) return false
val expected = when (service) {
"dashboard" -> routes.first
"api" -> routes.second
else -> routes.third
}
return normalized.equals(expected, ignoreCase = true)
}
/**
* Roll up the per-surface verdicts into one connection-level [ConnectionSecurity].
* Pure + side-effect free so it is unit-testable without Android.
@@ -543,29 +543,6 @@ class ConnectionStore private constructor(
}
}
private fun Connection.withDashboardDefaults(): Connection {
val derivedDashboardUrl = Connection.deriveDefaultDashboardUrl(apiServerUrl)
val normalizedRoutes = routeCandidates.ifEmpty {
Connection.buildRouteCandidates(apiServerUrl, relayUrl)
}
val normalizedPreferredRouteRole = preferredRouteRole?.takeIf { preferred ->
normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) }
}
return if (
(dashboardUrl.isNullOrBlank() && derivedDashboardUrl != null) ||
normalizedRoutes != routeCandidates ||
normalizedPreferredRouteRole != preferredRouteRole
) {
copy(
dashboardUrl = dashboardUrl?.takeIf { it.isNotBlank() } ?: derivedDashboardUrl,
routeCandidates = normalizedRoutes,
preferredRouteRole = normalizedPreferredRouteRole,
)
} else {
this
}
}
companion object {
private const val TAG = "ConnectionStore"
@@ -585,3 +562,40 @@ class ConnectionStore private constructor(
private const val DEFAULT_RELAY_URL = "ws://localhost:8767"
}
}
/**
* Restore route defaults after loading a serialized connection. This remains
* internal so focused persistence tests can exercise the same normalization
* path used by [ConnectionStore].
*/
internal fun Connection.withDashboardDefaults(): Connection {
val derivedDashboardUrl = Connection.deriveDefaultDashboardUrl(apiServerUrl)
val effectiveDashboardUrl = dashboardUrl?.takeIf { it.isNotBlank() } ?: derivedDashboardUrl
val storedOrDefaultRoutes = routeCandidates.ifEmpty {
Connection.buildRouteCandidates(
apiServerUrl = apiServerUrl,
relayUrl = relayUrl,
dashboardUrl = effectiveDashboardUrl,
)
}
val normalizedRoutes = Connection.reconcileDashboardRoutes(
dashboardUrl = effectiveDashboardUrl,
candidates = storedOrDefaultRoutes,
)
val normalizedPreferredRouteRole = preferredRouteRole?.takeIf { preferred ->
normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) }
}
return if (
dashboardUrl != effectiveDashboardUrl ||
normalizedRoutes != routeCandidates ||
normalizedPreferredRouteRole != preferredRouteRole
) {
copy(
dashboardUrl = effectiveDashboardUrl,
routeCandidates = normalizedRoutes,
preferredRouteRole = normalizedPreferredRouteRole,
)
} else {
this
}
}
@@ -172,6 +172,11 @@ class DataManager(
suspend fun restoreConnectionBackup(backup: AppBackup) {
val store = connectionStore ?: return
// Validate every credential before deleting or replacing any current
// encrypted state. A malformed/hostile backup fails atomically.
backup.connectionSecrets.forEach { secret ->
AuthManager.validateStoredSecrets(secret.auth)
}
deleteSensitivePreferenceFiles()
store.replaceConnections(
connections = backup.connections,
@@ -45,8 +45,13 @@ data class EndpointCandidate(
val relay: RelayEndpoint? = null,
val dashboard: DashboardEndpoint? = null,
val proxy: ProxyEndpoint? = null,
/** Optional outbound rendezvous carrying the pinned [proxy] byte stream. */
val broker: BrokerEndpoint? = null,
val security: String? = null,
val recommended: Boolean = false,
val experimental: Boolean = false,
@SerialName("display_name")
val displayName: String? = null,
)
/**
@@ -110,6 +115,27 @@ data class ProxyEndpoint(
val transportHint: String? = null,
@SerialName("pin_sha256")
val pinSha256: String? = null,
/** Independently authenticated services carried by this pinned origin. */
val surfaces: List<String> = listOf("relay"),
)
/**
* Hermes Reach rendezvous metadata from an operator-reviewed pairing payload.
* The token authenticates only this broker route; Hermes service credentials
* remain inside the QR-pinned Secure Link TLS connection.
*/
@Serializable
data class BrokerEndpoint(
val url: String,
@SerialName("protocol_version")
val protocolVersion: Int = 1,
@SerialName("host_id")
val hostId: String,
@SerialName("credential_kind")
val credentialKind: String,
val token: String,
@SerialName("expires_at")
val expiresAt: Long? = null,
)
/**
@@ -123,7 +149,7 @@ data class ProxyEndpoint(
*/
fun EndpointCandidate.isKnownRole(): Boolean {
return when (role.lowercase()) {
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "https" -> true
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
else -> false
}
}
@@ -146,7 +172,8 @@ fun EndpointCandidate.displayLabel(): String {
"Public"
}
"https" -> "HTTPS"
"plugin_proxy", "plugin-proxy" -> "Plugin proxy"
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
else -> "Custom VPN ($role)"
}
}
@@ -177,7 +204,69 @@ fun EndpointCandidate.routeAuthority(): String? {
}
fun EndpointCandidate.hasSecureProxy(): Boolean =
proxy?.url?.startsWith("https://", ignoreCase = true) == true ||
proxy?.url?.startsWith("wss://", ignoreCase = true) == true ||
role.equals("plugin_proxy", ignoreCase = true) ||
role.equals("plugin-proxy", ignoreCase = true)
proxy?.isValidPinnedProxy() == true
/** Product-facing service inventory; wire identifiers remain unchanged. */
fun EndpointCandidate.secureLinkServices(): List<String> =
if (!hasSecureProxy()) emptyList() else proxy.orEmptySurfaces()
fun EndpointCandidate.secureLinkCoversAllServices(): Boolean =
secureLinkServices().containsAll(listOf("relay", "api", "dashboard"))
fun EndpointCandidate.presentationRouteUrl(): String? =
broker?.url?.takeIf { hasHermesReach() } ?: proxy?.url?.takeIf { hasSecureProxy() } ?: primaryRouteUrl()
fun EndpointCandidate.hasHermesReach(): Boolean =
role.lowercase() in setOf("outbound_broker", "broker", "relay_broker") &&
broker?.isValidHermesReach() == true && hasSecureProxy()
fun BrokerEndpoint.isValidHermesReach(): Boolean {
if (protocolVersion != 1 || !hostId.isCanonicalBase64Url(16) || !token.isCanonicalBase64Url(32)) return false
if (credentialKind !in setOf("bootstrap", "route")) return false
if (credentialKind == "bootstrap" && expiresAt?.let { it <= System.currentTimeMillis() / 1000L } == true) return false
val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
return uri.rawPath.orEmpty().let { it.isEmpty() || it == "/" || it == "/v1/connect" }
}
private fun String.isCanonicalBase64Url(byteCount: Int): Boolean {
if (isBlank() || '=' in this) return false
val decoded = runCatching { java.util.Base64.getUrlDecoder().decode(this) }.getOrNull() ?: return false
return decoded.size == byteCount &&
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == this
}
/** Exact host locator + broker authority replacement; never crosses devices. */
internal fun replaceHermesReachCredential(
source: List<EndpointCandidate>,
expected: BrokerEndpoint,
replacement: EndpointCandidate,
): List<EndpointCandidate> = source.map { candidate ->
if (candidate.broker?.hostId == expected.hostId &&
sameBrokerAuthority(candidate.broker.url, expected.url)
) replacement else candidate
}
internal fun sameBrokerAuthority(left: String, right: String): Boolean = runCatching {
val a = URI(left.trim())
val b = URI(right.trim())
fun port(uri: URI) = if (uri.port > 0) uri.port else 443
a.scheme.equals("wss", true) && b.scheme.equals("wss", true) &&
a.host.equals(b.host, true) && port(a) == port(b) &&
a.rawPath.orEmpty().trimEnd('/') == b.rawPath.orEmpty().trimEnd('/')
}.getOrDefault(false)
private fun ProxyEndpoint?.orEmptySurfaces(): List<String> = this?.surfaces.orEmpty()
.map { it.trim().lowercase() }
.filter { it in setOf("relay", "api", "dashboard") }
.distinct()
fun ProxyEndpoint.isValidPinnedProxy(): Boolean {
val uri = runCatching { URI(url.trim().trimEnd('/')) }.getOrNull() ?: return false
if (!uri.scheme.equals("https", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" }) return false
val pin = pinSha256?.trim()?.removePrefix("sha256/") ?: return false
return runCatching { java.util.Base64.getDecoder().decode(pin).size == 32 }.getOrDefault(false)
}
@@ -22,6 +22,7 @@ object FeatureFlags {
// DataStore keys
private val KEY_DEV_OPTIONS_UNLOCKED = booleanPreferencesKey("dev_options_unlocked")
private val KEY_PET_TERRAIN_OVERLAY = booleanPreferencesKey("pet_terrain_overlay")
/** Whether the app is running a debug build. */
val isDevBuild: Boolean get() = BuildConfig.DEV_MODE
@@ -32,6 +33,35 @@ object FeatureFlags {
prefs[KEY_DEV_OPTIONS_UNLOCKED] ?: isDevBuild
}
/**
* Developer-only visualization of the floating pet's measured terrain.
*
* The persisted request is intentionally weaker than both gates: release
* builds can never enable it, and explicitly locking Developer Options
* suppresses it immediately.
*/
fun petTerrainOverlayEnabled(context: Context): Flow<Boolean> =
context.relayDataStore.data.map { prefs ->
petTerrainOverlayEffective(
isDevBuild = isDevBuild,
devOptionsUnlocked = prefs[KEY_DEV_OPTIONS_UNLOCKED] ?: isDevBuild,
requested = prefs[KEY_PET_TERRAIN_OVERLAY] ?: false,
)
}
internal fun petTerrainOverlayEffective(
isDevBuild: Boolean,
devOptionsUnlocked: Boolean,
requested: Boolean,
): Boolean = isDevBuild && devOptionsUnlocked && requested
/** Persist the developer's overlay request. Runtime gates remain authoritative. */
suspend fun setPetTerrainOverlayEnabled(context: Context, enabled: Boolean) {
context.relayDataStore.edit { prefs ->
prefs[KEY_PET_TERRAIN_OVERLAY] = enabled
}
}
/** Unlock Developer Options. */
suspend fun unlockDevOptions(context: Context) {
context.relayDataStore.edit { prefs ->
@@ -43,6 +73,7 @@ object FeatureFlags {
suspend fun lockDevOptions(context: Context) {
context.relayDataStore.edit { prefs ->
prefs[KEY_DEV_OPTIONS_UNLOCKED] = false
prefs[KEY_PET_TERRAIN_OVERLAY] = false
}
}
@@ -2,6 +2,8 @@ package com.hermesandroid.relay.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/**
* A rich content card emitted inline in an assistant message via the
@@ -117,6 +119,8 @@ data class HermesCardInput(
val kind: String,
/** Quick-answer chips (clarify). Empty = no chip row. */
val choices: List<String> = emptyList(),
/** Choices toggle independently and require an explicit submit. */
val multiSelect: Boolean = false,
/** Render the inline free-text mini field under the chips. */
val allowFreeText: Boolean = false,
/** Password-style field: masked glyphs + reveal toggle (secret/sudo). */
@@ -124,7 +128,7 @@ data class HermesCardInput(
/** Submit is a 650ms hold-to-confirm press-fill instead of a tap (sudo). */
val holdToConfirm: Boolean = false,
/**
* Wall-clock expiry for timed asks (sudo 120s, clarify/secret 300s).
* Wall-clock expiry for asks with an advertised deadline.
* The renderer shows a countdown footer (Amber under 30s) and
* self-collapses to "Expired — not granted" past it. Null = no timeout
* (approval is session-scoped).
@@ -155,6 +159,10 @@ data class HermesCardInput(
}
}
/** Exact JSON-array wire value expected by upstream multi-select clarify. */
internal fun encodeClarifyMultiSelectAnswer(values: List<String>): String =
Json.encodeToString(values.map(String::trim).filter(String::isNotEmpty).distinct())
/**
* A label/value row inside a card. [value] is rendered as markdown so the
* agent can embed emphasis, inline code, or links.
@@ -0,0 +1,135 @@
package com.hermesandroid.relay.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
/** Exact cadence values consumed by the floating-pet behavior director. */
data class PetBehaviorPacing(
val responseVisitDelayMs: Long,
val roamIntervalMs: Long,
val idleReactionCadenceMs: Long,
) {
init {
require(responseVisitDelayMs > 0L)
require(roamIntervalMs > responseVisitDelayMs)
require(idleReactionCadenceMs > roamIntervalMs)
}
}
/**
* User-facing pet activity presets.
*
* These values control how often an otherwise-idle pet may act. Existing
* animation, reduced-motion, touch-exploration, scrolling, and agent-activity
* gates remain authoritative and may always defer an action.
*/
enum class PetTemperament(val pacing: PetBehaviorPacing) {
Calm(
PetBehaviorPacing(
responseVisitDelayMs = 2_500L,
roamIntervalMs = 12_000L,
idleReactionCadenceMs = 28_000L,
),
),
Balanced(
PetBehaviorPacing(
responseVisitDelayMs = 1_500L,
roamIntervalMs = 8_000L,
idleReactionCadenceMs = 18_000L,
),
),
Playful(
PetBehaviorPacing(
responseVisitDelayMs = 750L,
roamIntervalMs = 5_000L,
idleReactionCadenceMs = 10_000L,
),
),
}
val DEFAULT_PET_TEMPERAMENT: PetTemperament = PetTemperament.Balanced
const val DEFAULT_PET_SIZE_SCALE: Float = 1f
const val MIN_PET_SIZE_SCALE: Float = 0.6f
const val MAX_PET_SIZE_SCALE: Float = 1.2f
private const val LEGACY_PET_SIZE_BASE_SCALE: Float = 1.25f
private const val CURRENT_PET_SIZE_SCALE_VERSION: Int = 2
internal fun sanitizedPetSizeScale(value: Float?): Float =
value?.takeIf(Float::isFinite)?.coerceIn(MIN_PET_SIZE_SCALE, MAX_PET_SIZE_SCALE)
?: DEFAULT_PET_SIZE_SCALE
internal fun decodeStoredPetSizeScale(value: Float?, version: Int?): Float {
if (value == null) return DEFAULT_PET_SIZE_SCALE
val rebased = if (version == null) value / LEGACY_PET_SIZE_BASE_SCALE else value
return sanitizedPetSizeScale(rebased)
}
data class PetBehaviorPreferences(
val temperament: PetTemperament = DEFAULT_PET_TEMPERAMENT,
val sizeScale: Float = DEFAULT_PET_SIZE_SCALE,
) {
/**
* Runtime seam for the behavior director. A disabled motion gate returns
* no pacing rather than weakening the app's accessibility policy.
*/
fun pacingWhenMotionAllowed(motionAllowed: Boolean): PetBehaviorPacing? =
temperament.pacing.takeIf { motionAllowed }
}
/** Additive, phone-local DataStore persistence for pet behavior preferences. */
class PetBehaviorPreferencesRepository(
private val dataStore: DataStore<Preferences>,
) {
constructor(context: Context) : this(context.relayDataStore)
companion object {
internal val KEY_TEMPERAMENT = stringPreferencesKey("pet_temperament")
internal val KEY_SIZE_SCALE = floatPreferencesKey("pet_size_scale")
internal val KEY_SIZE_SCALE_VERSION = intPreferencesKey("pet_size_scale_version")
}
val flow: Flow<PetBehaviorPreferences> = dataStore.data
.map { preferences ->
PetBehaviorPreferences(
temperament = decodeTemperament(preferences[KEY_TEMPERAMENT]),
sizeScale = decodeStoredPetSizeScale(
value = preferences[KEY_SIZE_SCALE],
version = preferences[KEY_SIZE_SCALE_VERSION],
),
)
}
.distinctUntilChanged()
val temperament: Flow<PetTemperament> = flow
.map { preferences -> preferences.temperament }
.distinctUntilChanged()
val sizeScale: Flow<Float> = flow
.map { preferences -> preferences.sizeScale }
.distinctUntilChanged()
suspend fun setTemperament(temperament: PetTemperament) {
dataStore.edit { preferences ->
preferences[KEY_TEMPERAMENT] = temperament.name
}
}
suspend fun setSizeScale(sizeScale: Float) {
dataStore.edit { preferences ->
preferences[KEY_SIZE_SCALE] = sanitizedPetSizeScale(sizeScale)
preferences[KEY_SIZE_SCALE_VERSION] = CURRENT_PET_SIZE_SCALE_VERSION
}
}
private fun decodeTemperament(raw: String?): PetTemperament =
raw?.let { stored -> PetTemperament.entries.firstOrNull { it.name == stored } }
?: DEFAULT_PET_TEMPERAMENT
}
@@ -34,6 +34,10 @@ data class ProactiveInboxEntry(
* field).
*/
val chatId: String? = null,
/** Owning saved connection. Null only for entries written by older builds. */
val connectionId: String? = null,
/** Relay proved this row came from its bounded offline queue. */
val arrivedWhileAway: Boolean = false,
)
private val Context.proactiveInboxStore: DataStore<Preferences> by
@@ -49,10 +53,10 @@ private const val MAX_ENTRIES = 100
* newest-first, deduped by id (so a re-delivered message doesn't double up), and
* capped at [MAX_ENTRIES]. Survives app restart.
*
* Demoted (2026-06-29): the agent conversation now lives as a Thread in Chat (the
* gateway session is the durable history), so the in-app inbox view is retired.
* This store is only fed for messages NOT shown in an open Thread; it currently
* has no viewer and is fully retireable — see TODO.
* Demoted (2026-06-29): once a phone gateway session exists, it is the durable
* history. Outbound agent messages arrive before that session exists, so this
* bounded store also backs the provisional Thread until the user's first reply
* promotes it to a real `source=phone` session.
*/
class ProactiveInboxRepository(private val context: Context) {
@@ -0,0 +1,125 @@
package com.hermesandroid.relay.data
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import java.io.ByteArrayOutputStream
import kotlin.math.roundToInt
internal fun profileAvatarMime(bytes: ByteArray): String? = when {
bytes.size >= 8 && bytes.copyOfRange(0, 8).contentEquals(
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a),
) -> "image/png"
bytes.size >= 3 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte() &&
bytes[2] == 0xff.toByte() -> "image/jpeg"
bytes.size >= 12 && bytes.copyOfRange(0, 4).contentEquals("RIFF".toByteArray()) &&
bytes.copyOfRange(8, 12).contentEquals("WEBP".toByteArray()) -> "image/webp"
else -> null
}
/**
* Convert any image Android can decode into the small static format accepted by
* upstream `profiles.set_asset`. ImageDecoder applies camera EXIF orientation
* and downsamples before allocating the bitmap on current Android releases.
*/
internal fun prepareProfileAvatar(
context: Context,
uri: Uri,
maxBytes: Int,
): ByteArray? {
val original = runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val output = ByteArrayOutputStream(minOf(maxBytes + 1, 64 * 1024))
val buffer = ByteArray(16 * 1024)
while (output.size() <= maxBytes) {
val read = input.read(buffer)
if (read < 0) break
output.write(buffer, 0, read)
}
output.toByteArray()
}
}.getOrNull()
if (original != null && original.size <= maxBytes && profileAvatarMime(original) != null) {
return original
}
val bitmap = decodeProfileAvatar(context, uri) ?: return null
return try {
encodeProfileAvatar(bitmap, maxBytes)
} finally {
bitmap.recycle()
}
}
private fun decodeProfileAvatar(context: Context, uri: Uri): Bitmap? = runCatching {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(context.contentResolver, uri)) { decoder, info, _ ->
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
val width = info.size.width
val height = info.size.height
val longest = maxOf(width, height)
if (longest > PROFILE_AVATAR_MAX_DIMENSION) {
val scale = PROFILE_AVATAR_MAX_DIMENSION.toFloat() / longest
decoder.setTargetSize(
(width * scale).roundToInt().coerceAtLeast(1),
(height * scale).roundToInt().coerceAtLeast(1),
)
}
}
} else {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / sample > PROFILE_AVATAR_MAX_DIMENSION) sample *= 2
context.contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample })
}
}
}.getOrNull()
internal fun encodeProfileAvatar(bitmap: Bitmap, maxBytes: Int): ByteArray? {
var working = bitmap.scaledToFit(PROFILE_AVATAR_MAX_DIMENSION)
var ownsWorking = working !== bitmap
try {
while (true) {
val format = if (working.hasAlpha()) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG
val qualities = if (format == Bitmap.CompressFormat.PNG) intArrayOf(100) else intArrayOf(92, 82, 72, 62)
for (quality in qualities) {
val encoded = ByteArrayOutputStream().use { output ->
if (!working.compress(format, quality, output)) null else output.toByteArray()
}
if (encoded != null && encoded.size <= maxBytes) return encoded
}
if (maxOf(working.width, working.height) <= PROFILE_AVATAR_MIN_DIMENSION) return null
val next = Bitmap.createScaledBitmap(
working,
(working.width * 0.75f).roundToInt().coerceAtLeast(1),
(working.height * 0.75f).roundToInt().coerceAtLeast(1),
true,
)
if (ownsWorking) working.recycle()
working = next
ownsWorking = true
}
} finally {
if (ownsWorking) working.recycle()
}
}
private fun Bitmap.scaledToFit(maxDimension: Int): Bitmap {
val longest = maxOf(width, height)
if (longest <= maxDimension) return this
val scale = maxDimension.toFloat() / longest
return Bitmap.createScaledBitmap(
this,
(width * scale).roundToInt().coerceAtLeast(1),
(height * scale).roundToInt().coerceAtLeast(1),
true,
)
}
private const val PROFILE_AVATAR_MAX_DIMENSION = 1024
private const val PROFILE_AVATAR_MIN_DIMENSION = 128
@@ -2,6 +2,35 @@ package com.hermesandroid.relay.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
internal fun isSafeProfileUiMeta(meta: JsonObject): Boolean {
if (meta.toString().toByteArray(Charsets.UTF_8).size > 65_536) return false
fun containsEmbeddedAsset(value: String): Boolean {
val compact = value.trim()
return compact.startsWith("data:image/", ignoreCase = true) ||
compact.startsWith("iVBORw0KGgo") || // PNG
compact.startsWith("/9j/") || // JPEG
compact.startsWith("UklGR") || // RIFF/WebP
compact.startsWith("R0lGOD") || // GIF
compact.startsWith("UEsDB") // ZIP/pet archive
}
fun safe(element: JsonElement): Boolean = when (element) {
is JsonObject -> element.size <= 128 && element.all { (key, value) ->
key.length <= 128 && safe(value)
}
is JsonArray -> element.size <= 128 && element.all(::safe)
is JsonPrimitive -> {
val value = element.contentOrNull
value == null || (value.length <= 4_096 && !containsEmbeddedAsset(value))
}
}
return safe(meta)
}
/**
* An agent profile advertised by a Hermes server in its `auth.ok` payload.
@@ -47,14 +76,16 @@ import kotlinx.serialization.Serializable
*
* **Hermes profile API metadata.** A relay can advertise an isolated
* profile API server without exposing its secret. When [apiServerUrl] is
* present, Android routes chat/session traffic to that URL and reuses the
* active connection's stored API key. Operators that use distinct API keys
* per profile should pair those profile API servers as separate connections.
* present, Android routes chat/session traffic to that URL using the active
* connection credential. A positively identified shared multiplex
* `/p/<profile>` route instead uses a separately encrypted profile credential;
* the root connection key is never reused for that route.
*/
@Serializable
data class Profile(
val name: String,
val model: String,
val provider: String = "",
val description: String = "",
@SerialName("system_message")
val systemMessage: String? = null,
@@ -74,6 +105,12 @@ data class Profile(
val apiServerPort: Int? = null,
@SerialName("api_server_key_present")
val apiServerKeyPresent: Boolean = false,
@SerialName("is_default")
val isDefault: Boolean = false,
@SerialName("has_avatar")
val hasAvatar: Boolean = false,
@SerialName("ui_meta")
val uiMeta: JsonObject = JsonObject(emptyMap()),
) {
val hasIsolatedApi: Boolean
get() = !apiServerUrl.isNullOrBlank()
@@ -4,13 +4,15 @@ import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/**
* Local-only per-profile agent icons — the visual twin of [ProfileDisplayAliasStore].
* Per-profile icon cache. Local fallback paths and Hermes-owned avatar cache
* paths use separate keys so syncing either side never silently overwrites the other.
*
* Stores a **file path** to an image that was copied into app storage (not a SAF
* content URI, so it survives without a persistable-permission grant). Like the
@@ -25,6 +27,8 @@ class ProfileIconStore(
companion object {
private const val PREFIX = "profile_icon__"
private const val SERVER_PREFIX = "profile_avatar_server__"
private const val LOCAL_OVERRIDE_PREFIX = "profile_icon_override__"
private fun keyName(connectionId: String, profileName: String?): String =
"$PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}"
@@ -34,6 +38,20 @@ class ProfileIconStore(
private fun connectionPrefix(connectionId: String): String =
"$PREFIX${connectionId}__"
private fun serverKeyFor(connectionId: String, profileName: String) =
stringPreferencesKey("$SERVER_PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}")
private fun serverConnectionPrefix(connectionId: String): String =
"$SERVER_PREFIX${connectionId}__"
private fun localOverrideKeyFor(connectionId: String, profileName: String?) =
booleanPreferencesKey(
"$LOCAL_OVERRIDE_PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}",
)
private fun localOverrideConnectionPrefix(connectionId: String): String =
"$LOCAL_OVERRIDE_PREFIX${connectionId}__"
}
suspend fun setIcon(connectionId: String, profileName: String?, path: String?) {
@@ -52,11 +70,39 @@ class ProfileIconStore(
return dataStore.data.map { prefs -> prefs[key] }
}
suspend fun setServerAvatar(connectionId: String, profileName: String, path: String?) {
dataStore.edit { prefs ->
val key = serverKeyFor(connectionId, profileName)
if (path.isNullOrBlank()) prefs.remove(key) else prefs[key] = path
}
}
fun serverAvatarFlow(connectionId: String, profileName: String): Flow<String?> {
val key = serverKeyFor(connectionId, profileName)
return dataStore.data.map { prefs -> prefs[key] }
}
suspend fun setLocalOverride(connectionId: String, profileName: String?, enabled: Boolean) {
dataStore.edit { prefs ->
val key = localOverrideKeyFor(connectionId, profileName)
if (enabled) prefs[key] = true else prefs.remove(key)
}
}
fun localOverrideFlow(connectionId: String, profileName: String?): Flow<Boolean> {
val key = localOverrideKeyFor(connectionId, profileName)
return dataStore.data.map { prefs -> prefs[key] ?: false }
}
suspend fun clearConnection(connectionId: String) {
val prefix = connectionPrefix(connectionId)
val prefixes = listOf(
connectionPrefix(connectionId),
serverConnectionPrefix(connectionId),
localOverrideConnectionPrefix(connectionId),
)
dataStore.edit { prefs ->
prefs.asMap().keys
.filter { it.name.startsWith(prefix) }
.filter { key -> prefixes.any(key.name::startsWith) }
.forEach { prefs.remove(it) }
}
}
@@ -66,5 +112,11 @@ class ProfileIconStore(
}
}
internal fun preferredProfileIcon(
server: String?,
local: String?,
useLocalOverride: Boolean,
): String? = if (useLocalOverride && !local.isNullOrBlank()) local else server ?: local
internal val Context.profileIconsDataStore: DataStore<Preferences>
by preferencesDataStore(name = "profile_icons")
@@ -136,3 +136,154 @@ data class ProfileMemoryUpdateResponse(
@SerialName("bytes_written")
val bytesWritten: Long,
)
/** Authoritative upstream `profiles.describe` snapshot. */
data class GatewayProfileDescription(
val name: String,
val description: String,
val soul: String,
val provider: String,
val model: String,
val skills: List<GatewayProfileSkill>,
val toolsets: List<GatewayProfileToolset>,
val toolsetsPinned: Boolean,
)
data class GatewayProfileSkill(val name: String, val enabled: Boolean)
data class GatewayProfileToolset(
val name: String,
val description: String,
val toolCount: Int,
val enabled: Boolean,
)
enum class GatewayProfileSection(val wireName: String) {
Description("description"),
Soul("soul"),
Model("model"),
Skills("skills"),
Toolsets("toolsets"),
McpServers("mcp_servers"),
UiMeta("ui_meta"),
}
/** Null leaves a section unchanged; empty lists retain upstream replace semantics. */
data class GatewayProfilePatch(
val description: String? = null,
val soul: String? = null,
val provider: String? = null,
val model: String? = null,
val disabledSkills: List<String>? = null,
val enabledToolsets: List<String>? = null,
val enabledMcpServers: List<String>? = null,
/** Small interoperable preferences only; binary assets belong in profiles.set_asset. */
val uiMeta: JsonObject? = null,
) {
val requestedSections: Set<GatewayProfileSection>
get() = buildSet {
if (description != null) add(GatewayProfileSection.Description)
if (soul != null) add(GatewayProfileSection.Soul)
if (provider != null && model != null) add(GatewayProfileSection.Model)
if (disabledSkills != null) add(GatewayProfileSection.Skills)
if (enabledToolsets != null) add(GatewayProfileSection.Toolsets)
if (enabledMcpServers != null) add(GatewayProfileSection.McpServers)
if (uiMeta != null) add(GatewayProfileSection.UiMeta)
}
}
enum class GatewayProfileAuthChoice {
/** Share the launch profile's refreshable OAuth/token store; copy static environment keys. */
Shared,
/** Copy the current credential snapshot into a separate profile-owned store. */
Copied,
/** Copy no credentials or provider defaults. */
Isolated,
}
data class GatewayProfileCreateRequest(
val name: String,
val description: String? = null,
val cloneFrom: String? = null,
val cloneAll: Boolean = false,
val noSkills: Boolean = false,
val soul: String? = null,
val model: String? = null,
val provider: String? = null,
val authChoice: GatewayProfileAuthChoice = GatewayProfileAuthChoice.Shared,
)
data class GatewayProfileCreateResult(
val name: String,
val soulWritten: Boolean,
val modelSet: Boolean,
val mirroredEnvironment: Boolean,
val mirroredAuth: String?,
val modelInherited: Boolean,
val voiceMirrored: Boolean,
) {
fun partialMessages(request: GatewayProfileCreateRequest): List<String> = buildList {
if (!request.soul.isNullOrBlank() && !soulWritten) add("SOUL was not saved")
if (!request.model.isNullOrBlank() && !modelSet) add("model was not saved")
if (request.authChoice == GatewayProfileAuthChoice.Shared && mirroredAuth != "shared") {
add("shared sign-in was not confirmed")
}
if (
request.authChoice == GatewayProfileAuthChoice.Copied &&
!mirroredEnvironment && mirroredAuth != "true"
) {
add("no credential source was copied")
}
}
}
data class GatewayProfileAsset(
val data: ByteArray,
val mime: String,
)
class GatewayProfileManagementUnsupportedException(
operation: String,
) : Exception("$operation is not supported by this gateway")
data class GatewayProfileConfigureResult(
val requested: Set<GatewayProfileSection>,
val applied: Set<GatewayProfileSection>,
) {
val failed: Set<GatewayProfileSection> get() = requested - applied
}
interface GatewayProfileEditorClient {
suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription>
suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult>
}
class GatewayProfileEditorUnsupportedException : Exception(
"Profile editing is not supported by this gateway",
)
/** Relay fallback retained for older gateways and Relay-only memory files. */
interface LegacyProfileInspectorClient {
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse>
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse>
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse>
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse>
suspend fun updateSoul(profileName: String, content: String): Result<ProfileSoulUpdateResponse>
suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
): Result<ProfileMemoryUpdateResponse>
suspend fun updateSkillToggle(skillName: String, enabled: Boolean): Result<RelaySkillToggleResult>
suspend fun probeSkillToggleSupported(): Boolean
}
sealed interface RelaySkillToggleResult {
data object Ok : RelaySkillToggleResult
data object NotImplemented : RelaySkillToggleResult
}
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
@@ -16,6 +17,8 @@ import kotlinx.serialization.json.Json
data class ProfilePresentation(
val order: List<String> = emptyList(),
val hidden: Set<String> = emptySet(),
/** Local-only named-profile accent overrides, stored as normalized RGB hex. */
val colors: Map<String, String> = emptyMap(),
)
/**
@@ -26,7 +29,6 @@ object ProfilePresentationPolicy {
fun availableKeys(profiles: List<Profile>): List<String> = buildList {
add(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY)
profiles.asSequence()
.filterNot { AgentDisplay.isServerDefaultAlias(it.name) }
.map(Profile::name)
.distinct()
.forEach(::add)
@@ -49,6 +51,12 @@ object ProfilePresentationPolicy {
): List<String> = orderedKeys(profiles, presentation).filter { key ->
key == selectedKey || key !in presentation.hidden
}
fun shouldShowShelf(
profiles: List<Profile>,
presentation: ProfilePresentation,
selectedKey: String,
): Boolean = visibleKeys(profiles, presentation, selectedKey).size > 1
}
class ProfilePresentationStore(
@@ -58,14 +66,17 @@ class ProfilePresentationStore(
private val json = Json { ignoreUnknownKeys = true }
private val listSerializer = ListSerializer(String.serializer())
private val mapSerializer = MapSerializer(String.serializer(), String.serializer())
private fun orderKey(connectionId: String) = stringPreferencesKey("order_$connectionId")
private fun hiddenKey(connectionId: String) = stringPreferencesKey("hidden_$connectionId")
private fun colorsKey(connectionId: String) = stringPreferencesKey("colors_$connectionId")
fun presentationFlow(connectionId: String): Flow<ProfilePresentation> = dataStore.data.map { prefs ->
ProfilePresentation(
order = decode(prefs[orderKey(connectionId)]),
hidden = decode(prefs[hiddenKey(connectionId)]).toSet(),
colors = decodeMap(prefs[colorsKey(connectionId)]),
)
}
@@ -77,10 +88,18 @@ class ProfilePresentationStore(
dataStore.edit { it[hiddenKey(connectionId)] = json.encodeToString(listSerializer, hidden.sorted()) }
}
suspend fun setColors(connectionId: String, colors: Map<String, String>) {
dataStore.edit {
if (colors.isEmpty()) it.remove(colorsKey(connectionId))
else it[colorsKey(connectionId)] = json.encodeToString(mapSerializer, colors.toSortedMap())
}
}
suspend fun clear(connectionId: String) {
dataStore.edit {
it.remove(orderKey(connectionId))
it.remove(hiddenKey(connectionId))
it.remove(colorsKey(connectionId))
}
}
@@ -93,6 +112,12 @@ class ProfilePresentationStore(
} else {
runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())
}
private fun decodeMap(raw: String?): Map<String, String> = if (raw == null) {
emptyMap()
} else {
runCatching { json.decodeFromString(mapSerializer, raw) }.getOrDefault(emptyMap())
}
}
internal val Context.profilePresentationDataStore: DataStore<Preferences>
@@ -0,0 +1,7 @@
package com.hermesandroid.relay.data
/** Live activity surfaced beside a session without conflating it with selection. */
enum class SessionActivityState {
Working,
NeedsInput,
}
@@ -13,6 +13,11 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val DEFAULT_VOICE_STOP_PHRASES: List<String> = listOf("stop")
/**
* User-tunable voice mode preferences.
@@ -36,6 +41,8 @@ data class VoiceSettings(
val audioRoute: String = VoiceAudioRoute.Auto.storageValue,
val interactionMode: String = "tap",
val silenceThresholdMs: Long = 1250L,
/** Exact phrases that end an active voice chat; empty disables the command. */
val stopPhrases: List<String> = DEFAULT_VOICE_STOP_PHRASES,
/**
* When true, voice keeps progress visual and waits for the settled Hermes
* answer before speaking. Tool status, service updates, and intermediate
@@ -200,6 +207,7 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
// un-namespaced means switching profiles never churns these.
private val KEY_INTERACTION_MODE = stringPreferencesKey("voice_interaction_mode")
private val KEY_SILENCE_THRESHOLD_MS = longPreferencesKey("voice_silence_threshold_ms")
private val KEY_STOP_PHRASES = stringPreferencesKey("voice_stop_phrases")
private val KEY_FINAL_ANSWER_ONLY = booleanPreferencesKey("voice_final_answer_only")
private val KEY_PRESENTATION_MODE = stringPreferencesKey("voice_presentation_mode")
private val KEY_REALTIME_TRACE_DETAILS = booleanPreferencesKey("voice_realtime_trace_details")
@@ -215,6 +223,10 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
const val DEFAULT_PRESENTATION_MODE = "focus"
const val DEFAULT_REALTIME_TRACE_DETAILS = false
const val DEFAULT_REALTIME_PERSISTENT_SESSION = true
private val stopPhrasesJson = Json {
ignoreUnknownKeys = true
isLenient = true
}
/**
* Build the storage name for a per-profile [base] key under [scope].
@@ -280,6 +292,7 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
// --- global (shared across profiles) ---
interactionMode = prefs[KEY_INTERACTION_MODE] ?: DEFAULT_INTERACTION_MODE,
silenceThresholdMs = prefs[KEY_SILENCE_THRESHOLD_MS] ?: DEFAULT_SILENCE_THRESHOLD_MS,
stopPhrases = decodeStopPhrases(prefs[KEY_STOP_PHRASES]),
finalAnswerOnly = prefs[KEY_FINAL_ANSWER_ONLY] ?: DEFAULT_FINAL_ANSWER_ONLY,
presentationMode = VoicePresentationMode.fromStorage(
prefs[KEY_PRESENTATION_MODE] ?: DEFAULT_PRESENTATION_MODE,
@@ -393,6 +406,15 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
dataStore.edit { it[KEY_SILENCE_THRESHOLD_MS] = ms.coerceAtLeast(500L) }
}
suspend fun setStopPhrases(phrases: List<String>) {
val normalized = phrases.asSequence()
.map(String::trim)
.filter(String::isNotEmpty)
.distinct()
.toList()
dataStore.edit { it[KEY_STOP_PHRASES] = stopPhrasesJson.encodeToString(normalized) }
}
suspend fun setFinalAnswerOnly(enabled: Boolean) {
dataStore.edit { it[KEY_FINAL_ANSWER_ONLY] = enabled }
}
@@ -409,6 +431,17 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
dataStore.edit { it[KEY_REALTIME_PERSISTENT_SESSION] = enabled }
}
private fun decodeStopPhrases(raw: String?): List<String> {
if (raw == null) return DEFAULT_VOICE_STOP_PHRASES
return runCatching { stopPhrasesJson.decodeFromString<List<String>>(raw) }
.getOrDefault(DEFAULT_VOICE_STOP_PHRASES)
.asSequence()
.map(String::trim)
.filter(String::isNotEmpty)
.distinct()
.toList()
}
/**
* Atomically apply the phone-side portion of [preset]. Only fields owned by
* the preset are written, so route/provider/model/voice overrides and other
@@ -3,6 +3,8 @@ package com.hermesandroid.relay.diagnostics
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.hermesandroid.relay.reliability.ReliabilityCenter
import com.hermesandroid.relay.reliability.ReliabilityRedactor
enum class DiagnosticCategory(val label: String) {
Api("API"),
@@ -25,7 +27,16 @@ data class DiagnosticLogEntry(
val severity: DiagnosticSeverity,
val title: String,
val detail: String? = null,
/** Human-readable action that produced this event, not merely its subsystem. */
val operation: String? = null,
val endpointRole: String? = null,
/** User/configuration-facing route before protocol/path normalization. */
val configuredUrl: String? = null,
/** Exact sanitized URL attempted on the wire, including the diagnostic path. */
val requestUrl: String? = null,
/** Concrete next troubleshooting step for failures with a known interpretation. */
val suggestion: String? = null,
/** Legacy single-URL field retained for diagnostics that have not needed split context. */
val url: String? = null,
val elapsedMs: Long? = null,
/**
@@ -34,7 +45,11 @@ data class DiagnosticLogEntry(
* the detail view shows this. Null for non-error / manually-recorded entries.
*/
val stacktrace: String? = null,
)
) {
/** Best route for mode inference and compact list rendering. */
val primaryUrl: String?
get() = configuredUrl ?: requestUrl ?: url
}
/**
* Current health of a single subsystem on the Diagnostics status timeline.
@@ -81,19 +96,29 @@ object DiagnosticsLog {
severity: DiagnosticSeverity = DiagnosticSeverity.Info,
title: String,
detail: String? = null,
operation: String? = null,
endpointRole: String? = null,
configuredUrl: String? = null,
requestUrl: String? = null,
suggestion: String? = null,
url: String? = null,
elapsedMs: Long? = null,
stacktrace: String? = null,
) {
val safeConfiguredUrl = sanitizeUrl(configuredUrl)
val safeRequestUrl = sanitizeUrl(requestUrl)
val entry = DiagnosticLogEntry(
timestampMs = System.currentTimeMillis(),
category = category,
severity = severity,
title = clean(title) ?: title.take(MAX_TEXT_LENGTH),
detail = clean(detail),
operation = clean(operation),
endpointRole = clean(endpointRole),
url = sanitizeUrl(url),
configuredUrl = safeConfiguredUrl,
requestUrl = safeRequestUrl,
suggestion = clean(suggestion),
url = if (safeConfiguredUrl == null && safeRequestUrl == null) sanitizeUrl(url) else null,
elapsedMs = elapsedMs,
stacktrace = redactTrace(stacktrace),
)
@@ -121,20 +146,40 @@ object DiagnosticsLog {
title: String,
detail: String? = null,
throwable: Throwable? = null,
operation: String? = null,
endpointRole: String? = null,
configuredUrl: String? = null,
requestUrl: String? = null,
suggestion: String? = null,
url: String? = null,
elapsedMs: Long? = null,
reliabilityContext: String? = null,
) {
record(
category = category,
severity = DiagnosticSeverity.Error,
title = title,
detail = detail ?: throwable?.message,
operation = operation,
endpointRole = endpointRole,
configuredUrl = configuredUrl,
requestUrl = requestUrl,
suggestion = suggestion,
url = url,
elapsedMs = elapsedMs,
stacktrace = throwable?.let { stackTraceText(it) },
)
if (throwable != null) {
runCatching {
ReliabilityCenter.recordHandled(
title = title,
detail = detail ?: throwable.message,
throwable = throwable,
context = reliabilityContext,
routeRole = endpointRole,
)
}
}
}
private fun stackTraceText(t: Throwable): String =
@@ -167,10 +212,8 @@ object DiagnosticsLog {
val prefix = noQuery.substring(0, schemeEnd + 3)
val rest = noQuery.substring(schemeEnd + 3)
val slash = rest.indexOf('/').let { if (it < 0) rest.length else it }
val authority = rest.substring(0, slash)
val path = rest.substring(slash)
val safeAuthority = authority.substringAfterLast('@')
prefix + safeAuthority + path
prefix + "[host]" + path
} else {
noQuery
}
@@ -197,7 +240,7 @@ object DiagnosticsLog {
*/
private fun redactTrace(value: String?): String? {
val trimmed = value?.trim()?.takeIf { it.isNotBlank() } ?: return null
val redacted = redact(trimmed)
val redacted = ReliabilityRedactor.redact(trimmed, MAX_TRACE_LENGTH)
return if (redacted.length > MAX_TRACE_LENGTH) {
redacted.take(MAX_TRACE_LENGTH) + "\n… (truncated)"
} else {
@@ -205,8 +248,5 @@ object DiagnosticsLog {
}
}
private fun redact(value: String): String =
value.replace(Regex("""(?i)(bearer|token|api[_-]?key|session[_-]?token)\s*[:=]\s*\S+""")) {
"${it.groupValues[1]}=[hidden]"
}
private fun redact(value: String): String = ReliabilityRedactor.redact(value, MAX_TRACE_LENGTH)
}
@@ -0,0 +1,42 @@
package com.hermesandroid.relay.diagnostics
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException
/**
* Maps network failure classes to narrow, truthful next steps.
*
* These messages are diagnostic guidance, not recovery behavior: callers still
* own retries, routing, and authentication. Walking the cause chain preserves
* useful classification when OkHttp or a coroutine boundary wraps the socket
* exception in a higher-level failure.
*/
object NetworkDiagnosticGuidance {
fun forThrowable(throwable: Throwable, target: String): String? {
val causes = generateSequence(throwable as Throwable?) { it.cause }.take(12).toList()
return when {
causes.any { it is ConnectException } ->
"Verify $target is running and listening on the configured host and port."
causes.any { it is UnknownHostException } ->
"Verify the configured hostname resolves from this device."
causes.any { it is NoRouteToHostException } ->
"Verify the device has a network path to the configured host."
causes.any { it is SocketTimeoutException } ->
"Check network routing or firewall rules between this device and $target."
causes.any { it is SSLException } ->
"Verify the TLS scheme, certificate, and trust configuration for $target."
else -> null
}
}
fun forHttpStatus(statusCode: Int, target: String): String? = when (statusCode) {
401, 403 -> "Verify the configured $target credentials or pair the device again."
404 -> "Verify this URL points to the expected $target route and version."
429 -> "Wait for the server's backoff period before retrying."
in 500..599 -> "Check the $target server logs for the failing request."
else -> null
}
}
@@ -258,6 +258,7 @@ class BridgeCommandHandler(
private val pendingActivities =
java.util.concurrent.ConcurrentHashMap<String, PendingActivity>()
private val unattendedWakeRequests = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
// === END v0.4.1 polish ===
private val json = Json {
@@ -302,6 +303,8 @@ class BridgeCommandHandler(
put("error", t.message ?: "unknown executor error")
}
)
} finally {
releaseUnattendedWake(requestId)
}
}
}
@@ -396,6 +399,8 @@ class BridgeCommandHandler(
errorCode = "dispatch_exception",
resultJson = null,
)
} finally {
releaseUnattendedWake(requestId)
}
val resultJson = sink.get()
@@ -421,6 +426,54 @@ class BridgeCommandHandler(
method: String,
body: JsonObject,
) {
// Resolve path + method through the closed capability registry before
// any wake, confirmation, event read, executor, or run-tracker effect.
val registeredAuthority =
com.hermesandroid.relay.bridge.BridgeCommandRegistry.resolve(path, method)
val capabilityAuthorization = when {
registeredAuthority == null -> BridgeSafetyManager.CapabilityAuthorization(
allowed = false,
errorCode = "unknown_bridge_command",
)
!BuildFlavor.isSideload && registeredAuthority.grant !=
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.EXEMPT ->
BridgeSafetyManager.CapabilityAuthorization(
allowed = false,
authority = registeredAuthority,
errorCode = "device_control_sideload_only",
)
registeredAuthority.grant ==
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.EXEMPT ->
BridgeSafetyManager.CapabilityAuthorization(true, registeredAuthority)
else -> safetyManager?.authorizeCapability(path, method)
?: BridgeSafetyManager.CapabilityAuthorization(
allowed = false,
authority = registeredAuthority,
errorCode = "bridge_policy_unavailable",
)
}
if (!capabilityAuthorization.allowed) {
return respond(
requestId,
403,
buildJsonObject {
put(
"error",
if (capabilityAuthorization.errorCode == "device_control_sideload_only") {
"Device Control is not included in the Google Play build."
} else {
"Bridge capability is not granted for this connection."
},
)
put("error_code", capabilityAuthorization.errorCode ?: "bridge_capability_denied")
capabilityAuthorization.authority?.capability?.let {
put("capability", it.wireId)
}
put("required_action", "Review Bridge > Safety & capabilities on the phone")
},
)
}
// === v0.4.1 polish: keep auto-return idle timer alive ===
// Any non-polling bridge command during a run is evidence the
// agent is still working — reset BridgeRunTracker's idle timer
@@ -475,44 +528,6 @@ class BridgeCommandHandler(
return
}
// === PHASE3-event-stream: B1 android_events read-only polling ===
// /events is a read-only peek at the EventStore ring buffer. The
// buffer lives in our own process so there's no safety gate —
// the agent already opted into streaming via /events/stream
// which IS gated. This mirrors the /ping early-return path so
// polling works even when the service is transiently unbound.
if (path == "/events") {
val limitRaw = body["limit"]?.jsonPrimitive?.content?.toIntOrNull() ?: 50
val limit = limitRaw.coerceIn(1, EventStore.MAX_ENTRIES)
val since = body["since"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
val entries = EventStore.recent(limit = limit, since = since)
val arr: JsonArray = buildJsonArray {
for (e in entries) {
add(
buildJsonObject {
put("timestamp", e.timestamp)
put("event_type", e.eventType)
e.packageName?.let { put("package_name", it) }
e.className?.let { put("class_name", it) }
e.text?.let { put("text", it) }
e.contentDescription?.let { put("content_description", it) }
put("source", e.source)
}
)
}
}
respond(
requestId, 200,
buildJsonObject {
put("entries", arr)
put("count", entries.size)
put("streaming", EventStore.isStreaming)
}
)
return
}
// === END PHASE3-event-stream ===
// /setup exists on the relay as a legacy bridge HTTP route, but
// android_setup() in plugin/tools/android_tool.py is host-side
// only (it just writes ANDROID_BRIDGE_TOKEN to ~/.hermes/.env)
@@ -576,10 +591,7 @@ class BridgeCommandHandler(
}
)
if (!service.isMasterEnabled() &&
path != "/current_app" &&
path != "/return_to_hermes"
) {
if (!service.isMasterEnabled()) {
// Crystal-clear error text + structured error_code. Bailey hit
// 2026-04-15: when the phone was paired + a11y granted but
// master toggle flipped off, the agent read the shorter
@@ -649,9 +661,13 @@ class BridgeCommandHandler(
}
}
// Reschedule the idle auto-disable timer on every accepted
// command. Safe to call even when no timer is currently armed.
safetyManager?.rescheduleAutoDisable()
// Permanent capabilities never keep screen control armed. Only an
// accepted timed inspection/control command refreshes the timer.
if (capabilityAuthorization.authority?.grant ==
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.TIMED
) {
safetyManager?.rescheduleAutoDisable()
}
// === END PHASE3-safety-rails ===
// === v0.4.1 unattended-access wake + keyguard dismiss ===
@@ -673,6 +689,9 @@ class BridgeCommandHandler(
if (!isReadOnlyRoute) {
val outcome = runCatching { UnattendedAccessManager.acquireForAction() }
.getOrDefault(UnattendedAccessManager.WakeOutcome.Disabled)
if (outcome != UnattendedAccessManager.WakeOutcome.Disabled) {
unattendedWakeRequests += requestId
}
if (outcome == UnattendedAccessManager.WakeOutcome.KeyguardBlocked) {
respond(
requestId, 423,
@@ -705,6 +724,30 @@ class BridgeCommandHandler(
val executor = service.actionExecutor
when (path) {
"/events" -> {
val limitRaw = body["limit"]?.jsonPrimitive?.content?.toIntOrNull() ?: 50
val limit = limitRaw.coerceIn(1, EventStore.MAX_ENTRIES)
val since = body["since"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
val entries = EventStore.recent(limit = limit, since = since)
val arr: JsonArray = buildJsonArray {
for (e in entries) {
add(buildJsonObject {
put("timestamp", e.timestamp)
put("event_type", e.eventType)
e.packageName?.let { put("package_name", it) }
e.className?.let { put("class_name", it) }
e.text?.let { put("text", it) }
e.contentDescription?.let { put("content_description", it) }
put("source", e.source)
})
}
}
respond(requestId, 200, buildJsonObject {
put("entries", arr)
put("count", entries.size)
put("streaming", EventStore.isStreaming)
})
}
"/current_app" -> respond(
requestId, 200,
buildJsonObject {
@@ -2417,6 +2460,12 @@ class BridgeCommandHandler(
}
multiplexer.send(envelope)
}
private fun releaseUnattendedWake(requestId: String) {
if (unattendedWakeRequests.remove(requestId)) {
UnattendedAccessManager.releaseAfterAction()
}
}
}
// LocalDispatchResult moved to network.shared (ADR 34 fence): it is a passive
@@ -5,20 +5,26 @@ import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.SystemClock
import android.util.Log
import com.hermesandroid.relay.R
import com.hermesandroid.relay.auth.CertPinStore
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
import com.hermesandroid.relay.network.relay.models.Envelope
import com.hermesandroid.relay.network.shared.EndpointResolver
import com.hermesandroid.relay.network.shared.EndpointSurface
import com.hermesandroid.relay.network.shared.fullJitterDelayMs
import com.hermesandroid.relay.network.shutdownOffMainThread
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
@@ -44,6 +50,20 @@ enum class ConnectionState {
Reconnecting
}
internal fun isRelayRateLimitBackoffActive(untilMs: Long, nowMs: Long): Boolean =
untilMs > nowMs
internal fun canOverrideScheduledRelayReconnect(
state: ConnectionState,
backoffWaiting: Boolean,
rateLimitBackoffActive: Boolean,
): Boolean = !rateLimitBackoffActive && when (state) {
ConnectionState.Disconnected -> true
ConnectionState.Reconnecting -> backoffWaiting
ConnectionState.Connecting,
ConnectionState.Connected -> false
}
/**
* Build an OkHttp request for a relay socket URL, or `null` if the URL is
* malformed. OkHttp's [Request.Builder.url] throws [IllegalArgumentException]
@@ -58,6 +78,9 @@ internal fun buildRelayRequestOrNull(url: String): Request? =
null
}
private fun EndpointCandidate.relayWebSocketUrl(): String? =
pluginProxyRoutesOrNull()?.relayWebSocketUrl ?: relay?.url
class ConnectionManager(
private val multiplexer: ChannelMultiplexer,
/**
@@ -121,6 +144,12 @@ class ConnectionManager(
* non-null — the manager falls back to the single-URL path.
*/
private val deviceIdProvider: (suspend () -> String?)? = null,
/** Random source for ordinary reconnect full-jitter; exact backoffs never use it. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
/** Exact-authority pinned client for a plugin-proxy WSS URL. */
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
/** Test seam for observing lifecycle teardown without opening a socket. */
private val okHttpClientFactory: (() -> OkHttpClient)? = null,
) {
private val supervisorJob = SupervisorJob()
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
@@ -130,7 +159,8 @@ class ConnectionManager(
encodeDefaults = true
}
private fun buildClient(): OkHttpClient {
private fun buildClient(url: String? = null): OkHttpClient {
okHttpClientFactory?.let { return it() }
val builder = OkHttpClient.Builder()
// OkHttp's 10s default connectTimeout is LAN-tuned; a Tailscale
// DERP-relayed cold-start handshake can exceed it, and a failed
@@ -144,7 +174,9 @@ class ConnectionManager(
// that wipes a pin would still be subject to the pre-wipe rules.
certPinStore?.let { store ->
try {
builder.certificatePinner(store.buildPinnerSnapshot())
builder.certificatePinner(
url?.let(store::buildPinnerSnapshotFor) ?: store.buildPinnerSnapshot(),
)
} catch (e: Exception) {
Log.w(TAG, "CertificatePinner build failed: ${e.message}")
builder.certificatePinner(CertificatePinner.DEFAULT)
@@ -161,7 +193,11 @@ class ConnectionManager(
@Volatile
private var serverUrl: String? = null
private var reconnectAttempt = 0
private val reconnectState = RelayReconnectState()
@Volatile
private var reconnectJob: Job? = null
@Volatile
private var reconnectBackoffWaiting = false
private var shouldReconnect = true
// Last HTTP status seen during WSS upgrade, captured in onFailure.
// Used by scheduleReconnect() to pick an appropriate backoff — notably
@@ -169,14 +205,8 @@ class ConnectionManager(
// we don't re-fill the ban bucket and brick our own auth window.
@Volatile
private var lastUpgradeResponseCode: Int? = null
// Consecutive relay socket failures (response == null) since the last
// successful onOpen. One slow Tailscale/DERP cold-start handshake must not
// immediately evict the active route from the SHARED resolver cache (chat +
// dashboard ride the same resolver), so we only poison the route after a
// couple of consecutive transport-level failures.
@Volatile
private var consecutiveSocketFailures = 0
private var rateLimitBackoffUntilMs: Long = 0L
// The relay requires the FIRST frame on a socket to be `system/auth` and
// rejects the whole connection otherwise ("expected system/auth, got
@@ -205,6 +235,12 @@ class ConnectionManager(
// Endpoints card in Settings.
private val _activeEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeEndpoint: StateFlow<EndpointCandidate?> = _activeEndpoint.asStateFlow()
private val _activeApiEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeApiEndpoint: StateFlow<EndpointCandidate?> = _activeApiEndpoint.asStateFlow()
/** Relay-only winner, deliberately separate from the standard route. */
private val _activeRelayEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeRelayEndpoint: StateFlow<EndpointCandidate?> = _activeRelayEndpoint.asStateFlow()
/**
* Manual role override. When non-null, the resolver's output is replaced
@@ -262,9 +298,9 @@ class ConnectionManager(
private const val TAG = "ConnectionManager"
private const val MAX_BACKOFF_MS = 30_000L
private const val BASE_BACKOFF_MS = 1_000L
// How many consecutive relay socket failures before we mark the active
// endpoint unreachable in the shared resolver cache. Tolerates a single
// cold-start blip on a slow remote (Tailscale DERP) link.
// How many consecutive failures on one relay socket URL before we mark
// that candidate's Relay surface unreachable. Standard Dashboard/API
// reachability is cached independently and remains healthy.
private const val MARK_UNREACHABLE_AFTER_FAILURES = 2
// Settle window before re-resolving after a network event. Long
// enough to coalesce the onAvailable burst of a handoff, short
@@ -325,17 +361,22 @@ class ConnectionManager(
// behavior for freshly-upgraded installs and for v1/v2 QRs where
// the synthesized list just collapses to the same URL anyway.
scope.launch {
val resolved = resolveBestEndpointSafe()
val resolvedRelayUrl = resolved?.relay?.url?.takeIf { it.isNotBlank() }
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
_activeRelayEndpoint.value = relayResolved
_activeApiEndpoint.value = apiResolved
if (resolved != null) {
_activeEndpoint.value = resolved
Log.i(TAG, "connect: resolver picked role=${resolved.role} " +
"route=${resolved.primaryRouteUrl()} (relay fallback would have been $url)")
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
"route=${resolved.primaryRouteUrl()}")
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
category = DiagnosticCategory.Endpoint,
severity = DiagnosticSeverity.Info,
title = context?.getString(R.string.conn_diag_route_selected) ?: "Relay route selected",
title = context?.getString(R.string.conn_diag_route_selected) ?: "Route selected",
endpointRole = resolved.role,
url = resolved.primaryRouteUrl(),
)
@@ -350,6 +391,13 @@ class ConnectionManager(
url = url,
)
}
relayResolved?.let { relayRoute ->
Log.i(
TAG,
"connect: relay resolver picked role=${relayRoute.role} " +
"url=${relayRoute.relayWebSocketUrl()}",
)
}
if (targetUrl != null) {
connectToUrlOnMainPath(targetUrl)
} else {
@@ -358,6 +406,41 @@ class ConnectionManager(
}
}
/**
* Replace an ordinary scheduled reconnect with an immediate attempt.
*
* Foregrounding the app or opening Relay status is an explicit signal that
* the route may be usable again, so exponential/slow-poll backoff should not
* make the user wait. A server-issued 429 is different: retrying early would
* extend the server block, so that protected backoff is never overridden.
*/
fun reconnectNowIfAllowed(url: String): Boolean {
val rateLimitActive = isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
SystemClock.elapsedRealtime(),
)
if (!canOverrideScheduledRelayReconnect(
state = _connectionState.value,
backoffWaiting = reconnectBackoffWaiting,
rateLimitBackoffActive = rateLimitActive,
)
) {
if (rateLimitActive) {
Log.i(TAG, "reconnectNowIfAllowed: preserving rate-limit backoff")
}
return false
}
reconnectJob?.cancel()
reconnectJob = null
reconnectBackoffWaiting = false
// connectToUrlOnMainPath suppresses duplicate opens while the manager is
// Reconnecting. Move to the honest idle state before starting the fresh
// resolver/open path; the ViewModel's grace window prevents UI flicker.
_connectionState.value = ConnectionState.Disconnected
connect(url)
return true
}
/**
* Same as [connect] but bypasses the resolver — used by the network-
* change callback when we've already picked a winner and just want to
@@ -368,6 +451,7 @@ class ConnectionManager(
private fun connectToUrlOnMainPath(
url: String,
replaceReason: String = "Relay socket replaced",
preserveReconnectBackoff: Boolean = false,
) {
val isInsecure = url.startsWith("ws://") && !url.startsWith("wss://")
if (isInsecure && !_insecureMode.value) {
@@ -377,7 +461,9 @@ class ConnectionManager(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.conn_diag_socket_blocked) ?: "Relay socket blocked",
detail = "ws:// is disabled",
url = url,
operation = "Open Relay WebSocket",
configuredUrl = url,
suggestion = "Use wss:// or explicitly allow plain ws:// for a trusted LAN or VPN.",
)
return
}
@@ -388,7 +474,9 @@ class ConnectionManager(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.conn_diag_url_invalid) ?: "Relay socket URL invalid",
detail = "URL must start with ws:// or wss://",
url = url,
operation = "Open Relay WebSocket",
configuredUrl = url,
suggestion = "Edit or re-pair the Relay route with a ws:// or wss:// URL.",
)
return
}
@@ -398,6 +486,14 @@ class ConnectionManager(
// hits the HTTP root and comes back as 404 Not Found during the
// upgrade handshake. We still accept an explicit path if present.
val normalized = normalizeRelayUrl(url)
if (isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
SystemClock.elapsedRealtime(),
)
) {
Log.i(TAG, "connect: preserving active rate-limit backoff")
return
}
val existingState = _connectionState.value
if (serverUrl == normalized &&
(existingState == ConnectionState.Connecting ||
@@ -416,20 +512,28 @@ class ConnectionManager(
category = DiagnosticCategory.Relay,
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.conn_diag_opening_insecure) ?: "Opening insecure relay socket",
url = normalized,
operation = "Open Relay WebSocket",
configuredUrl = url,
requestUrl = normalized,
)
} else {
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
severity = DiagnosticSeverity.Info,
title = context?.getString(R.string.conn_diag_opening_socket) ?: "Opening relay socket",
url = normalized,
operation = "Open Relay WebSocket",
configuredUrl = url,
requestUrl = normalized,
)
}
serverUrl = normalized
shouldReconnect = true
reconnectAttempt = 0
if (preserveReconnectBackoff) {
reconnectState.beginAutomaticRouteSwap(normalized)
} else {
reconnectState.beginExplicitConnect(normalized)
}
doConnect(normalized, previousSocket, replaceReason)
}
@@ -445,9 +549,13 @@ class ConnectionManager(
* Wraps the DataStore read in a 1-second timeout; if DataStore stalls
* for any reason we don't block the connect loop forever.
*/
suspend fun resolveBestEndpoint(): EndpointCandidate? = resolveBestEndpointSafe()
suspend fun resolveBestEndpoint(): EndpointCandidate? =
resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
private suspend fun resolveBestEndpointSafe(): EndpointCandidate? {
private suspend fun resolveBestEndpointSafe(
surface: EndpointSurface,
): EndpointCandidate? {
val resolver = endpointResolver ?: return null
val ctx = context ?: return null
@@ -486,14 +594,14 @@ class ConnectionManager(
}
if (preferred != null) {
// Single-element list still respects the 2s probe gate.
val winner = resolver.resolve(listOf(preferred))
val winner = resolver.resolve(listOf(preferred), surface)
if (winner != null) return winner
Log.i(TAG, "manualRoleOverride=$preferredRole not reachable — " +
"falling through to strict-priority resolve")
}
}
return resolver.resolve(endpoints)
return resolver.resolve(endpoints, surface)
}
/**
@@ -521,7 +629,10 @@ class ConnectionManager(
suspend fun probeAndReconnectNow(): EndpointCandidate? {
endpointResolver?.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe()
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
// — keep the live route published rather than downgrading every
@@ -529,7 +640,9 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
val targetUrl = resolved?.relay?.url ?: current ?: return resolved
_activeApiEndpoint.value = apiResolved
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
val normalizedTarget = normalizeRelayUrl(targetUrl)
// Reconnect when the winner changed, and also when the socket is
// stale/disconnected on the same winner. The latter makes the
@@ -566,7 +679,9 @@ class ConnectionManager(
*/
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
if (clearProbeCache) endpointResolver?.clearCache()
val resolved = resolveBestEndpointSafe()
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
// (slow resume, mid-handoff blip) — keep publishing the live
@@ -575,6 +690,7 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
return resolved
}
@@ -590,9 +706,9 @@ class ConnectionManager(
fun getManualRoleOverride(): String? = _manualRoleOverride.value
private fun markActiveEndpointUnreachable(reason: String) {
val active = _activeEndpoint.value ?: return
endpointResolver?.markUnreachable(active)
private fun markActiveRelayEndpointUnreachable(reason: String) {
val active = _activeRelayEndpoint.value ?: return
endpointResolver?.markUnreachable(active, EndpointSurface.Relay)
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
}
@@ -615,9 +731,11 @@ class ConnectionManager(
// Tailscale's tun churns onAvailable repeatedly — coalesces into a
// single cache wipe + re-probe instead of one per event. onLost
// manages its own cache (clear + markUnreachable) and passes false.
if (wipeCache) endpointResolver?.clearCache()
if (wipeCache) endpointResolver.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe()
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null) {
// Hysteresis for the AUTOMATIC (network-callback) path. A
// transient cold-route probe miss must NOT null the published
@@ -654,6 +772,7 @@ class ConnectionManager(
}
sustainedLossDeclared = false
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
if (current == null) return@launch
// After an explicit disconnect() the route still publishes above
// (HTTP surfaces keep roaming), but no socket action: without
@@ -662,11 +781,34 @@ class ConnectionManager(
// (connectToUrlOnMainPath force-sets shouldReconnect = true, so
// the swap path never re-checked it.)
if (!shouldReconnect) return@launch
val relayUrl = resolved.relay?.url?.takeIf { it.isNotBlank() } ?: return@launch
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
?: return@launch
if (isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
SystemClock.elapsedRealtime(),
)
) {
// Keep publishing the newly resolved standard/Relay routes, but
// leave the protected retry job intact. It will resolve the
// latest Relay winner again when the server cooldown expires.
Log.i(TAG, "network change: preserving rate-limit retry job")
return@launch
}
val normalizedNew = normalizeRelayUrl(relayUrl)
if (normalizedNew != current) {
Log.i(TAG, "network change: swapping $current → $normalizedNew")
connectToUrlOnMainPath(relayUrl, closeReason)
if (reconnectBackoffWaiting) {
reconnectJob?.cancel()
reconnectJob = null
reconnectBackoffWaiting = false
}
connectToUrlOnMainPath(
relayUrl,
closeReason,
preserveReconnectBackoff = true,
)
} else if (_connectionState.value == ConnectionState.Disconnected &&
reconnectGate()
) {
@@ -708,7 +850,9 @@ class ConnectionManager(
Log.i(TAG, "network loss sustained past grace — marking active endpoint unreachable and resolving fallback")
sustainedLossDeclared = true
endpointResolver?.clearCache()
markActiveEndpointUnreachable("network lost (sustained)")
_activeEndpoint.value?.let { active ->
endpointResolver?.markUnreachable(active, EndpointSurface.Standard)
}
// wipeCache=false: we just cleared + poisoned the dead route
// above; re-wiping inside the job would drop that negative
// entry and let the dead route win the resolve again.
@@ -762,6 +906,11 @@ class ConnectionManager(
fun disconnect() {
shouldReconnect = false
reconnectJob?.cancel()
reconnectJob = null
reconnectBackoffWaiting = false
rateLimitBackoffUntilMs = 0L
lastUpgradeResponseCode = null
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
severity = DiagnosticSeverity.Info,
@@ -779,6 +928,9 @@ class ConnectionManager(
// the ViewModel on the next connection load.
_manualRoleOverride.value = null
_activeEndpoint.value = null
_activeApiEndpoint.value = null
_activeRelayEndpoint.value = null
reconnectState.reset()
}
fun shutdown() {
@@ -815,19 +967,28 @@ class ConnectionManager(
url: String,
previousSocketToClose: WebSocket? = null,
replaceReason: String = "Relay socket replaced",
scheduledReconnect: Boolean = false,
) {
if (isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
SystemClock.elapsedRealtime(),
)
) {
Log.i(TAG, "doConnect: preserving active rate-limit backoff")
return
}
val existingState = _connectionState.value
if (previousSocketToClose == null &&
serverUrl == url &&
(existingState == ConnectionState.Connecting ||
existingState == ConnectionState.Connected ||
existingState == ConnectionState.Reconnecting)
(existingState == ConnectionState.Reconnecting && !scheduledReconnect))
) {
Log.i(TAG, "doConnect: already ${existingState.name.lowercase()} to $url — skipping duplicate open")
return
}
_connectionState.value = if (reconnectAttempt > 0) {
_connectionState.value = if (reconnectState.reconnectAttempt > 0) {
ConnectionState.Reconnecting
} else {
ConnectionState.Connecting
@@ -848,7 +1009,18 @@ class ConnectionManager(
// Every new socket starts unauthenticated — the send-gate stays closed
// (auth frame excepted) until this socket's own auth.ok arrives.
authenticated = false
client = buildClient()
val isPluginProxyUrl = _activeRelayEndpoint.value?.pluginProxyRoutesOrNull()
?.relayWebSocketUrl
?.equals(url, ignoreCase = true) == true
client = if (isPluginProxyUrl) {
proxyClientProvider?.invoke(url) ?: run {
Log.e(TAG, "Pinned plugin proxy client unavailable — refusing generic TLS fallback")
_connectionState.value = ConnectionState.Disconnected
return
}
} else {
buildClient(url)
}
val request = buildRelayRequestOrNull(url)
if (request == null) {
@@ -863,7 +1035,9 @@ class ConnectionManager(
severity = DiagnosticSeverity.Error,
title = "Invalid relay URL",
detail = "The relay address could not be parsed; re-pair to refresh it.",
url = url,
operation = "Build Relay WebSocket request",
configuredUrl = url,
suggestion = "Edit or re-pair the Relay route to replace the invalid address.",
)
authenticated = false
_connectionState.value = ConnectionState.Disconnected
@@ -884,16 +1058,20 @@ class ConnectionManager(
webSocket.cancel()
return
}
reconnectAttempt = 0
reconnectState.connected(url)
reconnectJob?.cancel()
reconnectJob = null
reconnectBackoffWaiting = false
rateLimitBackoffUntilMs = 0L
lastUpgradeResponseCode = null
consecutiveSocketFailures = 0
_connectionState.value = ConnectionState.Connected
Log.i(TAG, "onOpen: WSS handshake complete ($url)")
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
severity = DiagnosticSeverity.Info,
title = context?.getString(R.string.conn_diag_connected) ?: "Relay socket connected",
url = url,
operation = "Relay WebSocket handshake",
requestUrl = url,
)
// TOFU: record the peer cert fingerprint if we don't have one
@@ -954,7 +1132,9 @@ class ConnectionManager(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.conn_diag_closed) ?: "Relay socket closed",
detail = "code=$code reason=$reason",
url = url,
operation = "Relay WebSocket session",
requestUrl = url,
suggestion = if (code == 1000) null else "Check the Relay server logs for the matching close code and reason.",
)
authenticated = false
_connectionState.value = ConnectionState.Disconnected
@@ -977,20 +1157,24 @@ class ConnectionManager(
t.message,
code?.let { "HTTP $it" },
).joinToString(": "),
url = url,
operation = "Relay WebSocket handshake",
requestUrl = url,
suggestion = code?.let {
NetworkDiagnosticGuidance.forHttpStatus(it, "Relay")
} ?: NetworkDiagnosticGuidance.forThrowable(t, "Relay"),
)
lastUpgradeResponseCode = code
if (response == null) {
// Transport-level failure (no HTTP upgrade response): on a
// remote (Tailscale) link the first handshake can fail cold.
// Don't evict the only working route from the shared resolver
// on a single blip — wait for it to repeat. A genuinely
// sustained network loss is handled separately by onLost.
consecutiveSocketFailures++
if (consecutiveSocketFailures >= MARK_UNREACHABLE_AFTER_FAILURES) {
markActiveEndpointUnreachable("socket failure x$consecutiveSocketFailures")
// Don't evict this Relay surface on a single blip — wait
// for the same socket URL to fail again. Standard route
// health is separate and is never poisoned here.
val failureCount = reconnectState.recordSocketFailure(url)
if (failureCount >= MARK_UNREACHABLE_AFTER_FAILURES) {
markActiveRelayEndpointUnreachable("socket failure x$failureCount")
} else {
Log.i(TAG, "relay socket failure $consecutiveSocketFailures/$MARK_UNREACHABLE_AFTER_FAILURES — not yet poisoning route")
Log.i(TAG, "relay socket failure $failureCount/$MARK_UNREACHABLE_AFTER_FAILURES — not yet poisoning route")
}
}
authenticated = false
@@ -1029,7 +1213,12 @@ class ConnectionManager(
}
val url = serverUrl ?: return
reconnectAttempt++
val reconnectAttempt = reconnectState.nextReconnectAttempt()
// Keep the socket lifecycle visibly in-flight for the whole backoff
// window. Callers such as reconnectIfStale() treat Disconnected as an
// invitation to call connect() again; leaving this state Disconnected
// let screen entry restart both the route resolve and the retry counter.
_connectionState.value = ConnectionState.Reconnecting
// Server-issued 429 means we're IP-banned — keep retrying at our
// normal exponential cadence and we'll re-fill the ban bucket on
@@ -1040,6 +1229,7 @@ class ConnectionManager(
// block window instead of re-filling the ban bucket at our normal
// cadence.
lastUpgradeResponseCode == 429 -> {
rateLimitBackoffUntilMs = SystemClock.elapsedRealtime() + RATE_LIMIT_BACKOFF_MS
Log.i(TAG, "scheduleReconnect: rate-limited (429) — backing off ${RATE_LIMIT_BACKOFF_MS}ms")
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
@@ -1064,8 +1254,9 @@ class ConnectionManager(
SLOW_POLL_BACKOFF_MS
}
else -> {
val ms = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
val capMs = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
.coerceAtMost(MAX_BACKOFF_MS)
val ms = fullJitterDelayMs(capMs, reconnectJitterUnit())
DiagnosticsLog.record(
category = DiagnosticCategory.Relay,
severity = DiagnosticSeverity.Info,
@@ -1077,14 +1268,17 @@ class ConnectionManager(
}
}
scope.launch {
reconnectJob?.cancel()
reconnectBackoffWaiting = true
val scheduledJob = scope.launch {
delay(backoffMs)
reconnectBackoffWaiting = false
// Re-check the gate after the backoff — by the time the delay
// expires, auth state may have changed (e.g., user hit Revoke
// during the retry window).
if (shouldReconnect && reconnectGate()) {
val resolved = resolveBestEndpointSafe()
val targetUrl = resolved?.relay?.url
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val targetUrl = resolved?.relayWebSocketUrl()
if (resolved != null) {
// Mirror scheduleNetworkReResolve: clear the sustained-loss
// latch on a successful resolve so a later transient miss
@@ -1092,24 +1286,28 @@ class ConnectionManager(
// in onLost's grace job but can be cleared on EITHER success
// edge — network-callback or relay-timer.)
sustainedLossDeclared = false
_activeEndpoint.value = resolved
} else if (sustainedLossDeclared || _activeEndpoint.value == null) {
// Same hysteresis as scheduleNetworkReResolve: a transient
// miss during a relay reconnect must not flip every effective
// URL back to the dead saved host. Keep the last-known route;
// we fall through to doConnect(url) and retry it with backoff.
_activeEndpoint.value = null
_activeRelayEndpoint.value = resolved
}
if (targetUrl != null && normalizeRelayUrl(targetUrl) != url) {
Log.i(TAG, "scheduleReconnect: switching $url → ${normalizeRelayUrl(targetUrl)}")
connectToUrlOnMainPath(targetUrl)
connectToUrlOnMainPath(
targetUrl,
preserveReconnectBackoff = true,
)
} else {
doConnect(url)
doConnect(url, scheduledReconnect = true)
}
} else if (!reconnectGate()) {
Log.i(TAG, "scheduleReconnect: gate turned false during backoff — aborting retry")
_connectionState.value = ConnectionState.Disconnected
}
}
reconnectJob = scheduledJob
scheduledJob.invokeOnCompletion {
if (reconnectJob === scheduledJob) {
reconnectJob = null
reconnectBackoffWaiting = false
}
}
}
}
@@ -5,7 +5,9 @@ import android.util.Log
import com.hermesandroid.relay.network.relay.models.Envelope
import com.hermesandroid.relay.notifications.ProactiveMessageNotifier
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
/**
@@ -50,7 +52,7 @@ class ProactiveMessageHandler(
/** Sink for the dedicated Hermes inbox (Phase 2a) — the always-present log. */
private val toInbox: ((ProactiveMessage) -> Unit)? = null,
/** Sink for injecting into the active chat session (Phase 2b). */
var toSession: ((ProactiveMessage) -> Unit)? = null,
var toSession: ((ProactiveMessage) -> Boolean)? = null,
/**
* Sink for the relay's per-reply ack (`proactive.reply.ack`) — lets the
* chat layer settle a Thread reply bubble from SENDING → DELIVERED. Wired
@@ -61,11 +63,13 @@ class ProactiveMessageHandler(
/**
* Show an inbound message inline in the Chat **Thread** it belongs to, when
* that Thread is currently open. Returns true if it was shown there — in
* which case the message is NOT also notified or added to the inbox (you're
* already looking at the conversation). The unified-Threads counterpart of
* which case the message is persisted but not also notified (you're already
* looking at the conversation). The unified-Threads counterpart of
* [toSession]; wired after construction.
*/
var injectIntoThread: ((ProactiveMessage) -> Boolean)? = null,
/** One callback per completed queued-message flush, never per message. */
var onBacklogDelivered: ((Int) -> Unit)? = null,
) {
fun onMessage(envelope: Envelope) {
@@ -80,6 +84,10 @@ class ProactiveMessageHandler(
}
// Subscribe ack — informational; nothing to do client-side.
"proactive.subscribed" -> Log.d(TAG, "proactive subscribe acked")
"proactive.backlog.complete" -> {
val count = envelope.payload["count"]?.jsonPrimitive?.intOrNull ?: 0
if (count > 0) onBacklogDelivered?.invoke(count)
}
// Per-reply ack — settle the matching Thread reply bubble (the
// `client_msg_id` is the id the app stamped on its own reply).
"proactive.reply.ack" -> {
@@ -94,24 +102,28 @@ class ProactiveMessageHandler(
/** Route a parsed message: into the open Thread if it belongs there, else
* the durable inbox log + the surface its hint selects. */
private fun dispatch(msg: ProactiveMessage) {
// Unified Threads: if this message belongs to the Thread currently open
// in Chat, render it inline there and STOP — no notification, no inbox
// entry (you're already looking at the conversation).
if (injectIntoThread?.invoke(msg) == true) return
// Otherwise the inbox is the durable log of agent-initiated messages and
// the surfacing hint selects the additional surface.
// Persist first even when the currently open Thread consumes the live
// message. Agent-initiated outbound sends do not create a gateway
// session until the phone replies, so this cache is the provisional
// Thread transcript during that gap.
toInbox?.invoke(msg)
// The surfacing hint selects the additional surface. Thread injection
// is best-effort presentation of the persisted row, not itself a reason
// to suppress an explicitly requested notification.
when (msg.surfacing?.lowercase()) {
"inbox" -> { /* inbox only — already recorded above */ }
"inbox" -> {
injectIntoThread?.invoke(msg)
}
"session" -> {
val sink = toSession
// Legacy explicit "inject into active session" path; if no sink
// (or no active chat) fall back to a notification so it isn't
// silently missed (the inbox copy already exists either way).
if (sink != null) sink.invoke(msg) else notify(msg)
val delivered = injectIntoThread?.invoke(msg) == true ||
toSession?.invoke(msg) == true
if (!delivered) notify(msg)
}
// null / "default" / "notification" / anything unrecognized.
else -> notify(msg)
else -> {
injectIntoThread?.invoke(msg)
notify(msg)
}
}
}
@@ -136,6 +148,7 @@ class ProactiveMessageHandler(
surfacing = payload["surfacing"]?.jsonPrimitive?.contentOrNull,
sentAt = payload["sent_at"]?.jsonPrimitive?.contentOrNull?.toLongOrNull(),
replyTo = payload["reply_to"]?.jsonPrimitive?.contentOrNull,
arrivedWhileAway = payload["queued_delivery"]?.jsonPrimitive?.booleanOrNull == true,
)
}
@@ -157,4 +170,6 @@ data class ProactiveMessage(
val sentAt: Long?,
/** Id of the message this one answers, if any (server threading hint). */
val replyTo: String? = null,
/** True only when Relay explicitly marked this as a reconnect queue flush. */
val arrivedWhileAway: Boolean = false,
)
@@ -7,10 +7,12 @@ import com.hermesandroid.relay.auth.PairedDeviceInfo
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.contentOrNull
@@ -59,6 +61,10 @@ class RelayHttpClient(
companion object {
private const val TAG = "RelayHttpClient"
const val MAX_MODEL_CAPABILITY_ROWS = 64
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
private const val MAX_MODEL_CAPABILITY_PROFILE_CHARS = 128
private val sessionsJson = Json {
ignoreUnknownKeys = true
isLenient = true
@@ -293,10 +299,10 @@ class RelayHttpClient(
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
}
} catch (e: IOException) {
Log.w(TAG, "fetchMedia failed for $token: ${e.message}")
Log.w(TAG, "fetchMedia failed: ${e.message}")
Result.failure(e)
} catch (e: Exception) {
Log.w(TAG, "fetchMedia unexpected error for $token: ${e.message}")
Log.w(TAG, "fetchMedia unexpected error: ${e.message}")
Result.failure(e)
}
}
@@ -710,6 +716,37 @@ class RelayHttpClient(
@SerialName("age_seconds") val ageSeconds: Int? = null,
)
@Serializable
data class ModelCapabilityRequestRow(
val provider: String,
val model: String,
)
@Serializable
data class ModelCapabilitiesRequest(
@SerialName("schema_version") val schemaVersion: Int = 1,
val profile: String? = null,
val refresh: Boolean = false,
val models: List<ModelCapabilityRequestRow>,
)
@Serializable
data class ModelCapabilityRow(
val provider: String,
val model: String,
val reasoning: Boolean? = null,
@SerialName("reasoning_efforts") val reasoningEfforts: List<String> = emptyList(),
@SerialName("reasoning_efforts_exact") val reasoningEffortsExact: Boolean = false,
val source: String = "",
)
@Serializable
data class ModelCapabilitiesResponse(
@SerialName("schema_version") val schemaVersion: Int = 1,
@SerialName("contract_version") val contractVersion: String = "",
val capabilities: List<ModelCapabilityRow> = emptyList(),
)
/** Fetch the installed plugin/protocol/profile capability contract. */
suspend fun fetchRelayInfo(): Result<RelayInfo?> = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
@@ -743,6 +780,64 @@ class RelayHttpClient(
}
}
/** Optional provider/model reasoning overlay; 404 and no pairing are fail-soft. */
suspend fun fetchModelCapabilities(
models: List<ModelCapabilityRequestRow>,
profile: String? = null,
refresh: Boolean = false,
): Result<ModelCapabilitiesResponse?> = withContext(Dispatchers.IO) {
val boundedModels = models
.asSequence()
.map {
ModelCapabilityRequestRow(
it.provider.trim().take(MAX_MODEL_CAPABILITY_PROVIDER_CHARS),
it.model.trim().take(MAX_MODEL_CAPABILITY_MODEL_CHARS),
)
}
.filter { it.provider.isNotEmpty() && it.model.isNotEmpty() }
.distinct()
.take(MAX_MODEL_CAPABILITY_ROWS)
.toList()
if (boundedModels.isEmpty()) return@withContext Result.success(null)
val relayUrl = relayUrlProvider()?.trim().orEmpty()
val token = sessionTokenProvider()
if (relayUrl.isEmpty() || token.isNullOrBlank()) return@withContext Result.success(null)
val base = relayUrl
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
.trimEnd('/')
val url = runCatching { "$base/relay/model-capabilities".toHttpUrl() }.getOrElse {
return@withContext Result.success(null)
}
val payload = ModelCapabilitiesRequest(
profile = profile?.trim()?.take(MAX_MODEL_CAPABILITY_PROFILE_CHARS)
?.takeIf { it.isNotEmpty() },
refresh = refresh,
models = boundedModels,
)
val request = Request.Builder()
.url(url)
.post(sessionsJson.encodeToString(payload).toRequestBody("application/json".toMediaType()))
.header("Authorization", "Bearer $token")
.header("Accept", "application/json")
.build()
try {
okHttpClient.newBuilder().callTimeout(4, java.util.concurrent.TimeUnit.SECONDS).build()
.newCall(request).execute().use { response ->
if (response.code == 404) return@withContext Result.success(null)
if (!response.isSuccessful) return@withContext Result.failure(IOException("HTTP ${response.code}"))
val body = response.body?.string().orEmpty()
val parsed = body.takeIf { it.isNotBlank() }?.let {
sessionsJson.decodeFromString(ModelCapabilitiesResponse.serializer(), it)
}
if (parsed?.schemaVersion != 1) Result.success(null) else Result.success(parsed)
}
} catch (e: Exception) {
Log.w(TAG, "fetchModelCapabilities failed: ${e.message}")
Result.failure(e)
}
}
/**
* Ask the relay whether a newer plugin release is available — it compares its
* installed version against the latest `plugin-v*` GitHub release (cached an
@@ -1139,6 +1234,7 @@ class RelayHttpClient(
logSuccess: Boolean = true,
): Result<RelayHealth> = withContext(Dispatchers.IO) {
val trimmed = relayUrl.trim()
val operation = "Relay health probe before WebSocket connection"
if (trimmed.isEmpty()) {
return@withContext Result.failure(
IllegalArgumentException("Relay URL is empty")
@@ -1159,7 +1255,9 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.http_diag_url_invalid) ?: "Relay URL invalid",
detail = e.message,
url = relayUrl,
operation = operation,
configuredUrl = relayUrl,
suggestion = "Enter a Relay URL beginning with ws:// or wss://.",
)
return@withContext Result.failure(
IOException("Invalid relay URL: ${e.message}")
@@ -1180,6 +1278,7 @@ class RelayHttpClient(
.get()
.header("Accept", "application/json")
.build()
val requestUrl = request.url.toString()
try {
fastClient.newCall(request).execute().use { response ->
@@ -1189,8 +1288,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = "HTTP ${response.code}",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forHttpStatus(response.code, "Relay"),
)
return@withContext Result.failure(
IOException("Relay responded HTTP ${response.code}")
@@ -1203,8 +1305,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = "Empty response",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = "Verify this route points to a Hermes-Relay server and inspect its logs.",
)
return@withContext Result.failure(
IOException("Relay returned an empty response")
@@ -1220,8 +1325,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = "Non-JSON response",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = "Verify this route points to a Hermes-Relay server rather than another HTTP service.",
)
return@withContext Result.failure(
IOException("Relay returned non-JSON: ${e.message ?: "parse error"}")
@@ -1234,8 +1342,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = "status=${status ?: "missing"}",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = "Check the Relay service health and server logs.",
)
return@withContext Result.failure(
IOException("Relay reports status=${status ?: "missing"} (expected 'ok')")
@@ -1248,8 +1359,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = "Missing version field",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = "Verify this route points to a current Hermes-Relay server.",
)
return@withContext Result.failure(
IOException("Response doesn't look like a hermes-relay — missing 'version' field")
@@ -1265,7 +1379,9 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Info,
title = context?.getString(R.string.http_diag_health_ok) ?: "Relay health ok",
detail = "version=$version clients=$clients sessions=$sessions",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
)
}
@@ -1278,8 +1394,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_timeout) ?: "Relay health timeout",
detail = "No HTTP response in 3s",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forThrowable(e, "Relay"),
)
Result.failure(IOException("Relay is not responding (3s timeout)"))
} catch (e: java.net.ConnectException) {
@@ -1289,8 +1408,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.http_diag_conn_refused) ?: "Relay connection refused",
detail = e.message,
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forThrowable(e, "Relay"),
)
Result.failure(IOException("Connection refused — is the relay running on this URL?"))
} catch (e: IOException) {
@@ -1300,8 +1422,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = e.message ?: "Network error",
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forThrowable(e, "Relay"),
)
Result.failure(IOException("Network error: ${e.message ?: "unreachable"}"))
} catch (e: Exception) {
@@ -1311,8 +1436,11 @@ class RelayHttpClient(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.http_diag_health_failed) ?: "Relay health failed",
detail = e.message ?: e.javaClass.simpleName,
url = httpBase,
operation = operation,
configuredUrl = trimmed,
requestUrl = requestUrl,
elapsedMs = System.currentTimeMillis() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forThrowable(e, "Relay"),
)
Result.failure(e)
}
@@ -7,6 +7,8 @@ import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerializationException
@@ -48,7 +50,7 @@ class RelayProfileInspectorClient(
private val okHttpClient: OkHttpClient,
private val relayUrlProvider: () -> String?,
private val sessionTokenProvider: suspend () -> String?,
) {
) : LegacyProfileInspectorClient {
companion object {
private const val TAG = "RelayProfileInspector"
@@ -79,19 +81,19 @@ class RelayProfileInspectorClient(
/** Fetch `GET /api/profiles/{name}/config`. */
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
get(profileName, "config", ProfileConfigResponse.serializer())
/** Fetch `GET /api/profiles/{name}/skills`. */
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
override suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
get(profileName, "skills", ProfileSkillsResponse.serializer())
/** Fetch `GET /api/profiles/{name}/soul`. */
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
override suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
get(profileName, "soul", ProfileSoulResponse.serializer())
/** Fetch `GET /api/profiles/{name}/memory`. */
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
override suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
get(profileName, "memory", ProfileMemoryResponse.serializer())
/**
@@ -108,7 +110,7 @@ class RelayProfileInspectorClient(
* would be a protocol violation; we send empty-string for an empty
* SOUL.
*/
suspend fun updateSoul(
override suspend fun updateSoul(
profileName: String,
content: String,
): Result<ProfileSoulUpdateResponse> = withContext(Dispatchers.IO) {
@@ -137,7 +139,7 @@ class RelayProfileInspectorClient(
* Used for both creating a new memory entry (the relay writes the
* file if missing) and updating an existing entry.
*/
suspend fun updateMemoryEntry(
override suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
@@ -270,10 +272,10 @@ class RelayProfileInspectorClient(
* server" snackbar and ghost out the toggle. When the real
* implementation lands server-side, this method needs no change.
*/
suspend fun updateSkillToggle(
override suspend fun updateSkillToggle(
skillName: String,
enabled: Boolean,
): Result<SkillToggleResult> = withContext(Dispatchers.IO) {
): Result<RelaySkillToggleResult> = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) {
return@withContext Result.failure(
@@ -319,8 +321,8 @@ class RelayProfileInspectorClient(
try {
okHttpClient.newCall(request).execute().use { response ->
when (response.code) {
in 200..299 -> Result.success(SkillToggleResult.Ok)
501 -> Result.success(SkillToggleResult.NotImplemented)
in 200..299 -> Result.success(RelaySkillToggleResult.Ok)
501 -> Result.success(RelaySkillToggleResult.NotImplemented)
401, 403 -> Result.failure(
IOException("Unauthorized — re-pair with the relay")
)
@@ -348,7 +350,7 @@ class RelayProfileInspectorClient(
* "not implemented" and any 2xx as "supported". The relay serves
* OPTIONS via aiohttp's CORS handling by default.
*/
suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
override suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) return@withContext false
val sessionToken = sessionTokenProvider() ?: return@withContext false
@@ -402,11 +404,6 @@ class RelayProfileInspectorClient(
* answered 501 — not implemented yet" without inventing magic
* error strings.
*/
sealed class SkillToggleResult {
data object Ok : SkillToggleResult()
data object NotImplemented : SkillToggleResult()
}
/**
* Best-effort pull of a `detail` or `error` string out of a relay
* 400 body. Falls back to the first 120 chars of the payload when
@@ -0,0 +1,61 @@
package com.hermesandroid.relay.network.relay
/**
* Route-aware retry state for the Relay WebSocket.
*
* Automatic LAN/Tailscale fallback keeps the accumulated reconnect attempt so
* swapping URLs cannot restart exponential backoff. Socket-failure streaks are
* scoped to one URL, so failures on different roles cannot combine and poison
* the newly selected route.
*/
internal class RelayReconnectState {
@Volatile
var reconnectAttempt: Int = 0
private set
private var socketFailureRoute: String? = null
private var consecutiveSocketFailures: Int = 0
@Synchronized
fun beginExplicitConnect(route: String) {
reconnectAttempt = 0
resetSocketFailures(route)
}
@Synchronized
fun beginAutomaticRouteSwap(route: String) {
resetSocketFailures(route)
}
@Synchronized
fun nextReconnectAttempt(): Int {
reconnectAttempt++
return reconnectAttempt
}
@Synchronized
fun recordSocketFailure(route: String): Int {
if (socketFailureRoute != route) {
resetSocketFailures(route)
}
consecutiveSocketFailures++
return consecutiveSocketFailures
}
@Synchronized
fun connected(route: String) {
reconnectAttempt = 0
resetSocketFailures(route)
}
@Synchronized
fun reset() {
reconnectAttempt = 0
resetSocketFailures(null)
}
private fun resetSocketFailures(route: String?) {
socketFailureRoute = route
consecutiveSocketFailures = 0
}
}
@@ -98,6 +98,7 @@ class RelayVoiceClient(
private val webSocketFactory: ((Request, WebSocketListener) -> WebSocket)? = null,
private val realtimeResumeRetryIntervalMs: Long = REALTIME_RESUME_RETRY_INTERVAL_MS,
private val realtimeResumeRetryWindowMs: Long = REALTIME_RESUME_RETRY_WINDOW_MS,
private val voiceOutputFirstAudioTimeoutMs: Long = VOICE_OUTPUT_FIRST_AUDIO_TIMEOUT_MS,
) {
companion object {
@@ -108,6 +109,7 @@ class RelayVoiceClient(
private val WAV_AUDIO = "audio/wav".toMediaType()
private val OCTET_STREAM = "application/octet-stream".toMediaType()
private const val REALTIME_TIMEOUT_MS = 90_000L
private const val VOICE_OUTPUT_FIRST_AUDIO_TIMEOUT_MS = 15_000L
private const val REALTIME_AGENT_IDLE_TIMEOUT_MS = 90_000L
private const val REALTIME_AGENT_MAX_TURN_MS = 5 * 60_000L
private const val REALTIME_AGENT_WAIT_SLICE_MS = 1_000L
@@ -867,6 +869,7 @@ class RelayVoiceClient(
val resumeAttempted = AtomicBoolean(false)
val routeProbeRequested = AtomicBoolean(false)
val currentSocket = AtomicReference<WebSocket?>()
val firstAudioSeen = AtomicBoolean(false)
val socketGeneration = AtomicLong(0L)
val activeSocketGeneration = AtomicLong(0L)
val lastEventId = AtomicLong(0L)
@@ -980,6 +983,7 @@ class RelayVoiceClient(
}
onEvent(event)
if (event.isAudioDelta) {
firstAudioSeen.set(true)
event.audioEventId?.let {
lastPlayedAudioEventId.updateAndGet { current -> maxOf(current, it) }
}
@@ -1123,6 +1127,15 @@ class RelayVoiceClient(
onHandoff = onHandoff,
completeFailure = ::completeFailure,
)
val firstAudioWatchdog = launch {
delay(voiceOutputFirstAudioTimeoutMs)
if (!completed.get() && !firstAudioSeen.get()) {
completeFailure(
"Voice output produced no audio within ${voiceOutputFirstAudioTimeoutMs}ms",
)
currentSocket.get()?.cancel()
}
}
try {
withTimeout(REALTIME_TIMEOUT_MS) {
finished.await()
@@ -1132,6 +1145,7 @@ class RelayVoiceClient(
socket.close(1001, "timeout")
Result.failure(IOException("Voice output timed out", e))
} finally {
firstAudioWatchdog.cancel()
routeWatcher?.cancel()
}
}
@@ -0,0 +1,41 @@
package com.hermesandroid.relay.network.shared
import okhttp3.Request
import java.io.IOException
/** Secret-free failure raised before OkHttp sees a malformed credential. */
class InvalidCredentialException internal constructor(message: String) : IOException(message)
/**
* Normalize only harmless surrounding horizontal whitespace. Credentials are
* otherwise single-line visible ASCII: embedded whitespace, CR/LF, controls,
* and non-ASCII input are rejected instead of repaired or logged.
*/
fun normalizeCredentialForHeader(raw: String, label: String): String {
val normalized = raw.trim(' ', '\t')
if (normalized.any { it < '!' || it > '~' }) {
throw InvalidCredentialException(
"Invalid $label — enter or import a single-line value.",
)
}
return normalized
}
fun Request.Builder.bearerAuthorization(
rawCredential: String,
label: String,
): Request.Builder {
val credential = normalizeCredentialForHeader(rawCredential, label)
if (credential.isEmpty()) return this
return header("Authorization", "Bearer $credential")
}
fun Request.Builder.credentialHeader(
name: String,
rawCredential: String,
label: String,
): Request.Builder {
val credential = normalizeCredentialForHeader(rawCredential, label)
if (credential.isEmpty()) return this
return header(name, credential)
}
@@ -9,6 +9,7 @@ import com.hermesandroid.relay.data.routeAuthority
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
@@ -47,6 +48,18 @@ data class RouteProbeOutcome(
val atMillis: Long,
)
/**
* Service whose reachability is being resolved. Standard Hermes surfaces and
* Relay are intentionally independent: a healthy Dashboard must not vouch for
* a dead Relay listener on the same host.
*/
enum class EndpointSurface {
Standard,
Dashboard,
Api,
Relay,
}
/**
* Picks the highest-priority **reachable** [EndpointCandidate] from a
* per-device list, driven by ADR 24 "Multi-endpoint pairing + network-aware
@@ -98,6 +111,8 @@ class EndpointResolver(
* expected path for plain JVM tests.
*/
private val context: Context? = null,
/** Route-aware client for pinned plugin proxy probes. */
private val clientForCandidate: ((EndpointCandidate) -> OkHttpClient?)? = null,
) {
/**
@@ -124,9 +139,14 @@ class EndpointResolver(
*/
val probeOutcomes: StateFlow<Map<String, RouteProbeOutcome>> = _probeOutcomes.asStateFlow()
private fun recordOutcome(candidate: EndpointCandidate, reachable: Boolean, detail: String?) {
private fun recordOutcome(
candidate: EndpointCandidate,
surface: EndpointSurface,
reachable: Boolean,
detail: String?,
) {
_probeOutcomes.update { outcomes ->
outcomes + (cacheKey(candidate) to RouteProbeOutcome(
outcomes + (cacheKey(candidate, surface) to RouteProbeOutcome(
reachable = reachable,
detail = detail,
atMillis = clock(),
@@ -167,21 +187,49 @@ class EndpointResolver(
private const val PROBE_TIMEOUT_DETAIL = "No answer (timed out)"
/**
* Stable cache key for a candidate: `"<role>|<primary host>:<port>"`.
* Stable cache key for one candidate surface:
* `"<surface>|<role>|<surface host>:<port>"`.
* Roles are preserved case-verbatim (HMAC canonicalization contract)
* but hostnames are lowercased — two roles pointing at the same
* host:port share reachability state.
*/
internal fun cacheKey(candidate: EndpointCandidate): String =
"${candidate.role}|${candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()}"
internal fun cacheKey(
candidate: EndpointCandidate,
surface: EndpointSurface = EndpointSurface.Standard,
): String {
val authority = when (surface) {
EndpointSurface.Standard ->
candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()
EndpointSurface.Dashboard ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url).orEmpty()
EndpointSurface.Api ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url).orEmpty()
EndpointSurface.Relay ->
candidate.pluginProxyRoutesOrNull()?.authority
?: routeAuthority(candidate.relay?.url).orEmpty()
}
return "${surface.name.lowercase()}|${candidate.role}|$authority"
}
private fun routeAuthority(rawUrl: String?): String? {
val candidate = rawUrl?.trim()?.takeIf { it.isNotBlank() } ?: return null
val httpUrl = when {
candidate.startsWith("ws://", ignoreCase = true) ->
"http://${candidate.substringAfter("://")}"
candidate.startsWith("wss://", ignoreCase = true) ->
"https://${candidate.substringAfter("://")}"
else -> candidate
}
return httpUrl.toHttpUrlOrNull()?.let { url -> "${url.host}:${url.port}" }
}
}
/**
* Run the resolver against [candidates].
*
* 1. Group by `priority` ascending.
* 2. For each priority group, race a HEAD /health probe against every
* candidate in the group (2 s per candidate). First 2xx wins; ties
* 2. For each priority group, race the selected surface's health probe
* against every candidate in the group. First 2xx wins; ties
* broken by whichever response lands first.
* 3. If the entire group is unreachable, fall through to the next
* priority group.
@@ -193,37 +241,47 @@ class EndpointResolver(
* its tier). An empty [candidates] list returns null immediately without
* touching the network.
*/
suspend fun resolve(candidates: List<EndpointCandidate>): EndpointCandidate? {
if (candidates.isEmpty()) return null
suspend fun resolve(
candidates: List<EndpointCandidate>,
surface: EndpointSurface = EndpointSurface.Standard,
): EndpointCandidate? {
val eligible = candidates.filter { probeTarget(it, surface) != null }
if (eligible.isEmpty()) return null
// Strict priority: sort ascending so priority-0 lands first. Grouping
// preserves emitted order within a priority class (DNS SRV parity).
val groups = candidates.groupBy { it.priority }.toSortedMap()
// Supported routes always run before experimental routes. Priority is
// strict inside each stability tier, so Reach remains available as a
// last-resort fallback without displacing Tailscale or direct TLS.
val supported = eligible.filterNot { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val experimental = eligible.filter { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val groups = (supported.groupBy { it.priority }.toSortedMap().values +
experimental.groupBy { it.priority }.toSortedMap().values)
for ((priority, group) in groups) {
for (group in groups) {
val priority = group.first().priority
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
val winner = raceGroup(group)
val winner = raceGroup(group, surface)
if (winner != null) {
val winnerUrl = probeTarget(winner, surface)?.baseUrl
Log.i(TAG, "resolve winner: role=${winner.role} " +
"route=${winner.primaryRouteUrl()} priority=$priority")
"surface=$surface route=$winnerUrl priority=$priority")
DiagnosticsLog.record(
category = DiagnosticCategory.Endpoint,
severity = DiagnosticSeverity.Info,
title = context?.getString(R.string.endpoint_diag_selected) ?: "Endpoint selected",
detail = "priority=$priority",
endpointRole = winner.role,
url = winner.primaryRouteUrl(),
url = winnerUrl,
)
return winner
}
}
Log.w(TAG, "resolve: no reachable candidate across ${candidates.size} record(s)")
Log.w(TAG, "resolve: no reachable $surface candidate across ${eligible.size} record(s)")
DiagnosticsLog.record(
category = DiagnosticCategory.Endpoint,
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.endpoint_diag_no_reachable) ?: "No reachable endpoint",
detail = "${candidates.size} configured route(s) failed health probes",
detail = "${eligible.size} configured $surface route(s) failed health probes",
)
return null
}
@@ -237,17 +295,20 @@ class EndpointResolver(
* for "first 2xx wins" so latency matters. The losing probes' results
* still land in the cache, though, so the next call benefits.
*/
private suspend fun raceGroup(group: List<EndpointCandidate>): EndpointCandidate? {
private suspend fun raceGroup(
group: List<EndpointCandidate>,
surface: EndpointSurface,
): EndpointCandidate? {
if (group.isEmpty()) return null
if (group.size == 1) {
val only = group.first()
return if (isReachable(only)) only else null
return if (isReachable(only, surface)) only else null
}
// Fast-path: any cached-reachable candidate wins immediately without
// touching the network.
for (candidate in group) {
val cached = probeCache[cacheKey(candidate)]
val cached = probeCache[cacheKey(candidate, surface)]
if (cached != null && cached.expiresAt > clock() && cached.reachable) {
return candidate
}
@@ -256,7 +317,7 @@ class EndpointResolver(
return coroutineScope {
val deferred = group.map { candidate ->
async(Dispatchers.IO) {
if (isReachable(candidate)) candidate else null
if (isReachable(candidate, surface)) candidate else null
}
}
// Collect results in arrival order: iterate through awaitAll +
@@ -276,8 +337,11 @@ class EndpointResolver(
* [probeCache] first; on miss or expiry, runs a HEAD /health probe and
* records the result.
*/
private suspend fun isReachable(candidate: EndpointCandidate): Boolean {
val key = cacheKey(candidate)
private suspend fun isReachable(
candidate: EndpointCandidate,
surface: EndpointSurface,
): Boolean {
val key = cacheKey(candidate, surface)
val now = clock()
val cached = probeCache[key]
if (cached != null && cached.expiresAt > now) {
@@ -285,7 +349,7 @@ class EndpointResolver(
return cached.reachable
}
val reachable = probe(candidate)
val reachable = probe(candidate, surface)
val ttl = if (reachable) CACHE_TTL_MS else NEGATIVE_CACHE_TTL_MS
probeCache[key] = CacheEntry(expiresAt = now + ttl, reachable = reachable)
return reachable
@@ -299,9 +363,18 @@ class EndpointResolver(
* Returns false on any failure (timeout, I/O, non-2xx, invalid URL).
* We never raise: a bad record shouldn't crash the connect loop.
*/
private suspend fun probe(candidate: EndpointCandidate): Boolean {
private suspend fun probe(
candidate: EndpointCandidate,
surface: EndpointSurface,
): Boolean {
val startedAtMs = clock()
val target = probeTarget(candidate)
val operation = when (surface) {
EndpointSurface.Standard -> "Dashboard or API route health probe"
EndpointSurface.Dashboard -> "Dashboard route health probe"
EndpointSurface.Api -> "API route health probe"
EndpointSurface.Relay -> "Relay route health probe"
}
val target = probeTarget(candidate, surface)
val url = target?.requestUrl?.toHttpUrlOrNull()
?: run {
Log.w(TAG, "probe: invalid url for role=${candidate.role}")
@@ -310,13 +383,15 @@ class EndpointResolver(
severity = DiagnosticSeverity.Error,
title = context?.getString(R.string.endpoint_diag_probe_invalid) ?: "Endpoint probe invalid",
detail = "No valid Dashboard, API, or Relay URL",
operation = operation,
endpointRole = candidate.role,
url = candidate.primaryRouteUrl(),
configuredUrl = candidate.primaryRouteUrl(),
suggestion = "Edit or re-pair this route so it contains a valid service URL.",
)
recordOutcome(candidate, reachable = false, detail = "Invalid route URL")
recordOutcome(candidate, surface, reachable = false, detail = "Invalid route URL")
return false
}
val fastClient = httpClient.newBuilder()
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.readTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
@@ -345,12 +420,20 @@ class EndpointResolver(
severity = if (ok) DiagnosticSeverity.Info else DiagnosticSeverity.Warning,
title = probeTitle,
detail = if (ok) null else "HTTP ${resp.code}",
operation = operation,
endpointRole = candidate.role,
url = target.baseUrl,
configuredUrl = target.baseUrl,
requestUrl = target.requestUrl,
elapsedMs = clock() - startedAtMs,
suggestion = if (ok) {
null
} else {
NetworkDiagnosticGuidance.forHttpStatus(resp.code, surface.diagnosticTarget())
},
)
recordOutcome(
candidate,
surface,
reachable = ok,
detail = if (ok) null else "HTTP ${resp.code} from ${target.path}",
)
@@ -362,11 +445,14 @@ class EndpointResolver(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.endpoint_diag_probe_timeout) ?: "Endpoint probe timeout",
detail = "No ${target.path} response in ${PROBE_TIMEOUT_MS}ms",
operation = operation,
endpointRole = candidate.role,
url = target.baseUrl,
configuredUrl = target.baseUrl,
requestUrl = target.requestUrl,
elapsedMs = clock() - startedAtMs,
suggestion = "Check network routing or firewall rules between this device and ${surface.diagnosticTarget()}.",
)
recordOutcome(candidate, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
recordOutcome(candidate, surface, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
false
}
} catch (_: TimeoutCancellationException) {
@@ -375,11 +461,14 @@ class EndpointResolver(
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.endpoint_diag_probe_timeout) ?: "Endpoint probe timeout",
detail = "No ${target.path} response in ${PROBE_TIMEOUT_MS}ms",
operation = operation,
endpointRole = candidate.role,
url = target.baseUrl,
configuredUrl = target.baseUrl,
requestUrl = target.requestUrl,
elapsedMs = clock() - startedAtMs,
suggestion = "Check network routing or firewall rules between this device and ${surface.diagnosticTarget()}.",
)
recordOutcome(candidate, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
recordOutcome(candidate, surface, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
false
} catch (e: Exception) {
Log.d(TAG, "probe failed role=${candidate.role} " +
@@ -388,19 +477,51 @@ class EndpointResolver(
category = DiagnosticCategory.Endpoint,
severity = DiagnosticSeverity.Warning,
title = context?.getString(R.string.endpoint_diag_probe_failed) ?: "Endpoint probe failed",
detail = e.javaClass.simpleName,
detail = humanProbeFailure(e),
operation = operation,
endpointRole = candidate.role,
url = target.baseUrl,
configuredUrl = target.baseUrl,
requestUrl = target.requestUrl,
elapsedMs = clock() - startedAtMs,
suggestion = NetworkDiagnosticGuidance.forThrowable(e, surface.diagnosticTarget()),
)
recordOutcome(candidate, reachable = false, detail = humanProbeFailure(e))
recordOutcome(candidate, surface, reachable = false, detail = humanProbeFailure(e))
false
}
}
}
/** Choose the standard Dashboard/Gateway surface first when advertised. */
private fun probeTarget(candidate: EndpointCandidate): ProbeTarget? {
private fun probeTarget(
candidate: EndpointCandidate,
surface: EndpointSurface,
): ProbeTarget? {
if (surface == EndpointSurface.Dashboard) {
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { base ->
return ProbeTarget(base, "$base/api/status", "/dashboard/api/status")
}
candidate.dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }?.let { base ->
return ProbeTarget(base, "$base/api/status", "/api/status")
}
return null
}
if (surface == EndpointSurface.Api) {
candidate.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { base ->
return ProbeTarget(base, "$base/health", "/api/health")
}
candidate.api?.url?.let { base -> return ProbeTarget(base, "$base/health", "/health") }
return null
}
if (surface == EndpointSurface.Relay) candidate.pluginProxyRoutesOrNull()?.let { proxy ->
return ProbeTarget(
baseUrl = proxy.relayHttpUrl,
requestUrl = "${proxy.relayHttpUrl}/health",
path = "/relay/health",
)
}
if (surface == EndpointSurface.Relay) {
return relayProbeTarget(candidate)
}
candidate.dashboard?.url
?.trim()
?.trimEnd('/')
@@ -421,6 +542,10 @@ class EndpointResolver(
)
}
return relayProbeTarget(candidate)
}
private fun relayProbeTarget(candidate: EndpointCandidate): ProbeTarget? {
candidate.relay?.url
?.trim()
?.trimEnd('/')
@@ -443,6 +568,11 @@ class EndpointResolver(
return null
}
internal fun probeRequestUrlForTest(
candidate: EndpointCandidate,
surface: EndpointSurface,
): String? = probeTarget(candidate, surface)?.requestUrl
/**
* Map a probe exception to a short, actionable string for the Routes
* card. The TLS case is the headline: a route saved with `https://`
@@ -458,6 +588,13 @@ class EndpointResolver(
else -> e.javaClass.simpleName
}
private fun EndpointSurface.diagnosticTarget(): String = when (this) {
EndpointSurface.Standard -> "Dashboard or API server"
EndpointSurface.Dashboard -> "Dashboard"
EndpointSurface.Api -> "API server"
EndpointSurface.Relay -> "Relay"
}
/**
* Mark [candidate] unreachable without re-probing. Called from
* `ConnectionManager`'s `NetworkCallback.onLost` so the next resolve()
@@ -467,13 +604,21 @@ class EndpointResolver(
* transition can skip the known-dead active route without suppressing a
* valid fallback for the whole positive cache window.
*/
fun markUnreachable(candidate: EndpointCandidate) {
val key = cacheKey(candidate)
fun markUnreachable(
candidate: EndpointCandidate,
surface: EndpointSurface = EndpointSurface.Standard,
) {
val key = cacheKey(candidate, surface)
probeCache[key] = CacheEntry(
expiresAt = clock() + NEGATIVE_CACHE_TTL_MS,
reachable = false,
)
recordOutcome(candidate, reachable = false, detail = "Network changed — assumed offline")
recordOutcome(
candidate,
surface,
reachable = false,
detail = "Network changed — assumed offline",
)
}
/**
@@ -61,7 +61,7 @@ object HermesLanDiscovery {
.callTimeout(PROBE_TIMEOUT_MS * 2, TimeUnit.MILLISECONDS)
.build()
coroutineScope {
val results = coroutineScope {
val semaphore = Semaphore(MAX_CONCURRENT_PROBES)
hosts.map { host ->
async {
@@ -79,6 +79,8 @@ object HermesLanDiscovery {
.thenBy { it.host },
)
}
Log.d(TAG, "scan complete hosts=${hosts.size} matches=${results.size}")
results
}
private fun probeHost(
@@ -133,8 +135,7 @@ object HermesLanDiscovery {
val body = response.body.string().take(2_048)
expectedBody(body, contentType)
}
} catch (e: Exception) {
Log.d(TAG, "probe failed url=$url type=${e.javaClass.simpleName}")
} catch (_: Exception) {
false
}
}

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