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 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 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
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
208 changed files with 16877 additions and 2018 deletions
+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"
+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
+1 -1
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"
+37 -2
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
@@ -175,7 +209,7 @@ jobs:
- 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
@@ -375,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"
+79
View File
@@ -6,19 +6,98 @@ 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
+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) |
+4 -14
View File
@@ -1,27 +1,17 @@
# Hermes-Relay CLI v__VERSION__
**Release Date:** 2026-08-14
**Release Date:** 2026-08-15
This beta makes connection recovery and Activity evidence inspectable in the compact management UI, and keeps the preferred CUA control engine usable when its upstream whole-desktop accessibility probe times out.
This patch keeps the Windows management UI usable when the Relay daemon is stopped or its status cannot be read.
**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
- **Inspectable Activity evidence.** Commands, files, device work, connection lifecycle, and computer control share a consistent event stepper with dedicated failure details.
- **Optional screenshot retention.** Screenshot events can keep bounded local PNG evidence for Off, 1 day, 7 days, or 30 days and open it in a larger borderless viewer. Evidence stays outside the JSON activity log.
### Changed
- **Connection state is live and actionable.** The UI distinguishes connected, reconnecting, and stopped states, shows retry timing, and offers Retry now without freezing the popup.
- **Connection notices stay out of the way.** Compact connect, disconnect, and reconnect cards appear only while the main management UI is hidden.
### Fixed
- **CUA readiness no longer depends on the flaky global accessibility scan.** Hermes verifies the canonical runtime, required tools, daemon, and safe permission mode before structured control; explicit accessibility health remains available for diagnosis and individual actions still fail closed.
- **Connection errors retain useful context.** Activity records bounded retry and recovery evidence without flooding one event per backoff attempt.
- **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
+65
View File
@@ -1,5 +1,70 @@
# 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,
+3
View File
@@ -128,6 +128,7 @@ 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 |
@@ -152,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
+23 -17
View File
@@ -1,10 +1,10 @@
# Hermes-Relay-Android v1.8.1
# Hermes-Relay-Android v1.11.0
**Release Date:** August 9, 2026
**Release Date:** August 20, 2026
## Download
> Installing on your phone? Download `hermes-relay-1.8.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,23 +12,29 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
## Summary
This patch keeps long Hermes conversations complete and aligns Android's
Gateway behavior with current upstream turn contracts.
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
- 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
- Complete transcript reads page explicitly across both API-server and
profile-scoped Dashboard routes, so sessions beyond Hermes' latest-500
default retain stable history, sharing, retry, edit, and recovery anchors.
- Gateway submit rejections preserve the authoritative server message without
silently falling through to SSE.
- Gateway event envelopes reconcile consistently, and edit-and-regenerate
requests send the required truncation confirmation.
- 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.8.1** (versionCode **42**).
- Standard Chat, sessions, Manage, and Vanilla Hermes voice continue to work
against unmodified upstream Hermes.
- The optional Relay plugin is not required for standard Android chat or hosted
Dashboard authentication.
- 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.
+28 -2
View File
@@ -6,6 +6,32 @@ 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
@@ -954,7 +980,7 @@ 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**; **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).
@@ -1271,7 +1297,7 @@ When the answer becomes clearer, this section becomes either an ADR in `docs/dec
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`
+3 -2
View File
@@ -319,6 +319,7 @@ 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)
@@ -371,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.71.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.71.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")
@@ -1 +1,3 @@
Long sessions now retain complete history beyond Hermes' latest-500 default, keeping edit, retry, sharing, and recovery anchors stable. Gateway submit rejections preserve the server's message without unintended SSE fallback, while event envelopes and edit-and-regenerate requests follow current upstream contracts.
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 @@
新增可在界面中漫游的 Petdex 浮动宠物、由已安装 Hermes 插件提供的安全原生页面,以及支持本地“Hey Hermes”的可选 Android 数字助理。本次更新还新增俄语,并改进语音恢复、路线切换、实时聊天稳定性和宠物移动。
v1.11.0 - 更可靠的聊天体验
已存会话恢复失败时会保留错误与重试信息。更多输入法可用回车键换行。取消回复恢复时会保留“已停止”状态。空闲动画更少,并更及时地释放屏幕捕获和音频资源。
+112
View File
@@ -1,5 +1,117 @@
{
"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",
+7 -5
View File
@@ -1,6 +1,8 @@
v1.8.1 - Complete, reliable transcripts
v1.11.0 - Access with clear boundaries
* Keep complete history in long sessions beyond Hermes' latest-500 default.
* Preserve stable edit, retry, sharing, and recovery anchors while paging history.
* Show authoritative Gateway rejection messages without an unintended fallback.
* Reconcile Gateway events and edit-and-regenerate requests with current upstream contracts.
* 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.
@@ -7,6 +7,8 @@ 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
@@ -38,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()
@@ -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
@@ -52,18 +52,12 @@ import kotlin.math.max
*
* 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,
@@ -93,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 {
@@ -108,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
@@ -122,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,
)
}
@@ -239,9 +225,8 @@ class BargeInListener internal constructor(
return@launch
}
Log.i(TAG, "Barge-in AudioRecord reader started")
// Do not block generation-phase listening while waiting for an
// AudioTrack session that does not exist until playback. The
// effects attach races harmlessly beside the reader.
// Effects attach beside the reader so capture can begin even
// on devices that reject or omit the optional preprocessors.
effectsJob = launch { maybeAttachEffects() }
while (isActive) {
@@ -282,7 +267,7 @@ class BargeInListener internal constructor(
val gated = rmsGate.observe(
frame = frameBuffer,
rawSpeech = result.probability > 0f,
nowMs = System.currentTimeMillis(),
nowMs = nowMsProvider(),
playbackGraceMs = playbackGraceMs,
confirmedSpeech = result.isSpeech,
playbackActiveOverride = playbackActiveProvider?.invoke(),
@@ -368,14 +353,12 @@ class BargeInListener internal constructor(
}
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
}
@@ -411,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 }
@@ -445,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
@@ -481,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
@@ -11,8 +11,11 @@ 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
@@ -216,21 +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_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,
secrets.profileApiKeys.takeIf { it.isNotEmpty() }?.let(::encodeProfileApiKeys),
normalized.profileApiKeys
.takeIf { it.isNotEmpty() }
?.let(::encodeProfileApiKeys),
)
writeOrRemove(store, KEY_PAIRED_META, secrets.pairedSessionMetaJson)
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,
@@ -286,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
@@ -305,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,
@@ -318,6 +354,9 @@ class AuthManager(
apiServerHost = apiServerHost,
apiServerPort = apiServerPort,
apiServerKeyPresent = apiServerKeyPresent,
isDefault = isDefault,
hasAvatar = hasAvatar,
uiMeta = uiMeta,
)
}
}
@@ -596,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
@@ -615,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())
}
}
}
@@ -804,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 {
@@ -995,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)
@@ -1007,11 +1095,13 @@ 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? =
@@ -1023,7 +1113,7 @@ class AuthManager(
profileApiKeysMutex.withLock {
val tokenStore = store()
val keys = decodeProfileApiKeys(tokenStore.getString(KEY_PROFILE_API_KEYS)).toMutableMap()
val normalizedKey = key.trim()
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)
@@ -1042,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(
@@ -1059,13 +1152,14 @@ class AuthManager(
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)
@@ -1158,6 +1252,11 @@ 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.",
)
}
}
}
}
@@ -1181,7 +1280,14 @@ class AuthManager(
protocolVersion = current.protocolVersion,
hostId = current.hostId,
credentialKind = "route",
token = credential["token"]?.jsonPrimitive?.contentOrNull ?: return,
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
@@ -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
@@ -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.
@@ -1,9 +1,27 @@
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.
@@ -86,15 +104,15 @@ data class ChatComposerDraft(
*/
interface ChatComposerDraftStore {
fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft>
fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
fun update(
suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
suspend fun update(
key: ChatComposerDraftKey,
transform: (ChatComposerDraft) -> ChatComposerDraft,
)
fun remove(key: ChatComposerDraftKey)
fun removeSession(connectionId: String, profileId: String, sessionId: String)
fun clear()
suspend fun remove(key: ChatComposerDraftKey)
suspend fun removeSession(connectionId: String, profileId: String, sessionId: String)
suspend fun clear()
}
class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
@@ -105,43 +123,370 @@ class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
.map { it[key] ?: ChatComposerDraft() }
.distinctUntilChanged()
override fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
override suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
drafts.value[key] ?: ChatComposerDraft()
@Synchronized
override fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
val normalized = draft.normalized()
drafts.value = if (normalized.isEmpty) {
drafts.value - key
} else {
drafts.value + (key to normalized)
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)
}
}
}
@Synchronized
override fun update(
override suspend fun update(
key: ChatComposerDraftKey,
transform: (ChatComposerDraft) -> ChatComposerDraft,
) {
save(key, transform(snapshot(key)))
}
@Synchronized
override fun remove(key: ChatComposerDraftKey) {
drafts.value = drafts.value - key
}
@Synchronized
override fun removeSession(connectionId: String, profileId: String, sessionId: String) {
drafts.value = drafts.value.filterKeys { key ->
key.connectionId != connectionId ||
key.profileId != profileId ||
key.sessionId != sessionId
override suspend fun remove(key: ChatComposerDraftKey) {
synchronized(drafts) {
drafts.value = drafts.value - key
}
}
@Synchronized
override fun clear() {
drafts.value = emptyMap()
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,
)
@@ -3,6 +3,7 @@ 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
@@ -30,6 +31,8 @@ class ChatInputPreferencesRepository(
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
@@ -40,9 +43,19 @@ class ChatInputPreferencesRepository(
}
.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),
)
}
@@ -147,6 +147,12 @@ data class ChatMessage(
* 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
@@ -156,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?,
@@ -299,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/")
@@ -412,6 +447,11 @@ data class ChatSession(
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,
@@ -436,6 +476,12 @@ data class ChatSession(
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)
@@ -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,
@@ -36,6 +36,8 @@ data class ProactiveInboxEntry(
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
@@ -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.
@@ -56,6 +85,7 @@ import kotlinx.serialization.Serializable
data class Profile(
val name: String,
val model: String,
val provider: String = "",
val description: String = "",
@SerialName("system_message")
val systemMessage: String? = null,
@@ -75,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")
@@ -164,6 +164,8 @@ enum class GatewayProfileSection(val wireName: String) {
Model("model"),
Skills("skills"),
Toolsets("toolsets"),
McpServers("mcp_servers"),
UiMeta("ui_meta"),
}
/** Null leaves a section unchanged; empty lists retain upstream replace semantics. */
@@ -174,6 +176,9 @@ data class GatewayProfilePatch(
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 {
@@ -182,9 +187,67 @@ data class GatewayProfilePatch(
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>,
@@ -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(),
)
/**
@@ -63,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)]),
)
}
@@ -82,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))
}
}
@@ -98,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>
@@ -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
@@ -148,6 +148,8 @@ class ConnectionManager(
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)
@@ -158,6 +160,7 @@ class ConnectionManager(
}
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
@@ -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
@@ -66,6 +68,8 @@ class ProactiveMessageHandler(
* [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" -> {
@@ -99,21 +107,23 @@ class ProactiveMessageHandler(
// session until the phone replies, so this cache is the provisional
// Thread transcript during that gap.
toInbox?.invoke(msg)
// Unified Threads: if this message belongs to the Thread currently open
// in Chat, render it inline there and stop before raising a notification.
if (injectIntoThread?.invoke(msg) == true) return
// The surfacing hint selects the additional surface.
// 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)
}
}
}
@@ -138,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,
)
}
@@ -159,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,
)
@@ -299,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)
}
}
@@ -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)
}
@@ -102,7 +102,11 @@ fun buildPluginProxyClient(
?.takeIf { it.isNotBlank() }
val request = if (token != null) {
chain.request().newBuilder()
.header("X-Hermes-Relay-Session", token)
.credentialHeader(
"X-Hermes-Relay-Session",
token,
"Relay session credential",
)
.build()
} else {
chain.request()
@@ -471,7 +471,12 @@ class ChatHandler {
* across the history reconcile; idempotent on the proactive [messageId] so a
* re-delivered push (e.g. an outbound-buffer flush) never double-posts.
*/
fun addAgentThreadMessage(text: String, messageId: String?, agentName: String?) {
fun addAgentThreadMessage(
text: String,
messageId: String?,
agentName: String?,
arrivedWhileAway: Boolean = false,
) {
val id = messageId?.let { "proactive-$it" } ?: "proactive-${java.util.UUID.randomUUID()}"
_messages.update { list ->
if (messageId != null && list.any { it.id == id }) return@update list
@@ -481,6 +486,7 @@ class ChatHandler {
content = text,
timestamp = System.currentTimeMillis(),
agentName = agentName,
badges = if (arrivedWhileAway) listOf("While away") else emptyList(),
clientOnly = true,
)
(list + msg).let { if (it.size > MAX_MESSAGES) it.drop(it.size - MAX_MESSAGES) else it }
@@ -524,6 +530,19 @@ class ChatHandler {
}
}
/**
* Whether [messageId] can be addressed without downgrading a durable
* transcript to an ordinal-only rewind. A wholly legacy transcript has no
* row ids and remains compatible with older Gateways. Once any visible
* user turn has a durable row id, the selected turn must have one too;
* otherwise the caller must refresh instead of guessing by position.
*/
fun hasSafeGatewayRewindAddress(messageId: String): Boolean {
val userTurns = _messages.value.filter { it.isGatewayRewindUser() }
val target = userTurns.firstOrNull { it.matchesIdentity(messageId) } ?: return false
return target.rowId != null || userTurns.none { it.rowId != null }
}
/**
* Rebind visible user turns after Gateway rewrites a truncated durable
* prefix. The response is positional in the same user-ordinal space used
@@ -1520,7 +1539,8 @@ class ChatHandler {
// this as the same visible row across the post-turn reload.
prior.copy(
id = messageId,
rowId = item.rowId,
rowId = item.resolvedRowId,
reactions = item.reactions,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -1551,7 +1571,8 @@ class ChatHandler {
// nothing local to carry).
ChatMessage(
id = messageId,
rowId = item.rowId,
rowId = item.resolvedRowId,
reactions = item.reactions,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -1624,7 +1645,7 @@ class ChatHandler {
is MediaMarkerHit.RelayToken -> {
val dedupeKey = "$messageId:relay:${hit.token}"
if (dispatchedMediaMarkers.add(dedupeKey)) {
Log.d(TAG, "Media marker (relay, reload): token=${hit.token}")
Log.d(TAG, "Media marker accepted from reloaded Relay history")
onMediaAttachmentRequested(messageId, hit.token)
}
}
@@ -2050,6 +2071,11 @@ class ChatHandler {
title = resolvedTitle,
model = item.model,
messageCount = item.messageCount ?: 0,
inputTokens = item.inputTokens ?: 0,
outputTokens = item.outputTokens ?: 0,
actualCostUsd = item.actualCostUsd,
estimatedCostUsd = item.estimatedCostUsd,
isActive = item.isActive,
updatedAt = activityAtMs,
startedAt = startedAtMs,
lastActivityAt = lastActivityAtMs,
@@ -2485,7 +2511,7 @@ class ChatHandler {
is MediaMarkerHit.RelayToken -> {
val dedupeKey = "$messageId:relay:${hit.token}"
if (dispatchedMediaMarkers.add(dedupeKey)) {
Log.d(TAG, "Media marker (relay): token=${hit.token}")
Log.d(TAG, "Media marker accepted from Relay stream")
onMediaAttachmentRequested(messageId, hit.token)
}
}
@@ -3319,6 +3345,7 @@ class ChatHandler {
.filterNot { msg ->
msg.matchesIdentity(messageId) &&
msg.role == MessageRole.ASSISTANT &&
msg.badges.isEmpty() &&
msg.toolCalls.isEmpty() &&
msg.backgroundTask == null &&
msg.thinkingContent.isBlank() &&
@@ -0,0 +1,50 @@
package com.hermesandroid.relay.network.upstream
/**
* User-reviewed input for upstream `cron.manage` creation.
*
* Repeat is intentionally bounded on the client. Upstream treats zero and
* negative values as an unlimited schedule, which is unsafe when the user
* explicitly chose a finite run count.
*/
data class CronCreationDraft(
val name: String,
val schedule: String,
val prompt: String,
val repeat: Int? = null,
val profile: String? = null,
) {
fun validated(): Result<CronCreationDraft> = runCatching {
val cleanName = name.trim()
val cleanSchedule = schedule.trim()
val cleanPrompt = prompt.trim()
require(cleanName.isNotEmpty()) { "Schedule name is required" }
require(cleanSchedule.isNotEmpty()) { "Schedule is required" }
require(cleanPrompt.isNotEmpty()) { "Task instructions are required" }
require(repeat == null || repeat in MIN_REPEAT..MAX_REPEAT) {
"Run count must be between $MIN_REPEAT and $MAX_REPEAT"
}
copy(
name = cleanName,
schedule = cleanSchedule,
prompt = cleanPrompt,
profile = profile?.trim()?.takeIf(String::isNotEmpty),
)
}
companion object {
const val MIN_REPEAT = 1
const val MAX_REPEAT = 999
}
}
/** Parse an optional finite-count field without ever coercing invalid input to unlimited. */
internal fun parseFiniteRepeat(value: String): Result<Int?> = runCatching {
val clean = value.trim()
if (clean.isEmpty()) return@runCatching null
val parsed = clean.toIntOrNull() ?: throw IllegalArgumentException("Run count must be a whole number")
require(parsed in CronCreationDraft.MIN_REPEAT..CronCreationDraft.MAX_REPEAT) {
"Run count must be between ${CronCreationDraft.MIN_REPEAT} and ${CronCreationDraft.MAX_REPEAT}"
}
parsed
}
@@ -66,6 +66,29 @@ data class DashboardStatus(
@SerialName("gateway_mode") val gatewayMode: String? = null,
val gateways: List<DashboardGatewayTopology> = emptyList(),
val componentHealth: DashboardComponentHealthRollup = DashboardComponentHealthRollup(),
val memory: DashboardMemoryStatus? = null,
val disk: DashboardDiskStatus? = null,
)
@Serializable
data class DashboardMemoryStatus(
val pressure: String,
@SerialName("gateway_rss_mb") val gatewayRssMb: Int? = null,
@SerialName("system_total_mb") val systemTotalMb: Int? = null,
@SerialName("system_available_mb") val systemAvailableMb: Int? = null,
@SerialName("swap_used_mb") val swapUsedMb: Int? = null,
@SerialName("sampled_at") val sampledAt: String? = null,
@SerialName("last_boot_unclean") val lastBootUnclean: Boolean = false,
@SerialName("last_boot_suspected_oom") val lastBootSuspectedOom: Boolean = false,
@SerialName("boot_id") val bootId: String? = null,
)
@Serializable
data class DashboardDiskStatus(
val pressure: String,
@SerialName("total_mb") val totalMb: Int? = null,
@SerialName("free_mb") val freeMb: Int? = null,
@SerialName("used_percent") val usedPercent: Double? = null,
)
@Serializable
@@ -1711,6 +1734,35 @@ class DashboardApiClient(
gatewayMode = root.stringField("gateway_mode"),
gateways = gateways,
componentHealth = parseComponentHealth(root),
memory = parseMemoryStatus(root["memory"] as? JsonObject),
disk = parseDiskStatus(root["disk"] as? JsonObject),
)
}
private fun parseMemoryStatus(obj: JsonObject?): DashboardMemoryStatus? {
obj ?: return null
val pressure = obj.stringField("pressure")?.lowercase() ?: return null
return DashboardMemoryStatus(
pressure = pressure,
gatewayRssMb = obj.intField("gateway_rss_mb"),
systemTotalMb = obj.intField("system_total_mb"),
systemAvailableMb = obj.intField("system_available_mb"),
swapUsedMb = obj.intField("swap_used_mb"),
sampledAt = obj.stringField("sampled_at"),
lastBootUnclean = obj.booleanField("last_boot_unclean") ?: false,
lastBootSuspectedOom = obj.booleanField("last_boot_suspected_oom") ?: false,
bootId = obj.stringField("boot_id"),
)
}
private fun parseDiskStatus(obj: JsonObject?): DashboardDiskStatus? {
obj ?: return null
val pressure = obj.stringField("pressure")?.lowercase() ?: return null
return DashboardDiskStatus(
pressure = pressure,
totalMb = obj.intField("total_mb"),
freeMb = obj.intField("free_mb"),
usedPercent = (obj["used_percent"] as? JsonPrimitive)?.contentOrNull?.toDoubleOrNull(),
)
}
File diff suppressed because it is too large Load Diff
@@ -260,6 +260,13 @@ class GatewayEventMapper(
}
callbacks.onUsage(parseGatewayUsage(payload?.get("usage") as? JsonObject))
if (failed) {
callbacks.onFailure(
GatewayTurnFailure(
error = error?.takeIf { it.isNotBlank() }
?: text.orEmpty().ifBlank { "Turn failed" },
recoverable = payload.boolean("recoverable") == true,
),
)
callbacks.onStatusUpdate(
ERROR_STATUS_KIND,
error?.takeIf { it.isNotBlank() } ?: text.orEmpty().ifBlank { "Turn failed" },
@@ -550,6 +550,12 @@ data class GatewaySessionModel(
val fast: Boolean? = null,
)
/** Structured terminal failure carried by Gateway `message.complete`. */
data class GatewayTurnFailure(
val error: String,
val recoverable: Boolean,
)
/** Result of the gateway `config.get {key:"reasoning"}` RPC. */
data class GatewayReasoningSettings(
val effort: String,
@@ -618,6 +624,10 @@ class GatewayTurnCallbacks(
val onInteractionRequest: (GatewayAsk) -> Unit,
/** Server declared a pending interaction expired; clear only the matching card. */
val onInteractionExpired: (GatewayAskExpiry) -> Unit,
/** Existing durable session could not be rebound; no prompt was submitted. */
val onResumeFailure: (String) -> Unit = { _ -> },
/** Terminal `message.complete {status:"error"}` without prose inspection. */
val onFailure: (GatewayTurnFailure) -> Unit = { _ -> },
/**
* Gateway `status.update` lifecycle line — model fallback, retries, and
* errors (often emoji-prefixed: 🔄 fallback, ⏳ retry, ❌ error). Default
@@ -6,6 +6,9 @@ import android.util.Log
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.AppAnalytics
import com.hermesandroid.relay.network.shutdownOffMainThread
import com.hermesandroid.relay.network.shared.InvalidCredentialException
import com.hermesandroid.relay.network.shared.bearerAuthorization
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
import com.hermesandroid.relay.network.upstream.models.CreateSessionRequest
import com.hermesandroid.relay.network.upstream.models.HermesSseEvent
import com.hermesandroid.relay.network.upstream.models.MessageItem
@@ -431,16 +434,20 @@ private class RetryingEventSource(
*/
class HermesApiClient(
baseUrl: String,
private val apiKey: String,
apiKey: String,
httpClient: OkHttpClient? = null,
private val json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
}
},
okHttpClient: OkHttpClient? = null,
) {
@Volatile
private var lastCapabilities: ServerCapabilities? = null
private val baseUrl: String = baseUrl.trimEnd('/')
private val apiCredential = runCatching {
normalizeCredentialForHeader(apiKey, "API credential")
}
companion object {
private const val TAG = "HermesApiClient"
@@ -480,7 +487,7 @@ class HermesApiClient(
private val mainHandler = Handler(Looper.getMainLooper())
private val client: OkHttpClient = httpClient ?: OkHttpClient.Builder()
private val client: OkHttpClient = httpClient ?: okHttpClient ?: OkHttpClient.Builder()
.readTimeout(5, TimeUnit.MINUTES)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
@@ -539,6 +546,8 @@ class HermesApiClient(
HealthCheckResult.Unhealthy("Server not found — check the hostname")
} catch (e: java.net.SocketTimeoutException) {
HealthCheckResult.Unhealthy("Connection timed out — is the server running?")
} catch (e: InvalidCredentialException) {
HealthCheckResult.Unhealthy(e.message ?: "Invalid API credential")
} catch (e: IOException) {
val msg = e.message ?: ""
when {
@@ -2022,9 +2031,8 @@ class HermesApiClient(
private fun authRequest(url: String): Request.Builder {
val builder = Request.Builder().url(url)
if (apiKey.isNotBlank()) {
builder.header("Authorization", "Bearer $apiKey")
}
val credential = apiCredential.getOrElse { throw it }
builder.bearerAuthorization(credential, "API credential")
return builder
}
@@ -2041,10 +2049,12 @@ class HermesApiClient(
*/
private fun authRequestOrNull(url: String): Request.Builder? {
val builder = buildApiRequestOrNull(url) ?: return null
if (apiKey.isNotBlank()) {
builder.header("Authorization", "Bearer $apiKey")
}
return builder
return runCatching {
builder.bearerAuthorization(
apiCredential.getOrElse { throw it },
"API credential",
)
}.getOrNull()
}
/**
@@ -2062,7 +2072,8 @@ class HermesApiClient(
/** Human message for a base URL that fails to parse (#131). */
private fun invalidBaseUrlMessage(): String =
"Invalid server address ($baseUrl) — edit the connection's API URL or re-pair."
apiCredential.exceptionOrNull()?.message
?: "Invalid server address ($baseUrl) — edit the connection's API URL or re-pair."
/**
* Make attachment drops on the SSE fallback transports explicit
@@ -4,6 +4,8 @@ import android.content.Context
import com.hermesandroid.relay.auth.SessionTokenStore
import com.hermesandroid.relay.auth.SecureStoreCache
import com.hermesandroid.relay.auth.buildRawTokenStore
import com.hermesandroid.relay.network.shared.bearerAuthorization
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
import java.io.EOFException
import java.io.IOException
import java.io.InterruptedIOException
@@ -75,11 +77,13 @@ class EncryptedNativeDashboardTokenStore(
override fun load(): NativeDashboardTokens? =
store.getString(TOKEN_KEY)?.let { raw ->
runCatching { json.decodeFromString<NativeDashboardTokens>(raw) }.getOrNull()
runCatching {
json.decodeFromString<NativeDashboardTokens>(raw).normalizedForStorage()
}.getOrNull()
}
override fun save(tokens: NativeDashboardTokens) {
store.putString(TOKEN_KEY, json.encodeToString(tokens))
store.putString(TOKEN_KEY, json.encodeToString(tokens.normalizedForStorage()))
}
override fun clear() {
@@ -140,7 +144,16 @@ class NativeDashboardAuthClient(
.addQueryParameter("code_challenge_method", "S256")
.addQueryParameter("redirect_uri", redirectUri)
.addQueryParameter("state", state)
.apply { provider?.takeIf(String::isNotBlank)?.let { addQueryParameter("provider", it) } }
// Match the official Desktop client for Nous-hosted gateways: the
// gateway selects its single native-eligible provider. The provider
// name advertised to UI clients is presentation/configuration data,
// not a stable native-broker identifier. Other providers retain the
// explicit selector for direct client use and tests.
.apply {
provider
?.takeIf { it.isNotBlank() && !it.equals("nous", ignoreCase = true) }
?.let { addQueryParameter("provider", it) }
}
.build()
.toString()
val generation = NativeTokenRefreshCoordinator.beginAuthorization(
@@ -441,7 +454,7 @@ class DashboardBearerAuth(
val tokens = usableTokens(forceRefresh = false, failedAccessToken = null)
val request = tokens?.let {
chain.request().newBuilder()
.header("Authorization", "Bearer ${it.accessToken}")
.bearerAuthorization(it.accessToken, "Dashboard credential")
.build()
} ?: chain.request()
return chain.proceed(request)
@@ -455,9 +468,12 @@ class DashboardBearerAuth(
forceRefresh = true,
failedAccessToken = failedAccessToken,
) ?: return null
val next = "Bearer ${tokens.accessToken}"
val accessToken = normalizeCredentialForHeader(tokens.accessToken, "Dashboard credential")
val next = "Bearer $accessToken"
if (next == previous) return null
return response.request.newBuilder().header("Authorization", next).build()
return response.request.newBuilder()
.bearerAuthorization(accessToken, "Dashboard credential")
.build()
}
private fun usableTokens(
@@ -487,6 +503,14 @@ class DashboardBearerAuth(
}
}
private fun NativeDashboardTokens.normalizedForStorage(): NativeDashboardTokens = copy(
accessToken = normalizeCredentialForHeader(accessToken, "Dashboard credential")
.also { require(it.isNotEmpty()) { "Dashboard credential is empty" } },
refreshToken = if (refreshToken.isEmpty()) "" else {
normalizeCredentialForHeader(refreshToken, "Dashboard refresh credential")
},
)
internal class NativeDashboardAuthHttpException(
val statusCode: Int,
) : IOException("Dashboard native authentication failed (HTTP $statusCode)")
@@ -22,7 +22,7 @@ private const val CALLBACK_PATH = "/callback"
private const val MAX_REQUEST_LINE_BYTES = 8 * 1024
private const val MAX_HEADER_BYTES = 16 * 1024
private const val ACCEPT_POLL_MILLIS = 500
internal const val DEFAULT_NATIVE_SIGN_IN_TIMEOUT_MILLIS = 2 * 60 * 1000L
internal const val DEFAULT_NATIVE_SIGN_IN_TIMEOUT_MILLIS = 5 * 60 * 1000L
internal val NATIVE_SIGN_IN_RETURN_URI = "${BuildConfig.APPLICATION_ID}://return"
private enum class CallbackPage(
@@ -46,6 +46,48 @@ private enum class CallbackPage(
message = "No session details were saved from this attempt.",
guidance = "Return to Hermes Relay and start sign-in again.",
),
AuthorizationRejected(
modifier = "failure",
eyebrow = "Provider sign-in",
title = "Sign-in was not completed",
message = "The provider returned without an approved authorization for Hermes.",
guidance = "Return to Hermes Relay and start again if you still want to sign in.",
),
CodeRejected(
modifier = "failure",
eyebrow = "Hosted Hermes callback",
title = "Hermes rejected the sign-in code",
message = "Google sign-in finished, but hosted Hermes could not exchange its one-time callback code for a session.",
guidance = "Return to Hermes Relay and start a fresh sign-in attempt.",
),
GatewayUnavailable(
modifier = "failure",
eyebrow = "Hosted Hermes callback",
title = "Hosted Hermes could not finish sign-in",
message = "The callback reached Hermes Relay, but the hosted Hermes sign-in service was unavailable.",
guidance = "Return to Hermes Relay, wait a moment, and try again.",
),
TransportFailure(
modifier = "failure",
eyebrow = "Secure sign-in connection",
title = "Could not reach hosted Hermes",
message = "Google sign-in finished, but the secure connection back to hosted Hermes was interrupted.",
guidance = "Return to Hermes Relay and retry on a stable connection.",
),
ResponseUnsupported(
modifier = "failure",
eyebrow = "Hosted Hermes callback",
title = "Hermes returned an unsupported session",
message = "The hosted gateway answered, but its sign-in response was not compatible with this app.",
guidance = "Return to Hermes Relay and check for app and hosted Hermes updates.",
),
SessionStorageFailure(
modifier = "failure",
eyebrow = "Secure session storage",
title = "The session could not be saved",
message = "Google sign-in finished, but Android could not securely save the Hermes session on this device.",
guidance = "Return to Hermes Relay and try again. If it repeats, check the app's diagnostics.",
),
Rejected(
modifier = "rejected",
eyebrow = "Protected callback",
@@ -194,14 +236,14 @@ class NativeDashboardSignInCoordinator(
writeResponse(
socket,
status = "400 Bad Request",
page = CallbackPage.Failure,
page = CallbackPage.AuthorizationRejected,
)
throw error
} catch (error: Exception) {
writeResponse(
socket,
status = "400 Bad Request",
page = CallbackPage.Failure,
page = callbackFailurePage(error),
)
throw error
}
@@ -296,6 +338,20 @@ class NativeDashboardSignInCoordinator(
}
}
private fun callbackFailurePage(error: Throwable): CallbackPage {
val stage = nativeDashboardSignInFailureStage(error)
return when {
stage == "token_http_400" -> CallbackPage.CodeRejected
stage == "callback_error" -> CallbackPage.AuthorizationRejected
stage == "token_http_429" || stage.startsWith("token_http_5") ->
CallbackPage.GatewayUnavailable
stage == "token_shape" -> CallbackPage.ResponseUnsupported
stage == "token_store" -> CallbackPage.SessionStorageFailure
stage.startsWith("token_transport") -> CallbackPage.TransportFailure
else -> CallbackPage.Failure
}
}
private fun callbackPageHtml(page: CallbackPage): String = """
<!doctype html>
<html lang="en">
@@ -1,19 +1,24 @@
package com.hermesandroid.relay.network.upstream.models
import com.hermesandroid.relay.data.MessageReaction
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
@@ -97,6 +102,36 @@ object FlexibleLongSerializer : KSerializer<Long?> {
}
}
/**
* Dashboard versions may expose SQLite JSON columns either as an object or as
* their raw JSON string. Normalize both shapes so persisted presentation data
* (notably message reactions) survives a history reload on every supported
* upstream version.
*/
object FlexibleJsonObjectSerializer : KSerializer<JsonObject?> {
override val descriptor = JsonObject.serializer().descriptor
override fun deserialize(decoder: Decoder): JsonObject? {
return try {
val jsonDecoder = decoder as? JsonDecoder ?: return null
when (val element = jsonDecoder.decodeJsonElement()) {
is JsonObject -> element
is JsonPrimitive -> element.content.takeIf { it.isNotBlank() }
?.let { Json.parseToJsonElement(it) as? JsonObject }
else -> null
}
} catch (_: Exception) {
null
}
}
override fun serialize(encoder: Encoder, value: JsonObject?) {
val jsonEncoder = encoder as? JsonEncoder
?: throw SerializationException("FlexibleJsonObjectSerializer requires JSON")
jsonEncoder.encodeJsonElement(value ?: JsonNull)
}
}
/** Timestamp serializer for Hermes session metadata.
*
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
@@ -134,6 +169,32 @@ object FlexibleTimestampSerializer : KSerializer<Double?> {
}
}
/**
* Boolean serializer for session flags backed by SQLite integer columns.
*
* Older Dashboard responses can expose those columns as `0` / `1` instead of
* JSON booleans. Accept the equivalent primitive forms without making arbitrary
* numbers or strings truthy, and always serialize back to a real JSON boolean.
*/
object FlexibleBooleanSerializer : KSerializer<Boolean> {
override val descriptor = PrimitiveSerialDescriptor("FlexibleBoolean", PrimitiveKind.BOOLEAN)
override fun deserialize(decoder: Decoder): Boolean {
val jsonDecoder = decoder as? JsonDecoder ?: return decoder.decodeBoolean()
val element = jsonDecoder.decodeJsonElement()
val value = (element as? JsonPrimitive)?.content?.trim()?.lowercase()
return when (value) {
"true", "1" -> true
"false", "0" -> false
else -> throw SerializationException("Expected a boolean-compatible value, got $element")
}
}
override fun serialize(encoder: Encoder, value: Boolean) {
encoder.encodeBoolean(value)
}
}
// --- Session CRUD responses ---
@Serializable
@@ -187,9 +248,16 @@ data class SessionItem(
@SerialName("tool_call_count") val toolCallCount: Int? = null,
@SerialName("input_tokens") val inputTokens: Int? = null,
@SerialName("output_tokens") val outputTokens: Int? = null,
@SerialName("has_model_config") val hasModelConfig: Boolean = false,
@SerialName("actual_cost_usd") val actualCostUsd: Double? = null,
@SerialName("estimated_cost_usd") val estimatedCostUsd: Double? = null,
@SerialName("is_active") val isActive: Boolean = false,
@SerialName("has_model_config")
@Serializable(with = FlexibleBooleanSerializer::class)
val hasModelConfig: Boolean = false,
/** Durable flags returned by current Dashboard and API-server session resources. */
@Serializable(with = FlexibleBooleanSerializer::class)
val pinned: Boolean = false,
@Serializable(with = FlexibleBooleanSerializer::class)
val archived: Boolean = false,
/** Optional workspace metadata added by newer Dashboard session lists. */
val cwd: String? = null,
@@ -327,7 +395,9 @@ data class MessageItem(
val timestamp: Double? = null,
@SerialName("finish_reason") val finishReason: String? = null,
@SerialName("display_kind") val displayKind: String? = null,
@SerialName("display_metadata") val displayMetadata: JsonObject? = null,
@SerialName("display_metadata")
@Serializable(with = FlexibleJsonObjectSerializer::class)
val displayMetadata: JsonObject? = null,
// Reasoning persisted with the assistant message (upstream serializes
// both names; reasoning is the canonical one). Restored into
// ChatMessage.thinkingContent so the Thought-process block survives a
@@ -335,11 +405,24 @@ data class MessageItem(
val reasoning: String? = null,
@SerialName("reasoning_content") val reasoningContent: String? = null,
) {
/**
* Dashboard history uses the SQLite row id as numeric `id`; Gateway
* history exposes the same value explicitly as `row_id`. Match Desktop by
* accepting either representation so persisted rows remain directly
* reactable after reload.
*/
val resolvedRowId: Long?
get() = rowId ?: id?.toLongOrNull()
/** Reasoning text under whichever field name the server used. */
val resolvedReasoning: String?
get() = reasoning?.takeIf { it.isNotBlank() }
?: reasoningContent?.takeIf { it.isNotBlank() }
/** Persisted tapbacks stored by Hermes in display_metadata.reactions. */
val reactions: List<MessageReaction>
get() = parseMessageReactions(displayMetadata?.get("reactions"))
/** Extract content as plain text string. Handles both string and array-of-parts formats. */
val contentText: String?
get() = when (content) {
@@ -367,6 +450,21 @@ data class MessageItem(
}
}
fun parseMessageReactions(element: JsonElement?): List<MessageReaction> =
(element as? JsonArray).orEmpty().mapNotNull { raw ->
val reaction = raw as? JsonObject ?: return@mapNotNull null
val emoji = (reaction["emoji"] as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() }
?: return@mapNotNull null
val author = (reaction["author"] as? JsonPrimitive)?.content
?.takeIf { it == "user" || it == "agent" }
?: return@mapNotNull null
MessageReaction(
emoji = emoji,
author = author,
at = (reaction["at"] as? JsonPrimitive)?.doubleOrNull ?: 0.0,
)
}
// --- SSE streaming events from /api/sessions/{id}/chat/stream ---
//
// Hermes WebAPI event types (from server source):
@@ -90,6 +90,29 @@ object ReliabilityCenter {
writer.execute { runCatching { target.append(report) } }
}
/** Persist a bounded, content-free checkpoint before a user-requested chat reset. */
fun recordSessionCheckpoint(context: Context, evidence: SessionResetEvidence) {
initialize(context)
val report = ReliabilityReport(
reportId = ReliabilityReport.newId("checkpoint"),
appSessionId = appSessionId,
timeIso = Instant.now().toString(),
kind = ReliabilityKind.SessionCheckpoint,
owner = ReliabilityOwner.Android,
severity = ReliabilitySeverity.Info,
summary = "Chat context reset",
recovery = "The prior context remains on Hermes when it had a stored session.",
reportRecommended = false,
technicalDetail = evidence.technicalDetail(),
routeRole = evidence.transport,
environment = environment(),
)
// A pre-reset checkpoint is useful only if it lands before state is
// replaced. The store is tiny and atomically rewritten, so persist it
// synchronously instead of queueing behind later failures.
runCatching { store?.append(report) }
}
fun reports(context: Context): List<ReliabilityReport> {
initialize(context)
return store?.readAll().orEmpty()
@@ -15,6 +15,7 @@ const val RELIABILITY_SCHEMA_VERSION = 1
enum class ReliabilityKind {
FatalCrash,
AnrSignal,
SessionCheckpoint,
RecoverableProductError,
Connectivity,
Authentication,
@@ -0,0 +1,33 @@
package com.hermesandroid.relay.reliability
/**
* Content-free evidence captured immediately before Android replaces a chat
* context. Deliberately excludes prompts, message text, IDs, profile names,
* URLs, paths, attachments, and tool arguments/results.
*/
data class SessionResetEvidence(
val reason: String,
val transport: String,
val messageCount: Int,
val toolCount: Int,
val queuedCount: Int,
val pendingAttachmentCount: Int,
val hadStoredSession: Boolean,
val turnActive: Boolean,
val askPending: Boolean,
) {
fun technicalDetail(): String = buildString {
appendLine("reason=${reason.safeToken()}")
appendLine("transport=${transport.safeToken()}")
appendLine("messages=${messageCount.coerceAtLeast(0)}")
appendLine("tools=${toolCount.coerceAtLeast(0)}")
appendLine("queued=${queuedCount.coerceAtLeast(0)}")
appendLine("pending_attachments=${pendingAttachmentCount.coerceAtLeast(0)}")
appendLine("had_stored_session=$hadStoredSession")
appendLine("turn_active=$turnActive")
append("ask_pending=$askPending")
}
private fun String.safeToken(): String =
lowercase().replace(Regex("[^a-z0-9_.-]"), "_").take(40).ifBlank { "unknown" }
}
@@ -5,6 +5,8 @@ import androidx.lifecycle.ViewModelStore
import com.hermesandroid.relay.HermesRelayApp
import com.hermesandroid.relay.data.VoicePreferencesRepository
import com.hermesandroid.relay.data.VoiceSettings
import com.hermesandroid.relay.data.PersistentChatComposerDraftStore
import java.io.File
import com.hermesandroid.relay.network.relay.RelayVoiceClient
import com.hermesandroid.relay.viewmodel.ChatViewModel
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
@@ -70,7 +72,13 @@ class HermesProcessRuntime internal constructor(
}
val chatViewModel: ChatViewModel by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
viewModelProvider[ChatViewModel::class.java]
viewModelProvider[ChatViewModel::class.java].also { chat ->
chat.installComposerDraftStore(
PersistentChatComposerDraftStore(
File(application.noBackupFilesDir, "chat-composer-drafts"),
),
)
}
}
val voiceViewModel: VoiceViewModel by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
@@ -142,8 +142,8 @@ internal class HermesRuntimeBinder(
voiceHandoffReporter = connection::recordVoiceHandoff,
bargeInPreferences = BargeInPreferencesRepository(application),
vadEngineFactory = { VadEngine(application) },
bargeInListenerFactory = { vad, audioSessionIdProvider ->
BargeInListener.create(application, vad, audioSessionIdProvider)
bargeInListenerFactory = { vad ->
BargeInListener.create(application, vad)
},
)
@@ -176,7 +176,9 @@ internal class HermesRuntimeBinder(
chat.setDisplayProfileProvider { connection.effectiveDisplayProfile.value }
chat.setDisplayAliasProvider { connection.profileDisplayAlias.value }
chat.setProfileSessionLister { connection.listProfileScopedSessions() }
chat.setProfileMessageLoaderWithMode(connection::loadProfileScopedMessages)
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
connection.loadProfileScopedMessages(profileName, sessionId, mode)
}
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
chat.profileSessionDeleter = connection::deleteProfileScopedSession
chat.profileSessionRenamer = connection::renameProfileScopedSession
@@ -96,6 +96,7 @@ import com.hermesandroid.relay.ui.components.avatar.LocalFloatingPet
import com.hermesandroid.relay.ui.components.avatar.LocalPetPlaybackSpeed
import com.hermesandroid.relay.ui.components.avatar.LocalPetStabilize
import com.hermesandroid.relay.ui.components.avatar.PetLoader
import com.hermesandroid.relay.ui.components.avatar.toAvatar
import com.hermesandroid.relay.ui.components.avatar.SphereAvatar
import com.hermesandroid.relay.ui.components.avatar.resolveBackgroundAvatar
import com.hermesandroid.relay.ui.components.FloatingPetCompanion
@@ -116,6 +117,7 @@ import com.hermesandroid.relay.ui.components.PowerFeatureGateStatus
import com.hermesandroid.relay.ui.components.RelayStatusStrip
import com.hermesandroid.relay.ui.components.UnattendedGlobalBanner
import com.hermesandroid.relay.ui.components.UpdateAvailableBanner
import com.hermesandroid.relay.ui.components.HostResourcePressureBanner
import com.hermesandroid.relay.ui.components.rememberUpdateAvailability
import com.hermesandroid.relay.ui.components.resolveChatTransportStatus
import com.hermesandroid.relay.ui.components.WhatsNewDialog
@@ -741,8 +743,12 @@ fun RelayApp() {
) {
value = withContext(Dispatchers.IO) { PetLoader.loadPets(sphereContext) }
}
val activeFloatingPet = remember(floatingPetId, availablePets) {
availablePets.firstOrNull { it.id == floatingPetId }
val hermesPetState by connectionViewModel.hermesPetState.collectAsState()
val upstreamProfilePet = remember(hermesPetState.active) {
hermesPetState.active?.toAvatar()
}
val activeFloatingPet = remember(floatingPetId, availablePets, upstreamProfilePet) {
availablePets.firstOrNull { it.id == floatingPetId } ?: upstreamProfilePet
}
var floatingPetMenuExpanded by remember(activeFloatingPet?.id) { mutableStateOf(false) }
val activeBackgroundAvatar = remember(backgroundAvatarId, availablePets) {
@@ -887,6 +893,7 @@ fun RelayApp() {
// ChatViewModel isn't available where ConnectionViewModel builds the
// handler, so the session sink is set here at the app root where both
// ViewModels are in scope.
val proactiveSummaryResources = LocalContext.current.resources
LaunchedEffect(connectionViewModel, chatViewModel) {
connectionViewModel.proactiveMessageHandler.toSession = { msg ->
val text = buildString {
@@ -895,6 +902,15 @@ fun RelayApp() {
}
chatViewModel.injectProactiveMessage(text)
}
connectionViewModel.proactiveMessageHandler.onBacklogDelivered = { count ->
UiMessageBus.info(
proactiveSummaryResources.getQuantityString(
R.plurals.proactive_messages_arrived_while_away,
count,
count,
),
)
}
// Agent Thread reply path: a send from the chat composer while a
// source=phone Thread is open routes over the relay proactive
// channel (continues the gateway phone session) instead of a normal
@@ -906,7 +922,8 @@ fun RelayApp() {
chatViewModel.onProactiveReplyAck(clientMsgId, status)
}
// Unified Threads: render an inbound agent message inline in the open
// Thread (suppressing the notification/inbox) when it belongs there.
// Thread when it belongs there. Surfacing semantics still decide
// independently whether a system notification is also required.
connectionViewModel.proactiveMessageHandler.injectIntoThread = { msg ->
chatViewModel.injectThreadMessage(msg)
}
@@ -1370,12 +1387,22 @@ fun RelayApp() {
}
val masterEnabled by masterEnabledFlow.collectAsState(initial = false)
val unattendedEnabled by unattendedEnabledFlow.collectAsState(initial = false)
val activeBridgePolicy by (connectionViewModel.bridgeSafety?.activeCapabilityPolicy
?: remember { kotlinx.coroutines.flow.MutableStateFlow(
com.hermesandroid.relay.bridge.BridgeCapabilityPolicy(),
) })
.collectAsState()
val timedScreenControlActive = activeBridgePolicy.allows(
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL,
System.currentTimeMillis(),
)
// Sideload-only: googlePlay has no wake lock and the unattended
// flag never gets written there — gating here is defence in depth
// and makes the check cheap via R8 in release builds.
val showUnattendedBanner = BuildFlavor.isSideload &&
masterEnabled &&
unattendedEnabled &&
timedScreenControlActive &&
!suppressGlobalChrome &&
!showStartupSphere &&
!voiceUiState.voiceMode
@@ -1383,6 +1410,22 @@ fun RelayApp() {
// user always knows the chat is sample data with no live server, and
// can exit into the real Connect flow with one tap.
val showDemoBanner = isDemoMode && !voiceUiState.voiceMode
val hostResourcePressure by connectionViewModel.hostResourcePressure.collectAsState()
val showHostResourcePressure = hostResourcePressure.needsAttention &&
!isDemoMode && !voiceUiState.voiceMode && !showStartupSphere
val hostResourcePressureText = buildList {
if (hostResourcePressure.lastBootSuspectedOom) {
add(stringResource(R.string.host_resource_recent_oom))
}
when (hostResourcePressure.memoryPressure) {
"critical" -> add(stringResource(R.string.host_resource_memory_critical))
"elevated" -> add(stringResource(R.string.host_resource_memory_elevated))
}
when (hostResourcePressure.diskPressure) {
"critical" -> add(stringResource(R.string.host_resource_disk_critical))
"elevated" -> add(stringResource(R.string.host_resource_disk_elevated))
}
}.distinct().joinToString(" ")
// Transient info/status banner (UiMessageBus) — thin, takes its own
// space, auto-dismisses. Folded into the inset accounting below so a
// child TopAppBar doesn't double-pad when this banner owns the top edge.
@@ -1489,6 +1532,18 @@ fun RelayApp() {
DemoModeBanner(onConnect = exitDemoToConnect)
}
AnimatedVisibility(
visible = showHostResourcePressure,
enter = fadeIn(tween(200)),
exit = fadeOut(tween(200)),
) {
HostResourcePressureBanner(
text = hostResourcePressureText,
critical = hostResourcePressure.critical,
includeStatusBarPadding = !showUnattendedBanner && !showDemoBanner,
)
}
// Connection status intentionally has NO top-of-screen surface (no
// banner, no strip, no float). Chat/agent status rides the chat header
// subtitle; the relay socket rides the bottom RelayStatusStrip cue. See
@@ -1499,7 +1554,7 @@ fun RelayApp() {
// that banner already padded the top — avoid double padding).
MessageBannerHost(
includeStatusBarPadding =
!showUnattendedBanner && !showDemoBanner,
!showUnattendedBanner && !showDemoBanner && !showHostResourcePressure,
)
// The update banner AND the connection-status indicator now render as
@@ -1539,7 +1594,7 @@ fun RelayApp() {
// The connection-status toast is now a floating overlay and
// doesn't occupy space above the Scaffold, so it no longer
// participates in the top-inset accounting.
if (showUnattendedBanner || showDemoBanner || connectionChipVisible ||
if (showUnattendedBanner || showDemoBanner || showHostResourcePressure || connectionChipVisible ||
showMessageBanner
) {
Modifier.consumeWindowInsets(WindowInsets.statusBars)
@@ -1583,7 +1638,7 @@ fun RelayApp() {
?: AgentDisplay.displayModelName(serverModelName)
?: stringResource(R.string.status_model_pending)
val safetyLabel = if (BuildFlavor.isSideload && masterEnabled) {
if (unattendedEnabled) stringResource(R.string.status_safety_unattended)
if (unattendedEnabled && timedScreenControlActive) stringResource(R.string.status_safety_unattended)
else stringResource(R.string.status_safety_on)
} else {
stringResource(R.string.status_profile_format, profileLabel)
@@ -2271,6 +2326,7 @@ fun RelayApp() {
composable(Screen.BridgeSafetySettings.route) {
if (BuildFlavor.isSideload) {
BridgeSafetySettingsScreen(
connectionId = activeConnectionId,
onBack = { navController.popBackStack() }
)
} else {
@@ -821,12 +821,21 @@ private fun ManualUrlSubsection(
val apiServerUrl by connectionViewModel.apiServerUrl.collectAsState()
val relayUrl by connectionViewModel.relayUrl.collectAsState()
val apiKeyPresent by connectionViewModel.authManager.apiKeyPresent.collectAsState()
val savedApiKeyError by connectionViewModel.authManager.apiKeyError.collectAsState()
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
// Keyed on the backing URL so a connection switch refreshes the input.
var apiUrlInput by remember(apiServerUrl) { mutableStateOf(apiServerUrl) }
var apiKeyInput by remember { mutableStateOf("") }
var apiKeyVisible by remember { mutableStateOf(false) }
val apiKeySingleLineError = stringResource(R.string.api_credential_single_line_error)
val inputApiKeyError = remember(apiKeyInput, apiKeySingleLineError) {
if (apiKeyInput.trim(' ', '\t').any { it < '!' || it > '~' }) {
apiKeySingleLineError
} else {
null
}
}
var relayUrlInput by remember(relayUrl) { mutableStateOf(relayUrl) }
var isTestingApi by remember { mutableStateOf(false) }
var apiVoiceSetupResult by remember {
@@ -900,13 +909,14 @@ private fun ManualUrlSubsection(
},
supportingText = {
Text(
if (apiKeyPresent && apiKeyInput.isBlank()) {
inputApiKeyError ?: savedApiKeyError ?: if (apiKeyPresent && apiKeyInput.isBlank()) {
apiKeyStoredHint
} else {
apiKeyNeededHint
},
)
},
isError = inputApiKeyError != null || (apiKeyInput.isBlank() && savedApiKeyError != null),
singleLine = true,
visualTransformation = if (apiKeyVisible) {
VisualTransformation.None
@@ -962,7 +972,7 @@ private fun ManualUrlSubsection(
).show()
}
},
enabled = apiUrlInput.isNotBlank() && !isTestingApi,
enabled = apiUrlInput.isNotBlank() && !isTestingApi && inputApiKeyError == null,
) {
Text(saveAndTestText)
}
@@ -3,105 +3,422 @@ package com.hermesandroid.relay.ui.components
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
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.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import androidx.compose.ui.res.stringResource
import com.hermesandroid.relay.R
import com.hermesandroid.relay.ui.components.SphereState
import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
import com.hermesandroid.relay.ui.components.avatar.PetAvatar
import com.hermesandroid.relay.ui.components.avatar.toAvatar
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import java.io.File
/**
* Per-profile agent-icon picker — the visual twin of the local-name (alias) row.
* The chosen image is copied into app storage and shown beside the agent's name
* in chat. Client-side only: never sent to Hermes. Keyed per `(connection,
* profile)` by [ConnectionViewModel.setProfileIcon] / `ProfileIconStore`.
*/
/** Shared Hermes identity and a separately-scoped phone presentation override. */
@Composable
fun AgentIconRow(connectionViewModel: ConnectionViewModel) {
val iconPath by connectionViewModel.profileIcon.collectAsState()
val localIconPath by connectionViewModel.localProfileIcon.collectAsState()
val serverAvatarPath by connectionViewModel.serverProfileAvatar.collectAsState()
val useLocalOverride by connectionViewModel.useLocalProfileIconOverride.collectAsState()
val hostImportState by connectionViewModel.hostProfileIconImportState.collectAsState()
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument()
) { uri: Uri? -> uri?.let { connectionViewModel.setProfileIcon(it) } }
val sharedState by connectionViewModel.sharedProfileAvatarState.collectAsState()
val hermesPetState by connectionViewModel.hermesPetState.collectAsState()
val hermesPetAvatar = remember(hermesPetState.active) { hermesPetState.active?.toAvatar() }
var confirmSharedRemoval by remember { mutableStateOf(false) }
var showHermesPetPicker by remember { mutableStateOf(false) }
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
LaunchedEffect(Unit) { connectionViewModel.refreshHermesPet() }
val sharedLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument(),
) { uri: Uri? -> uri?.let(connectionViewModel::setSharedProfileAvatar) }
val localLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument(),
) { uri: Uri? -> uri?.let(connectionViewModel::setProfileIcon) }
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
text = stringResource(R.string.agent_icon_title),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.size(44.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center,
AvatarSourceCard {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
val path = iconPath
if (!path.isNullOrBlank()) {
AsyncImage(
model = File(path),
contentDescription = stringResource(R.string.agent_icon_title),
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
HermesPetPreview(hermesPetAvatar)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.agent_icon_hermes_pet_title),
style = MaterialTheme.typography.titleSmall,
)
Text(
text = when {
hermesPetState.supported == false -> stringResource(R.string.agent_icon_hermes_pet_unsupported)
hermesPetState.active != null -> stringResource(
R.string.agent_icon_hermes_pet_active,
hermesPetState.active?.displayName.orEmpty(),
)
else -> stringResource(R.string.agent_icon_hermes_pet_empty)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (hermesPetState.loading) {
CircularProgressIndicator(modifier = Modifier.size(24.dp), strokeWidth = 2.dp)
} else if (hermesPetState.supported != false) {
Switch(
checked = hermesPetState.active != null,
onCheckedChange = { enabled ->
if (enabled) {
showHermesPetPicker = true
connectionViewModel.loadHermesPetGallery()
} else {
connectionViewModel.disableHermesPet()
}
},
)
}
}
OutlinedButton(onClick = { launcher.launch(arrayOf("image/*")) }) {
Text(if (iconPath.isNullOrBlank()) stringResource(R.string.agent_icon_set) else stringResource(R.string.agent_icon_change))
}
if (!iconPath.isNullOrBlank()) {
TextButton(onClick = { connectionViewModel.clearProfileIcon() }) {
Text(stringResource(R.string.agent_icon_clear))
if (hermesPetState.supported != false) {
OutlinedButton(
onClick = {
showHermesPetPicker = true
connectionViewModel.loadHermesPetGallery()
},
enabled = !hermesPetState.loading,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.agent_icon_hermes_pet_browse))
}
}
}
OutlinedButton(
onClick = { connectionViewModel.importProfileIconFromHost() },
enabled = !hostImportState.loading,
) {
Text(
if (hostImportState.loading) {
stringResource(R.string.agent_icon_importing_host)
} else {
stringResource(R.string.agent_icon_import_host)
}
)
}
hostImportState.error?.let { error ->
Text(
text = error,
text = stringResource(R.string.agent_icon_hermes_pet_description),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
text = stringResource(R.string.agent_icon_description),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
AvatarSourceCard {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
AvatarPreview(serverAvatarPath)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.agent_icon_shared_title),
style = MaterialTheme.typography.titleSmall,
)
Text(
text = if (serverAvatarPath.isNullOrBlank()) {
stringResource(R.string.agent_icon_shared_empty)
} else {
stringResource(R.string.agent_icon_shared_active)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
onClick = {
sharedLauncher.launch(arrayOf("image/*"))
},
enabled = !sharedState.loading,
) {
Text(stringResource(R.string.agent_icon_change_shared))
}
if (!serverAvatarPath.isNullOrBlank()) {
TextButton(
onClick = { confirmSharedRemoval = true },
enabled = !sharedState.loading,
) {
Text(
text = stringResource(R.string.agent_icon_remove_shared),
color = MaterialTheme.colorScheme.error,
)
}
}
}
sharedState.error?.let { AvatarError(it) }
}
AvatarSourceCard {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
AvatarPreview(localIconPath)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.agent_icon_phone_title),
style = MaterialTheme.typography.titleSmall,
)
Text(
text = stringResource(R.string.agent_icon_phone_description),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = useLocalOverride,
onCheckedChange = connectionViewModel::setUseLocalProfileIconOverride,
)
}
OutlinedButton(
onClick = { localLauncher.launch(arrayOf("image/*")) },
modifier = Modifier.fillMaxWidth(),
enabled = useLocalOverride,
) {
Text(
if (localIconPath.isNullOrBlank()) {
stringResource(R.string.agent_icon_choose_phone)
} else {
stringResource(R.string.agent_icon_change_phone)
},
)
}
OutlinedButton(
onClick = connectionViewModel::importProfileIconFromHost,
modifier = Modifier.fillMaxWidth(),
enabled = useLocalOverride && !hostImportState.loading,
) {
Text(
if (hostImportState.loading) {
stringResource(R.string.agent_icon_importing_host)
} else {
stringResource(R.string.agent_icon_import_host)
},
)
}
if (!localIconPath.isNullOrBlank()) {
TextButton(
onClick = connectionViewModel::clearProfileIcon,
enabled = useLocalOverride,
) {
Text(stringResource(R.string.agent_icon_remove_phone))
}
}
Text(
text = stringResource(R.string.agent_icon_animation_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
hostImportState.error?.let { AvatarError(it) }
hermesPetState.error?.let { AvatarError(it) }
}
if (confirmSharedRemoval) {
AlertDialog(
onDismissRequest = { confirmSharedRemoval = false },
title = { Text(stringResource(R.string.agent_icon_remove_shared_title)) },
text = { Text(stringResource(R.string.agent_icon_remove_shared_message)) },
confirmButton = {
TextButton(
onClick = {
confirmSharedRemoval = false
connectionViewModel.clearSharedProfileAvatar()
},
) {
Text(
text = stringResource(R.string.agent_icon_remove_shared),
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(onClick = { confirmSharedRemoval = false }) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
if (showHermesPetPicker) {
AlertDialog(
onDismissRequest = { showHermesPetPicker = false },
title = { Text(stringResource(R.string.agent_icon_hermes_pet_picker_title)) },
text = {
if (hermesPetState.galleryLoading && hermesPetState.gallery.isEmpty()) {
Box(
modifier = Modifier.fillMaxWidth().padding(24.dp),
contentAlignment = Alignment.Center,
) { CircularProgressIndicator() }
} else {
LazyColumn(modifier = Modifier.fillMaxWidth().heightIn(max = 420.dp)) {
if (hermesPetState.gallery.isEmpty()) {
item {
Text(
text = stringResource(R.string.agent_icon_hermes_pet_empty),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(12.dp),
)
}
}
items(hermesPetState.gallery, key = { it.slug }) { pet ->
LaunchedEffect(pet.slug, pet.spritesheetUrl) {
connectionViewModel.loadHermesPetThumbnail(pet)
}
TextButton(
onClick = {
showHermesPetPicker = false
connectionViewModel.selectHermesPet(pet.slug)
},
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
PetGalleryPreview(hermesPetState.thumbnails[pet.slug])
Column(modifier = Modifier.weight(1f)) {
Text(pet.displayName, style = MaterialTheme.typography.titleSmall)
Text(
text = when {
pet.slug == hermesPetState.active?.slug -> stringResource(R.string.agent_icon_hermes_pet_selected)
pet.installed -> stringResource(R.string.agent_icon_hermes_pet_installed)
else -> stringResource(R.string.agent_icon_hermes_pet_adopt)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
}
},
confirmButton = {},
dismissButton = {
TextButton(onClick = { showHermesPetPicker = false }) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
}
@Composable
private fun AvatarSourceCard(content: @Composable ColumnScope.() -> Unit) {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceContainerLow,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.6f)),
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
content = content,
)
}
}
@Composable
private fun AvatarPreview(path: String?) {
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center,
) {
if (!path.isNullOrBlank()) {
AsyncImage(
model = File(path),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
}
}
}
@Composable
private fun HermesPetPreview(pet: PetAvatar?) {
Box(
modifier = Modifier.size(56.dp),
contentAlignment = Alignment.Center,
) {
pet?.Render(
state = AvatarRenderState(state = SphereState.Idle),
modifier = Modifier.fillMaxSize(),
)
}
}
@Composable
private fun PetGalleryPreview(dataUri: String?) {
Box(
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(12.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center,
) {
if (dataUri != null) {
AsyncImage(
model = dataUri,
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier.fillMaxSize().padding(3.dp),
)
}
}
}
@Composable
private fun AvatarError(message: String) {
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
@@ -0,0 +1,632 @@
package com.hermesandroid.relay.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Security
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.RadioButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.hermesandroid.relay.R
import com.hermesandroid.relay.bridge.BridgeCapability
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
@Composable
fun BridgeAgentAccessCard(
policy: BridgeCapabilityPolicy,
nowMs: Long,
onSetUp: () -> Unit,
onManage: () -> Unit,
onAllowScreen: () -> Unit,
modifier: Modifier = Modifier,
) {
val hasGrant = policy.hasAnyGrant(nowMs)
val preset = policy.displayPreset()
val timed = policy.activeTimedCapabilities(nowMs)
val screenUnlimited = timed.any(policy::isUnlimited)
val nextExpiry = policy.timedExpiriesMs.filterValues {
it > nowMs && it != BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
}.values.maxOrNull()
val screenActive = timed.isNotEmpty()
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Filled.Security,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
Text(
text = stringResource(R.string.bridge_access_title),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 8.dp).weight(1f),
)
AccessStatePill(
text = when (preset) {
BridgeAccessPreset.READ_ONLY -> stringResource(R.string.bridge_access_preset_read_only)
BridgeAccessPreset.READ_CONFIRMED -> stringResource(R.string.bridge_access_preset_confirmed_short)
BridgeAccessPreset.CUSTOM -> stringResource(R.string.bridge_access_preset_custom)
null -> stringResource(R.string.bridge_access_not_set_up)
},
)
}
Text(
text = stringResource(R.string.bridge_access_summary_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (!hasGrant) {
Button(onClick = onSetUp, modifier = Modifier.fillMaxWidth()) {
Text(stringResource(R.string.bridge_access_set_up))
}
} else {
AccessSummaryRow(
title = stringResource(R.string.bridge_access_always),
subtitle = stringResource(
R.string.bridge_access_enabled_count,
policy.permanentGrants.size,
BridgeCapability.entries.count { !it.timed },
),
trailing = policy.permanentGrants.size.toString(),
onClick = onManage,
)
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.15f))
AccessSummaryRow(
title = stringResource(R.string.bridge_access_screen),
subtitle = if (screenActive) {
if (screenUnlimited) {
stringResource(R.string.bridge_access_screen_unlimited)
} else {
stringResource(R.string.bridge_access_screen_active)
}
} else {
stringResource(R.string.bridge_access_screen_off)
},
trailing = if (screenUnlimited) {
stringResource(R.string.bridge_access_until_off_short)
} else {
nextExpiry?.let { formatRemaining(it - nowMs) }
?: stringResource(R.string.bridge_access_allow_duration)
},
onClick = onAllowScreen,
)
}
}
}
}
@Composable
fun BridgeAndroidAccessSummaryCard(
summary: BridgeAndroidAccessSummary,
expanded: Boolean,
onToggle: () -> Unit,
modifier: Modifier = Modifier,
) {
Card(
modifier = modifier.fillMaxWidth().clickable(onClick = onToggle),
shape = RoundedCornerShape(14.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Icon(
imageVector = if (summary.allReady) Icons.Filled.CheckCircle else Icons.Filled.Security,
contentDescription = null,
tint = if (summary.allReady) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.bridge_android_access_title),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
Text(
text = when {
summary.required.isEmpty() -> stringResource(R.string.bridge_android_access_none)
summary.allReady -> stringResource(R.string.bridge_android_access_ready)
else -> stringResource(
R.string.bridge_android_access_missing,
summary.ready.size,
summary.required.size,
summary.missing.size,
)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
text = if (expanded) {
stringResource(R.string.bridge_android_access_hide)
} else {
stringResource(R.string.bridge_android_access_review)
},
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
)
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
}
}
}
@Composable
fun BridgeSelectedAndroidAccessCard(
summary: BridgeAndroidAccessSummary,
onOpenAccessibility: () -> Unit,
onOpenAppSettings: () -> Unit,
onOpenOverlay: () -> Unit,
modifier: Modifier = Modifier,
) {
if (summary.missing.isEmpty()) return
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
stringResource(R.string.bridge_android_selected_needs),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
Text(
stringResource(R.string.bridge_android_selected_needs_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
summary.missing.forEach { requirement ->
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(requirement.labelResource()),
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.bodyMedium,
)
TextButton(
onClick = when (requirement) {
BridgeAndroidRequirement.ACCESSIBILITY -> onOpenAccessibility
BridgeAndroidRequirement.OVERLAY -> onOpenOverlay
else -> onOpenAppSettings
},
) {
Text(stringResource(R.string.bridge_android_open_settings))
}
}
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BridgeAccessSetupSheet(
selected: BridgeAccessPreset,
onSelected: (BridgeAccessPreset) -> Unit,
onDismiss: () -> Unit,
onContinue: () -> Unit,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(
modifier = Modifier
.fillMaxWidth()
.height(600.dp)
.navigationBarsPadding()
.padding(horizontal = 20.dp, vertical = 8.dp),
) {
Column(
modifier = Modifier.weight(1f).verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
stringResource(R.string.bridge_access_choose_title),
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
)
Text(
stringResource(R.string.bridge_access_choose_desc),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
PresetChoice(
title = stringResource(R.string.bridge_access_preset_read_only),
description = stringResource(R.string.bridge_access_preset_read_only_desc),
selected = selected == BridgeAccessPreset.READ_ONLY,
recommended = true,
onClick = { onSelected(BridgeAccessPreset.READ_ONLY) },
)
PresetChoice(
title = stringResource(R.string.bridge_access_preset_confirmed),
description = stringResource(R.string.bridge_access_preset_confirmed_desc),
selected = selected == BridgeAccessPreset.READ_CONFIRMED,
onClick = { onSelected(BridgeAccessPreset.READ_CONFIRMED) },
)
PresetChoice(
title = stringResource(R.string.bridge_access_preset_custom),
description = stringResource(R.string.bridge_access_preset_custom_desc),
selected = selected == BridgeAccessPreset.CUSTOM,
onClick = { onSelected(BridgeAccessPreset.CUSTOM) },
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.bridge_cancel)) }
Button(onClick = onContinue) { Text(stringResource(R.string.bridge_access_continue)) }
}
Spacer(Modifier.size(4.dp))
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BridgeTimedAccessSheet(
inspectEnabled: Boolean,
controlEnabled: Boolean,
durationMinutes: Int,
unlimited: Boolean,
accessibilityReady: Boolean,
overlayReady: Boolean,
currentlyActive: Boolean,
onInspectChanged: (Boolean) -> Unit,
onControlChanged: (Boolean) -> Unit,
onDurationChanged: (Int) -> Unit,
onUnlimitedChanged: (Boolean) -> Unit,
onOpenAccessibility: () -> Unit,
onOpenOverlay: () -> Unit,
onDismiss: () -> Unit,
onAllow: () -> Unit,
onEndNow: () -> Unit,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.height(740.dp)
.navigationBarsPadding()
.padding(horizontal = 20.dp, vertical = 8.dp),
) {
Column(
modifier = Modifier.weight(1f).verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
stringResource(R.string.bridge_timed_title),
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
)
Text(
stringResource(R.string.bridge_timed_desc),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
stringResource(R.string.bridge_timed_lifetime_title),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
listOf(5, 30, 120).forEach { minutes ->
FilterChip(
selected = !unlimited && durationMinutes == minutes,
onClick = {
onUnlimitedChanged(false)
onDurationChanged(minutes)
},
label = { Text(formatIdleDuration(minutes)) },
)
}
}
FilterChip(
selected = unlimited,
onClick = { onUnlimitedChanged(true) },
label = { Text(stringResource(R.string.bridge_timed_until_off)) },
)
Text(
text = if (unlimited) {
stringResource(R.string.bridge_timed_unlimited_warning)
} else {
stringResource(R.string.bridge_timed_idle_explainer, formatDuration(durationMinutes))
},
style = MaterialTheme.typography.bodySmall,
color = if (unlimited) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
Text(
stringResource(R.string.bridge_timed_scope_title),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
TimedChoice(
title = stringResource(R.string.bss_capability_screen_inspection),
description = stringResource(R.string.bridge_timed_inspection_desc),
checked = inspectEnabled,
onCheckedChange = onInspectChanged,
)
TimedChoice(
title = stringResource(R.string.bss_capability_screen_control),
description = stringResource(R.string.bridge_timed_control_desc),
checked = controlEnabled,
onCheckedChange = onControlChanged,
)
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
stringResource(R.string.bridge_timed_prerequisites),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
PrerequisiteRow(
stringResource(R.string.bpc_accessibility),
accessibilityReady,
onOpenAccessibility,
)
if (controlEnabled) {
PrerequisiteRow(
stringResource(R.string.bpc_overlay),
overlayReady,
onOpenOverlay,
)
}
Text(
stringResource(R.string.bridge_timed_capture_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
if (currentlyActive) {
TextButton(onClick = onEndNow) {
Text(stringResource(R.string.bridge_timed_end_now))
}
} else {
Spacer(Modifier.size(1.dp))
}
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.bridge_cancel)) }
Button(
onClick = onAllow,
enabled = (inspectEnabled || controlEnabled) &&
accessibilityReady && (!controlEnabled || overlayReady),
) {
Text(stringResource(R.string.bridge_timed_allow))
}
}
}
Spacer(Modifier.size(4.dp))
}
Spacer(Modifier.size(12.dp))
}
}
}
@Composable
private fun AccessSummaryRow(
title: String,
subtitle: String,
trailing: String,
onClick: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.bodyLarge)
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(trailing, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null)
}
}
@Composable
private fun PresetChoice(
title: String,
description: String,
selected: Boolean,
recommended: Boolean = false,
onClick: () -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.semantics { role = Role.RadioButton }
.clickable(onClick = onClick),
colors = CardDefaults.cardColors(
containerColor = if (selected) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.35f)
} else {
MaterialTheme.colorScheme.surfaceVariant
},
),
) {
Row(
modifier = Modifier.padding(14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
RadioButton(selected = selected, onClick = null)
Column(modifier = Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
Text(
description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (recommended) {
Text(
stringResource(R.string.bridge_access_recommended),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
}
}
@Composable
private fun TimedChoice(
title: String,
description: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)) {
Row(
modifier = Modifier.fillMaxWidth().padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = checked, onCheckedChange = onCheckedChange)
Column(modifier = Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleSmall)
Text(
description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@Composable
private fun PrerequisiteRow(label: String, ready: Boolean, onClick: () -> Unit) {
Row(
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.CheckCircle,
contentDescription = null,
tint = if (ready) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
modifier = Modifier.size(18.dp),
)
Text(label, modifier = Modifier.padding(start = 8.dp).weight(1f))
Text(
if (ready) stringResource(R.string.bridge_android_ready_short)
else stringResource(R.string.bridge_android_missing_short),
style = MaterialTheme.typography.labelLarge,
color = if (ready) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
)
Icon(
Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = stringResource(R.string.bridge_android_open_settings),
modifier = Modifier.padding(start = 4.dp),
)
}
}
@Composable
private fun AccessStatePill(text: String) {
Surface(
shape = RoundedCornerShape(50),
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
) {
Text(
text,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
)
}
}
private fun formatRemaining(remainingMs: Long): String {
val totalSeconds = (remainingMs.coerceAtLeast(0L) / 1_000L).toInt()
return "%d:%02d".format(totalSeconds / 60, totalSeconds % 60)
}
private fun formatDuration(minutes: Int): String =
if (minutes == 120) "2 hr" else "$minutes min"
private fun formatIdleDuration(minutes: Int): String =
if (minutes == 120) "2 hr idle" else "$minutes min idle"
private fun BridgeAndroidRequirement.labelResource(): Int = when (this) {
BridgeAndroidRequirement.ACCESSIBILITY -> R.string.bpc_accessibility
BridgeAndroidRequirement.CONTACTS -> R.string.bpc_contacts
BridgeAndroidRequirement.LOCATION -> R.string.bpc_location
BridgeAndroidRequirement.SMS -> R.string.bpc_sms
BridgeAndroidRequirement.PHONE -> R.string.bpc_phone
BridgeAndroidRequirement.OVERLAY -> R.string.bpc_overlay
}
@@ -0,0 +1,97 @@
package com.hermesandroid.relay.ui.components
import com.hermesandroid.relay.bridge.BridgeCapability
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
import com.hermesandroid.relay.viewmodel.BridgePermissionStatus
enum class BridgeAccessPreset {
READ_ONLY,
READ_CONFIRMED,
CUSTOM,
}
val READ_ONLY_BRIDGE_CAPABILITIES: Set<BridgeCapability> = setOf(
BridgeCapability.DEVICE_INFO,
BridgeCapability.CONTACTS_READ,
BridgeCapability.LOCATION_READ,
BridgeCapability.CLIPBOARD_READ,
)
val READ_CONFIRMED_BRIDGE_CAPABILITIES: Set<BridgeCapability> =
READ_ONLY_BRIDGE_CAPABILITIES + setOf(
BridgeCapability.COMMUNICATIONS,
BridgeCapability.OUTBOUND_SHARING,
)
enum class BridgeAndroidRequirement {
ACCESSIBILITY,
CONTACTS,
LOCATION,
SMS,
PHONE,
OVERLAY,
}
data class BridgeAndroidAccessSummary(
val required: Set<BridgeAndroidRequirement>,
val ready: Set<BridgeAndroidRequirement>,
) {
val missing: Set<BridgeAndroidRequirement> get() = required - ready
val allReady: Boolean get() = missing.isEmpty()
}
fun BridgeCapabilityPolicy.hasAnyGrant(nowMs: Long): Boolean =
permanentGrants.isNotEmpty() || timedExpiriesMs.any { (capability, expiry) ->
capability.timed && expiry > nowMs
}
fun BridgeCapabilityPolicy.activeTimedCapabilities(nowMs: Long): Set<BridgeCapability> =
timedExpiriesMs.filterValues { it > nowMs }.keys
fun BridgeCapabilityPolicy.displayPreset(): BridgeAccessPreset? = when (permanentGrants) {
READ_ONLY_BRIDGE_CAPABILITIES -> BridgeAccessPreset.READ_ONLY
READ_CONFIRMED_BRIDGE_CAPABILITIES -> BridgeAccessPreset.READ_CONFIRMED
else -> if (permanentGrants.isEmpty()) null else BridgeAccessPreset.CUSTOM
}
fun bridgeAndroidAccessSummary(
policy: BridgeCapabilityPolicy,
status: BridgePermissionStatus,
nowMs: Long,
): BridgeAndroidAccessSummary {
val timed = policy.activeTimedCapabilities(nowMs)
val required = buildSet {
// Current BridgeCommandHandler is service-owned even for passive
// commands. Keep this visible until non-screen executors are split.
if (policy.permanentGrants.isNotEmpty() || timed.isNotEmpty()) {
add(BridgeAndroidRequirement.ACCESSIBILITY)
}
if (BridgeCapability.CONTACTS_READ in policy.permanentGrants) {
add(BridgeAndroidRequirement.CONTACTS)
}
if (BridgeCapability.LOCATION_READ in policy.permanentGrants) {
add(BridgeAndroidRequirement.LOCATION)
}
if (BridgeCapability.COMMUNICATIONS in policy.permanentGrants) {
add(BridgeAndroidRequirement.SMS)
add(BridgeAndroidRequirement.PHONE)
}
if (BridgeCapability.SCREEN_CONTROL in timed ||
BridgeCapability.COMMUNICATIONS in policy.permanentGrants ||
BridgeCapability.OUTBOUND_SHARING in policy.permanentGrants
) {
add(BridgeAndroidRequirement.OVERLAY)
}
}
val ready = required.filterTo(linkedSetOf()) { requirement ->
when (requirement) {
BridgeAndroidRequirement.ACCESSIBILITY -> status.accessibilityServiceEnabled
BridgeAndroidRequirement.CONTACTS -> status.contactsPermitted
BridgeAndroidRequirement.LOCATION -> status.locationPermitted
BridgeAndroidRequirement.SMS -> status.smsPermitted
BridgeAndroidRequirement.PHONE -> status.phonePermitted
BridgeAndroidRequirement.OVERLAY -> status.overlayPermitted
}
}
return BridgeAndroidAccessSummary(required = required, ready = ready)
}
@@ -40,8 +40,8 @@ import com.hermesandroid.relay.data.DEFAULT_DESTRUCTIVE_VERBS
*
* - Blocklist count ("12 apps blocked")
* - Destructive-verb count ("12 verbs need confirmation")
* - Auto-disable window ("Auto-off after 30 min idle")
* - Auto-disable countdown when a timer is active
* - Timed screen-access window
* - Timed screen-access countdown when active
*
* Tap → navigate to [BridgeSafetySettingsScreen].
*
@@ -53,6 +53,8 @@ import com.hermesandroid.relay.data.DEFAULT_DESTRUCTIVE_VERBS
fun BridgeSafetySummaryCard(
settings: BridgeSafetySettings,
autoDisableAtMs: Long? = null,
screenAccessActive: Boolean = false,
screenAccessUnlimited: Boolean = false,
onManage: () -> Unit,
) {
// Tick a local clock every second when a countdown is active so the
@@ -114,14 +116,18 @@ fun BridgeSafetySummaryCard(
value = "${settings.destructiveVerbs.size}",
)
SafetySummaryRow(
label = stringResource(R.string.bssc_auto_disable),
value = if (autoDisableAtMs != null) {
label = stringResource(R.string.bridge_access_screen),
value = if (screenAccessUnlimited) {
stringResource(R.string.bridge_access_until_off_short)
} else if (!screenAccessActive) {
stringResource(R.string.bmt_off)
} else if (autoDisableAtMs != null) {
val remainMs = (autoDisableAtMs - nowMs).coerceAtLeast(0L)
val remainMin = (remainMs / 60_000L).toInt()
val remainSec = ((remainMs % 60_000L) / 1000L).toInt()
"in ${remainMin}:${remainSec.toString().padStart(2, '0')}"
} else {
"${settings.autoDisableMinutes} min"
stringResource(R.string.bridge_access_screen_active)
},
)
@@ -183,6 +189,7 @@ private fun BridgeSafetySummaryCardPreview_Countdown() {
destructiveVerbs = DEFAULT_DESTRUCTIVE_VERBS,
),
autoDisableAtMs = System.currentTimeMillis() + 12 * 60_000L + 34_000L,
screenAccessActive = true,
onManage = {},
)
}
@@ -0,0 +1,147 @@
package com.hermesandroid.relay.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.hermesandroid.relay.R
import com.hermesandroid.relay.viewmodel.ChatFailureNotice
@Composable
fun ChatFailurePanel(
failure: ChatFailureNotice,
routeLabel: String,
onDetails: () -> Unit,
onRetry: () -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier,
) {
Surface(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp),
color = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
shape = MaterialTheme.shapes.medium,
) {
Column(modifier = Modifier.padding(start = 12.dp, top = 12.dp, end = 8.dp, bottom = 4.dp)) {
Row(verticalAlignment = Alignment.Top) {
Icon(
imageVector = Icons.Default.Warning,
contentDescription = null,
modifier = Modifier.padding(top = 2.dp),
)
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.chat_failure_title),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
failureIdentity(routeLabel, failure.model, failure.provider)
.takeIf { it.isNotBlank() }
?.let { identity ->
Text(
text = identity,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.78f),
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onDetails) {
Text(stringResource(R.string.chat_failure_details))
}
if (failure.recoverable) {
TextButton(onClick = onRetry) {
Text(stringResource(R.string.chat_retry))
}
}
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.chat_dismiss))
}
}
}
}
}
@Composable
fun ChatFailureDetailsDialog(
failure: ChatFailureNotice,
routeLabel: String,
onCopy: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.chat_failure_details_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
failureIdentity(routeLabel, failure.model, failure.provider)
.takeIf { it.isNotBlank() }
?.let { identity ->
Text(text = identity, style = MaterialTheme.typography.labelLarge)
}
Text(
text = stringResource(R.string.chat_failure_details_guidance),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
shape = MaterialTheme.shapes.small,
) {
SelectionContainer {
Text(
text = failure.rawError,
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
style = MaterialTheme.typography.bodySmall,
)
}
}
}
},
confirmButton = {
TextButton(onClick = onCopy) {
Text(stringResource(R.string.chat_failure_copy_details))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.common_close))
}
},
)
}
internal fun failureIdentity(route: String, model: String?, provider: String?): String =
listOfNotNull(
route.takeIf { it.isNotBlank() },
provider?.trim()?.takeIf { it.isNotEmpty() },
model?.trim()?.takeIf { it.isNotEmpty() },
).distinct().joinToString(" · ")
@@ -29,7 +29,6 @@ import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
@@ -65,6 +64,7 @@ import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.contentDescription
@@ -94,7 +94,7 @@ import kotlinx.coroutines.delay
*/
enum class ChatInputTrailing { SEND, VOICE, STOP, STEER, QUEUE }
private val ChatComposerShape = RoundedCornerShape(18.dp)
private val ChatComposerShape = RoundedCornerShape(26.dp)
private val ChatInputChipShape = RoundedCornerShape(12.dp)
internal const val CHAT_INPUT_FIELD_TEST_TAG = "chat-input-field"
@@ -187,14 +187,24 @@ fun ChatInputBar(
modifier: Modifier = Modifier,
surfaceModifier: Modifier = Modifier,
enabled: Boolean = true,
submitEnabled: Boolean = true,
physicalEnterSends: Boolean = true,
largePasteThreshold: Int? = null,
onLargePaste: (String) -> Unit = {},
) {
val canSubmit = enabled && trailing in setOf(
val canSubmit = enabled && submitEnabled && trailing in setOf(
ChatInputTrailing.SEND,
ChatInputTrailing.STEER,
ChatInputTrailing.QUEUE,
)
// Enter only means "send" when a physical keyboard is attached (see
// the key handler below). Read the configuration here, in the composable
// scope, and capture it for the non-composable onPreviewKeyEvent lambda.
val keyboardAttached =
LocalConfiguration.current.keyboard !=
android.content.res.Configuration.KEYBOARD_NOKEYS
// Keep the last caption around so the AnimatedVisibility exit doesn't
// flash an empty line while collapsing.
var lastCaption by remember { mutableStateOf<String?>(null) }
@@ -315,7 +325,7 @@ fun ChatInputBar(
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 6.dp)
.padding(horizontal = 8.dp, vertical = 3.dp)
.then(surfaceModifier),
) {
Column {
@@ -341,15 +351,24 @@ fun ChatInputBar(
}
Column(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
modifier = Modifier.padding(horizontal = 6.dp, vertical = 3.dp),
) {
BasicTextField(
value = value,
onValueChange = { if (it.length <= charLimit) onValueChange(it) },
onValueChange = { updated ->
val converted = largePasteThreshold
?.let { threshold -> detectLargeTextInsertion(value, updated, threshold) }
if (converted != null) {
onValueChange(converted.remainingText)
onLargePaste(converted.insertedText)
} else if (updated.length <= charLimit) {
onValueChange(updated)
}
},
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 34.dp)
.padding(horizontal = 8.dp, vertical = 4.dp)
.heightIn(min = 30.dp)
.padding(horizontal = 10.dp, vertical = 2.dp)
// Keep directional keys inside the editor. Compose's
// BasicTextField owns normal caret/selection movement;
// cancelling focus traversal prevents a boundary arrow
@@ -364,10 +383,18 @@ fun ChatInputBar(
val native = event.nativeKeyEvent
val isEnter = native.keyCode == android.view.KeyEvent.KEYCODE_ENTER ||
native.keyCode == android.view.KeyEvent.KEYCODE_NUMPAD_ENTER
// Enter only means "send" when a physical keyboard is
// attached. IME-dispatched Enter (commitText or a
// synthesized KEYCODE_ENTER) must always fall through
// so the soft keyboard's return key inserts a newline
// instead of sending (issue #367). Key events alone
// cannot distinguish physical vs IME origin — deviceId
// is 0 or -1 depending on the IME — so gate on the
// hardware keyboard configuration (read above).
val isSubmitShortcut = native.isCtrlPressed || native.isMetaPressed
if (native.action != android.view.KeyEvent.ACTION_DOWN || !isEnter) {
false
} else if (isSubmitShortcut || (physicalEnterSends && !native.isShiftPressed)) {
} else if (isSubmitShortcut || (keyboardAttached && physicalEnterSends && !native.isShiftPressed)) {
if (canSubmit) onSend()
true
} else {
@@ -382,10 +409,10 @@ fun ChatInputBar(
enabled = enabled,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Send,
),
keyboardActions = KeyboardActions(
onSend = { if (canSubmit) onSend() },
// The field is multiline and already has a dedicated
// send button. Leave the software keyboard action as
// Return; hardware Enter remains handled above.
imeAction = ImeAction.Default,
),
textStyle = MaterialTheme.typography.bodyLarge.copy(
color = MaterialTheme.colorScheme.onSurface,
@@ -408,7 +435,7 @@ fun ChatInputBar(
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp),
.heightIn(min = 44.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
@@ -521,12 +548,12 @@ fun ChatInputBar(
when (state) {
ChatInputTrailing.SEND -> IconButton(
onClick = onSend,
enabled = enabled,
enabled = canSubmit,
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.Send,
contentDescription = stringResource(R.string.chat_input_send_message),
tint = if (enabled) MaterialTheme.colorScheme.primary
tint = if (canSubmit) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
@@ -580,7 +607,7 @@ fun ChatInputBar(
ChatInputTrailing.STEER -> IconButton(
onClick = onSend,
enabled = enabled,
enabled = canSubmit,
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.Send,
@@ -591,7 +618,7 @@ fun ChatInputBar(
ChatInputTrailing.QUEUE -> IconButton(
onClick = onSend,
enabled = enabled,
enabled = canSubmit,
) {
Box {
Icon(
@@ -620,6 +647,39 @@ fun ChatInputBar(
}
}
internal data class LargeTextInsertion(
val insertedText: String,
val remainingText: String,
)
/** Finds one large contiguous edit without requiring clipboard access or retaining clipboard data. */
internal fun detectLargeTextInsertion(
previous: String,
updated: String,
threshold: Int,
): LargeTextInsertion? {
if (threshold <= 0 || updated == previous) return null
val prefixLength = previous.commonPrefixWith(updated).length
val maxSuffixLength = minOf(
previous.length - prefixLength,
updated.length - prefixLength,
)
var suffixLength = 0
while (
suffixLength < maxSuffixLength &&
previous[previous.lastIndex - suffixLength] == updated[updated.lastIndex - suffixLength]
) {
suffixLength++
}
val insertedEnd = updated.length - suffixLength
val inserted = updated.substring(prefixLength, insertedEnd)
if (inserted.length < threshold) return null
return LargeTextInsertion(
insertedText = inserted,
remainingText = updated.removeRange(prefixLength, insertedEnd),
)
}
@Composable
private fun ChatInputPickerChip(
control: ChatInputPickerControl,
@@ -2249,6 +2249,11 @@ private fun StandardEntryStep(
val apiError = apiUrlSchemeError(apiUrl, context)
val tailscaleError = optionalHttpUrlError(tailscaleApiUrl, context)
val dashboardError = optionalHttpUrlError(dashboardUrl, context)
val apiKeyError = if (apiKey.trim(' ', '\t').any { it < '!' || it > '~' }) {
stringResource(R.string.api_credential_single_line_error)
} else {
null
}
var advancedExpanded by remember { mutableStateOf(false) }
var scanBusy by remember { mutableStateOf(false) }
var scanResults by remember { mutableStateOf<List<HermesLanDiscoveryResult>>(emptyList()) }
@@ -2263,6 +2268,7 @@ private fun StandardEntryStep(
apiError == null &&
tailscaleError == null &&
dashboardError == null &&
apiKeyError == null &&
!isConnecting
val defaultDashboardUrl = Connection.deriveDefaultDashboardUrl(apiUrl)
val effectiveDashboardUrl = dashboardUrl
@@ -2407,8 +2413,9 @@ private fun StandardEntryStep(
label = { Text(stringResource(R.string.cw_api_key_label)) },
placeholder = { Text(stringResource(R.string.cw_api_key_placeholder)) },
singleLine = true,
isError = apiKeyError != null,
supportingText = {
Text(stringResource(R.string.cw_api_key_hint))
Text(apiKeyError ?: stringResource(R.string.cw_api_key_hint))
},
visualTransformation = if (apiKeyVisible) {
VisualTransformation.None
@@ -0,0 +1,81 @@
package com.hermesandroid.relay.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.WarningAmber
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
/** Persistent, server-authored resource-pressure warning for the active Hermes host. */
@Composable
fun HostResourcePressureBanner(
text: String,
critical: Boolean,
includeStatusBarPadding: Boolean,
modifier: Modifier = Modifier,
) {
val background = if (critical) {
MaterialTheme.colorScheme.errorContainer
} else {
MaterialTheme.colorScheme.tertiaryContainer
}
val foreground = if (critical) {
MaterialTheme.colorScheme.onErrorContainer
} else {
MaterialTheme.colorScheme.onTertiaryContainer
}
Column(
modifier = modifier
.fillMaxWidth()
.background(background)
.then(
if (includeStatusBarPadding) {
Modifier.windowInsetsPadding(WindowInsets.statusBars)
} else {
Modifier
},
),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 32.dp)
.padding(horizontal = 12.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(
imageVector = Icons.Outlined.WarningAmber,
contentDescription = null,
tint = foreground,
modifier = Modifier.size(17.dp),
)
Text(
text = text,
color = foreground,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Medium,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
}
}
@@ -15,9 +15,13 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -51,6 +55,8 @@ import com.mikepenz.markdown.m3.markdownColor
import com.mikepenz.markdown.m3.markdownTypography
import com.mikepenz.markdown.model.markdownDimens
import com.mikepenz.markdown.model.markdownExtendedSpans
import com.mikepenz.markdown.model.rememberStreamingMarkdownState
import com.mikepenz.markdown.model.StreamingMarkdownState
import com.hermesandroid.relay.ui.theme.LocalBrand
import dev.snipme.highlights.Highlights
import dev.snipme.highlights.model.SyntaxThemes
@@ -66,6 +72,23 @@ fun MarkdownContent(
textColor: Color,
modifier: Modifier = Modifier
) {
ConfiguredMarkdownContent(
content = content,
textColor = textColor,
modifier = modifier,
)
}
@Composable
private fun ConfiguredMarkdownContent(
textColor: Color,
modifier: Modifier = Modifier,
content: String? = null,
streamingState: StreamingMarkdownState? = null,
) {
require((content == null) != (streamingState == null)) {
"Exactly one Markdown source must be provided"
}
val isDarkTheme = LocalBrand.current.isDark
val chatBodyStyle = MaterialTheme.typography.bodyMedium.copy(
fontSize = 15.sp,
@@ -75,109 +98,108 @@ fun MarkdownContent(
val highlightsBuilder = remember(isDarkTheme) {
Highlights.Builder().theme(SyntaxThemes.atom(darkMode = isDarkTheme))
}
Markdown(
content = content,
modifier = modifier,
// Code surfaces must contrast against the bubble (which is itself
// surfaceVariant for assistant turns) or code reads as invisible. The
// block uses the lowest container (a darker inset in dark themes, a
// clean white inset in light), inline code a subtle raised step.
colors = markdownColor(
text = textColor,
codeBackground = MaterialTheme.colorScheme.surfaceContainerLowest,
inlineCodeBackground = MaterialTheme.colorScheme.surfaceContainerHighest
),
// Chat-tuned type ramp. Left unset, the mikepenz M3 defaults map headings
// to DISPLAY roles (in this app's scale h1=displayLarge 57sp, h2=displayMedium
// ~45sp, h3=displaySmall 36sp) — a single `#` becomes a billboard inside the
// ~272dp bubble. Here every level derives from bodyLarge/bodyMedium (so the
// live font-picker still applies) and is capped so the largest heading is
// proportionate to the 15sp body, matching Discord / GitHub-mobile
// in-message headings.
typography = markdownTypography(
h1 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold, color = textColor,
),
h2 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp, lineHeight = 24.sp, fontWeight = FontWeight.Bold, color = textColor,
),
h3 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.SemiBold, color = textColor,
),
h4 = MaterialTheme.typography.bodyMedium.copy(
fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold, color = textColor,
),
h5 = MaterialTheme.typography.bodyMedium.copy(
fontWeight = FontWeight.Bold, color = textColor,
),
h6 = MaterialTheme.typography.bodyMedium.copy(
fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.4.sp,
color = textColor.copy(alpha = 0.85f),
),
// Prose, list items, and quotes share a 15sp/21sp reading rhythm.
// The library default 'text'/list role is bodyLarge (16sp), while
// bodyMedium was previously 14sp and unnecessarily small for long chat.
paragraph = chatBodyStyle,
text = chatBodyStyle,
bullet = chatBodyStyle,
ordered = chatBodyStyle,
list = chatBodyStyle,
quote = chatBodyStyle.copy(
fontStyle = FontStyle.Italic,
color = textColor.copy(alpha = 0.9f),
),
// Inline + fenced code at 13sp (one step under body, not two): monospace
// + the tinted chip already signal "code" without also shrinking it, and
// the loose 0.4sp default tracking is reset to 0 for tighter token runs.
code = MaterialTheme.typography.bodySmall.copy(
fontSize = 13.sp, letterSpacing = 0.sp,
fontFamily = FontFamily.Monospace,
color = textColor,
),
inlineCode = MaterialTheme.typography.bodyMedium.copy(
fontSize = 13.sp, letterSpacing = 0.sp,
fontFamily = FontFamily.Monospace, color = textColor,
),
// Links get an accent color + underline so they read as tappable on the
// muted assistant bubble (the default textLink is body-colored).
textLink = TextLinkStyles(
style = SpanStyle(
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
textDecoration = TextDecoration.Underline,
),
),
),
// Tables get a phone-friendly minimum measure. The stock renderer uses
// one-line cells; our table component below keeps the same AST/inline
// annotator path but permits wrapping and exposes horizontal overflow.
dimens = markdownDimens(
tableCellWidth = 110.dp,
tableCellPadding = 12.dp,
),
components = markdownComponents(
codeBlock = {
SafeMarkdownHighlightedCodeBlock(
content = it.content,
node = it.node,
highlightsBuilder = highlightsBuilder,
showHeader = true
)
},
codeFence = {
SafeMarkdownHighlightedCodeFence(
content = it.content,
node = it.node,
highlightsBuilder = highlightsBuilder,
showHeader = true
)
},
table = { WideMarkdownTable(it) },
),
extendedSpans = markdownExtendedSpans {
remember { ExtendedSpans(RoundedCornerSpanPainter()) }
}
// Code surfaces must contrast against the assistant bubble. Keeping these
// exact values shared between static and streaming renderers prevents a
// typography/color change when a live turn completes.
val colors = markdownColor(
text = textColor,
codeBackground = MaterialTheme.colorScheme.surfaceContainerLowest,
inlineCodeBackground = MaterialTheme.colorScheme.surfaceContainerHighest,
)
val typography = markdownTypography(
h1 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold, color = textColor,
),
h2 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp, lineHeight = 24.sp, fontWeight = FontWeight.Bold, color = textColor,
),
h3 = MaterialTheme.typography.bodyLarge.copy(
fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.SemiBold, color = textColor,
),
h4 = MaterialTheme.typography.bodyMedium.copy(
fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold, color = textColor,
),
h5 = MaterialTheme.typography.bodyMedium.copy(
fontWeight = FontWeight.Bold, color = textColor,
),
h6 = MaterialTheme.typography.bodyMedium.copy(
fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.4.sp,
color = textColor.copy(alpha = 0.85f),
),
paragraph = chatBodyStyle,
text = chatBodyStyle,
bullet = chatBodyStyle,
ordered = chatBodyStyle,
list = chatBodyStyle,
quote = chatBodyStyle.copy(
fontStyle = FontStyle.Italic,
color = textColor.copy(alpha = 0.9f),
),
code = MaterialTheme.typography.bodySmall.copy(
fontSize = 13.sp,
letterSpacing = 0.sp,
fontFamily = FontFamily.Monospace,
color = textColor,
),
inlineCode = MaterialTheme.typography.bodyMedium.copy(
fontSize = 13.sp,
letterSpacing = 0.sp,
fontFamily = FontFamily.Monospace,
color = textColor,
),
textLink = TextLinkStyles(
style = SpanStyle(
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
textDecoration = TextDecoration.Underline,
),
),
)
val dimens = markdownDimens(tableCellWidth = 110.dp, tableCellPadding = 12.dp)
val components = markdownComponents(
codeBlock = {
SafeMarkdownHighlightedCodeBlock(
content = it.content,
node = it.node,
highlightsBuilder = highlightsBuilder,
showHeader = true,
)
},
codeFence = {
SafeMarkdownHighlightedCodeFence(
content = it.content,
node = it.node,
highlightsBuilder = highlightsBuilder,
showHeader = true,
)
},
table = { WideMarkdownTable(it) },
)
val extendedSpans = markdownExtendedSpans {
remember { ExtendedSpans(RoundedCornerSpanPainter()) }
}
if (streamingState != null) {
Markdown(
streamingMarkdownState = streamingState,
modifier = modifier,
colors = colors,
typography = typography,
dimens = dimens,
components = components,
extendedSpans = extendedSpans,
)
} else {
Markdown(
content = checkNotNull(content),
modifier = modifier,
colors = colors,
typography = typography,
dimens = dimens,
components = components,
extendedSpans = extendedSpans,
)
}
}
/**
@@ -291,39 +313,63 @@ private fun WideMarkdownTable(model: MarkdownComponentModel) {
fun StreamingMarkdownContent(
content: String,
textColor: Color,
isStreaming: Boolean = true,
modifier: Modifier = Modifier,
) {
if (isStreaming) {
// Keep one stable layout node for the entire live turn. Promoting each
// blank-terminated paragraph into Markdown replaced the Text subtree
// repeatedly; LazyColumn then exposed its fallback anchor for a frame,
// which looked like the whole chat reloaded. Updating this Text value
// only remeasures the growing bubble. Full Markdown is parsed once the
// owning row releases its stable live-tail layout.
Text(
// CommonMark ignores blank lines before the first block. The live
// Text renderer must do the same or a response whose transport
// prefix contains newlines appears to start several lines down.
// Preserve indentation on the first non-blank line so indented
// code and deliberately spaced prose are not altered.
text = content.withoutLeadingBlankLines(),
modifier = modifier,
style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 15.sp,
lineHeight = 21.sp,
),
color = textColor,
)
} else {
MarkdownContent(
content = content,
var generation by remember { mutableIntStateOf(0) }
key(generation) {
NativeStreamingMarkdownGeneration(
content = content.withoutLeadingBlankLines(),
textColor = textColor,
modifier = modifier,
onResetRequired = { generation += 1 },
)
}
}
@Composable
private fun NativeStreamingMarkdownGeneration(
content: String,
textColor: Color,
modifier: Modifier,
onResetRequired: () -> Unit,
) {
val streamingState = rememberStreamingMarkdownState()
LaunchedEffect(content, streamingState) {
val plan = planStreamingMarkdownAppend(
renderedContent = streamingState.content.toString(),
nextContent = content,
)
if (plan.resetRequired) {
onResetRequired()
} else if (plan.delta.isNotEmpty()) {
streamingState.append(plan.delta)
}
}
ConfiguredMarkdownContent(
streamingState = streamingState,
textColor = textColor,
modifier = modifier,
)
}
internal data class StreamingMarkdownAppendPlan(
val resetRequired: Boolean,
val delta: String,
)
internal fun planStreamingMarkdownAppend(
renderedContent: String,
nextContent: String,
): StreamingMarkdownAppendPlan = if (nextContent.startsWith(renderedContent)) {
StreamingMarkdownAppendPlan(
resetRequired = false,
delta = nextContent.substring(renderedContent.length),
)
} else {
StreamingMarkdownAppendPlan(resetRequired = true, delta = "")
}
internal fun String.withoutLeadingBlankLines(): String {
var contentStart = 0
while (contentStart < length) {
@@ -42,6 +42,9 @@ import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
@@ -252,6 +255,7 @@ private fun MessageRow(
Row(
modifier = Modifier
.fillMaxWidth()
.semantics { liveRegion = LiveRegionMode.Polite }
.heightIn(min = ROW_MIN_HEIGHT_DP.dp)
.padding(horizontal = 10.dp, vertical = 7.dp),
horizontalArrangement = Arrangement.spacedBy(9.dp),
@@ -1,7 +1,6 @@
package com.hermesandroid.relay.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -27,6 +26,7 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
@@ -34,7 +34,6 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.draw.clip
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.text.selection.DisableSelection
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.VolumeUp
import androidx.compose.material.icons.filled.ContentCopy
@@ -43,6 +42,7 @@ import androidx.compose.material.icons.filled.FormatQuote
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
@@ -90,6 +90,7 @@ import java.text.SimpleDateFormat
import java.util.Date
internal const val CHAT_PET_IDENTITY_OBSTACLE_PREFIX = "chat-message-identity:"
private val MESSAGE_REACTIONS = listOf("❤️", "👍", "👎", "😂", "‼️", "❓")
@OptIn(ExperimentalFoundationApi::class)
@Composable
@@ -100,13 +101,6 @@ fun MessageBubble(
showThinking: Boolean = true,
isFirstInGroup: Boolean = true,
isLastInGroup: Boolean = true,
/**
* Keeps the current live tail on its stable Text layout while a final
* streaming frame commits. The owning list releases it immediately after
* completion so the same row transitions to full Markdown with its bottom
* anchor preserved.
*/
retainStreamingLayout: Boolean = false,
onCopyMessage: (String) -> Unit = {},
/**
* Select this message as a structured composer quote. Null hides Quote.
@@ -455,11 +449,51 @@ fun MessageBubble(
val showEditAction = onEditMessage != null && isUser
val showSpeakAction = shouldShowSpeakResponseAction(message, onSpeakMessage != null)
val showStopSpeakingAction = shouldShowStopSpeakingAction(message, onStopSpeaking != null)
val selectedUserReaction = message.reactions.firstOrNull { it.author == "user" }?.emoji
if (onQuoteMessage != null || onReact != null || showEditAction || showSpeakAction || showStopSpeakingAction) {
DropdownMenu(
expanded = showMessageActions,
onDismissRequest = { showMessageActions = false },
shape = RoundedCornerShape(24.dp),
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 3.dp,
shadowElevation = 8.dp,
) {
if (onReact != null) {
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 6.dp),
) {
MESSAGE_REACTIONS.forEach { emoji ->
IconButton(
onClick = {
showMessageActions = false
onReact(emoji)
},
modifier = Modifier.background(
color = if (selectedUserReaction == emoji) {
MaterialTheme.colorScheme.secondaryContainer
} else {
Color.Transparent
},
shape = CircleShape,
),
) {
Text(
text = emoji,
fontSize = 24.sp,
modifier = Modifier.semantics {
contentDescription = "React with $emoji"
},
)
}
}
}
HorizontalDivider()
}
DropdownMenuItem(
text = { Text(stringResource(R.string.msg_bubble_copy)) },
onClick = {
@@ -515,32 +549,26 @@ fun MessageBubble(
},
)
}
if (onReact != null && selectedUserReaction != null) {
DropdownMenuItem(
text = { Text("Remove reaction") },
onClick = {
showMessageActions = false
onReact(null)
},
)
}
}
}
Box(
modifier = Modifier.padding(
bottom = if (message.reactions.isNotEmpty()) 8.dp else 0.dp,
),
) {
Surface(
shape = bubbleShape,
color = backgroundColor,
modifier = Modifier
.then(
if (!isUser && !isSystem &&
(message.isStreaming || retainStreamingLayout)
) {
// The frame-paced text node is already measured at its
// new size. Animate and clip the owning surface so a
// newly wrapped line is revealed inside the expanding
// bubble instead of drawing below the previous bounds
// for one frame. TopStart keeps existing prose fixed.
Modifier.animateContentSize(
animationSpec = tween(
durationMillis = 72,
easing = LinearOutSlowInEasing,
),
alignment = Alignment.TopStart,
)
} else {
Modifier
}
)
.then(
if (!isUser && !isSystem && isDarkTheme) {
Modifier.leftEdgeGlow(
@@ -558,7 +586,7 @@ fun MessageBubble(
// same tactile confirm every chat app fires.
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
if (
onQuoteMessage != null || showEditAction || showSpeakAction ||
onQuoteMessage != null || onReact != null || showEditAction || showSpeakAction ||
showStopSpeakingAction
) {
showMessageActions = true
@@ -613,57 +641,29 @@ fun MessageBubble(
color = textColor
)
} else {
// Keep one plain Text node stable only while content is
// incomplete (plus the final committed live frame).
// Completion releases this flag and selects the full
// Markdown tree on the same stable message row.
// The renderer owns one incremental AST for the entire
// visible lifetime of this row. Stable and provisional
// blocks therefore use the same typography/components;
// completion is data state, not a renderer swap.
if (markdownBody.isNotEmpty()) {
StreamingMarkdownContent(
content = markdownBody,
textColor = textColor,
isStreaming = message.isStreaming || retainStreamingLayout,
)
}
}
}
// Compose's SelectionManager assumes that selectable IDs
// captured by a drag remain registered. Reset its owner when
// a live Text node becomes a Markdown tree, or settled
// Markdown content changes its node topology, so a handle
// cannot keep pointing at a removed selectable.
if (showSpeakAction || showStopSpeakingAction) {
DisableSelection { messageTextContent() }
} else {
key(
messageSelectionTopologyKey(
isPlainText = isUser || isSystem,
isStreaming = message.isStreaming,
retainStreamingLayout = retainStreamingLayout,
markdownBody = markdownBody,
),
) {
SelectionContainer { messageTextContent() }
}
// Voice actions live outside the message body and must never
// replace its selection owner. Speak becomes available exactly
// at completion; branching on it here recreated the complete
// incremental Markdown state for one frame.
key(
messageSelectionTopologyKey(
isPlainText = isUser || isSystem,
),
) {
SelectionContainer { messageTextContent() }
}
if (onReact != null) {
listOf("👍", "❤️", "😂").forEach { emoji ->
DropdownMenuItem(
text = { Text("React $emoji") },
onClick = {
showMessageActions = false
onReact(emoji)
},
)
}
DropdownMenuItem(
text = { Text("Remove reaction") },
onClick = {
showMessageActions = false
onReact(null)
},
)
}
if (onSessionReference != null && sessionReferences.isNotEmpty()) {
sessionReferences.forEach { reference ->
TextButton(
@@ -788,26 +788,39 @@ fun MessageBubble(
}
}
val hasTokenUsage = !isUser &&
(message.inputTokens != null || message.outputTokens != null)
// Timestamp — only on the LAST bubble of a same-author run so a
// burst of fragments doesn't stack three near-touching time labels.
// Grouping breaks on a >5min gap (ChatScreen), so every pause still
// surfaces its own time. Alpha floored at 0.6 for 11sp contrast.
// Reserve the footer from the first streaming frame so
// completion is a color-only transition and cannot resize the
// row. Hide the reserved timestamp from accessibility until it
// becomes visible.
// This row is reserved from the first streaming frame. Completion
// can reveal both timestamp and token usage without adding a new
// footer line or changing the bubble's measured height.
if (isLastInGroup) {
Spacer(modifier = Modifier.height(2.dp))
Text(
text = timeFormat.format(Date(message.timestamp)),
style = MaterialTheme.typography.labelSmall,
color = textColor.copy(alpha = if (message.isStreaming) 0f else 0.6f),
modifier = if (message.isStreaming) {
Modifier.clearAndSetSemantics { }
} else {
Modifier
},
)
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = timeFormat.format(Date(message.timestamp)),
style = MaterialTheme.typography.labelSmall,
color = textColor.copy(alpha = if (message.isStreaming) 0f else 0.6f),
modifier = if (message.isStreaming) {
Modifier.clearAndSetSemantics { }
} else {
Modifier
},
)
if (hasTokenUsage) {
TokenDisplay(
inputTokens = message.inputTokens,
outputTokens = message.outputTokens,
)
}
}
}
// Delivery status — only on agent-Thread reply bubbles (a user
@@ -828,16 +841,30 @@ fun MessageBubble(
)
}
// Token display (assistant messages only)
if (!isUser && (message.inputTokens != null || message.outputTokens != null)) {
// Non-tail historical fragments have no reserved timestamp row.
// Preserve their existing standalone token metadata layout.
if (!isLastInGroup && hasTokenUsage) {
Spacer(modifier = Modifier.height(2.dp))
TokenDisplay(
inputTokens = message.inputTokens,
outputTokens = message.outputTokens
outputTokens = message.outputTokens,
)
}
}
}
if (message.reactions.isNotEmpty()) {
MessageReactionBadge(
reactions = message.reactions.map { it.emoji },
onOpen = onReact?.let { { showMessageActions = true } },
modifier = Modifier
.align(if (isUser) Alignment.BottomEnd else Alignment.BottomStart)
.offset(
x = if (isUser) (-10).dp else 10.dp,
y = 9.dp,
),
)
}
}
val inlineActions: @Composable () -> Unit = {
MessageInlineActions(
showQuote = onQuoteMessage != null,
@@ -890,6 +917,41 @@ fun MessageBubble(
} // end CompositionLocalProvider(LocalMediaBlurMode)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MessageReactionBadge(
reactions: List<String>,
onOpen: (() -> Unit)?,
modifier: Modifier = Modifier,
) {
val description = "Reactions: ${reactions.joinToString(" ")}"
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest,
tonalElevation = 2.dp,
shadowElevation = 2.dp,
modifier = modifier
.then(
if (onOpen != null) {
Modifier.combinedClickable(onClick = onOpen, onLongClick = onOpen)
} else {
Modifier
},
)
.semantics { contentDescription = description },
) {
Row(
horizontalArrangement = Arrangement.spacedBy(2.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 7.dp, vertical = 3.dp),
) {
reactions.forEach { emoji ->
Text(text = emoji, fontSize = 14.sp, lineHeight = 16.sp)
}
}
}
}
@Composable
private fun MessageInlineActions(
showQuote: Boolean,
@@ -966,14 +1028,9 @@ internal data class MessageSelectionTopologyKey(
internal fun messageSelectionTopologyKey(
isPlainText: Boolean,
isStreaming: Boolean,
retainStreamingLayout: Boolean,
markdownBody: String,
): MessageSelectionTopologyKey = when {
isPlainText -> MessageSelectionTopologyKey(renderer = "plain", markdownBody = null)
isStreaming || retainStreamingLayout ->
MessageSelectionTopologyKey(renderer = "live", markdownBody = null)
else -> MessageSelectionTopologyKey(renderer = "markdown", markdownBody = markdownBody)
else -> MessageSelectionTopologyKey(renderer = "streaming-markdown", markdownBody = null)
}
/**
@@ -14,7 +14,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.withFrameNanos
import kotlinx.coroutines.delay
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
@@ -55,9 +54,6 @@ private const val SPHERE_TIME_UNITS_PER_SEC = 1f
private const val SPHERE_TWO_PI = 6.2832f
private const val SPHERE_COLOR_RADIANS_PER_SEC = 0.7854f
// Idle cadence: this delay plus the next frame wait nets a ~33ms period (~30fps).
private const val SPHERE_IDLE_FRAME_INTERVAL_MS = 25L
@Composable
fun MorphingSphere(
modifier: Modifier = Modifier,
@@ -108,19 +104,14 @@ fun MorphingSphere(
val cg2 by animateFloatAsState(targetC.g2, spec, label = "cg2")
val cb2 by animateFloatAsState(targetC.b2, spec, label = "cb2")
// Continuous motion is driven by a manual frame loop rather than
// rememberInfiniteTransition so the redraw rate can follow the orb's
// activity. An infinite transition pins the Canvas at the display refresh
// (120Hz) forever — even when Idle — which needlessly drains battery and,
// on Android 15, makes the platform log `setRequestedFrameRate` on every
// frame. Here we advance every frame while ACTIVE (full-smoothness
// thinking/streaming/voice pulse) and throttle to ~30fps while Idle, where
// the slower cadence is imperceptible for the chunky ASCII glyphs.
// dt-based accumulation keeps the animation speed identical at either rate.
// Continuous motion runs only for active agent/voice states. Idle is a
// stable frame: the 58x34 text grid is expensive enough that even a
// throttled cosmetic drift dominated measured screen-on CPU. Active states
// retain full display-rate motion and dt-based timing.
val animatedTime = remember { mutableFloatStateOf(0f) }
val animatedColorPhase = remember { mutableFloatStateOf(0f) }
val driveAnimation = fixedTime == null || fixedColorPhase == null
val fullFrameRate = state != SphereState.Idle || effVoiceMode
val driveAnimation = (fixedTime == null || fixedColorPhase == null) && fullFrameRate
if (driveAnimation) {
LaunchedEffect(fullFrameRate) {
var lastNanos = withFrameNanos { it }
@@ -133,7 +124,6 @@ fun MorphingSphere(
animatedColorPhase.floatValue =
(animatedColorPhase.floatValue + dtSec * SPHERE_COLOR_RADIANS_PER_SEC) %
SPHERE_TWO_PI
if (!fullFrameRate) delay(SPHERE_IDLE_FRAME_INTERVAL_MS)
}
}
}
@@ -146,6 +136,7 @@ fun MorphingSphere(
// Cache covers the ~25 distinct glyphs across charSets/dataChars/debrisChars.
val textMeasurer = rememberTextMeasurer(cacheSize = 64)
val glyphStrings = remember { HashMap<Char, String>(32) }
Canvas(modifier = modifier.fillMaxSize().clipToBounds()) {
val canvasW = size.width
@@ -176,7 +167,8 @@ fun MorphingSphere(
)
forEachSphereCell(frame) { cell ->
val layout = textMeasurer.measure(cell.char.toString(), style)
val glyph = glyphStrings.getOrPut(cell.char) { cell.char.toString() }
val layout = textMeasurer.measure(glyph, style)
// Legacy Paint used y as baseline (`row*cellH + cellH*0.8f`).
// Compose `drawText` uses top-left — offset by firstBaseline to match.
val px = cell.col * cellW
@@ -73,6 +73,7 @@ import com.hermesandroid.relay.data.ApiEndpoint
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.DashboardEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
import com.hermesandroid.relay.data.RelayEndpoint
import androidx.compose.ui.res.stringResource
import com.hermesandroid.relay.R
@@ -300,6 +301,11 @@ private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
} else {
decoded
}
val normalizedKey = normalizeCredentialForHeader(
decodedWithAliases.key,
"API credential",
)
val decodedWithSafeCredential = decodedWithAliases.copy(key = normalizedKey)
// TODO(security): verify `decoded.sig` against the server's HMAC
// secret once the pairing protocol exposes a public verification
@@ -310,12 +316,12 @@ private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
// Synthesize a single priority-0 candidate from the top-level fields
// when the wire payload didn't carry an explicit `endpoints` array.
// v3+ payloads with an explicit array pass through untouched.
if (decodedWithAliases.endpoints.isNullOrEmpty()) {
decodedWithAliases.copy(
endpoints = listOf(synthesizeLegacyEndpoint(decodedWithAliases)),
if (decodedWithSafeCredential.endpoints.isNullOrEmpty()) {
decodedWithSafeCredential.copy(
endpoints = listOf(synthesizeLegacyEndpoint(decodedWithSafeCredential)),
)
} else {
decodedWithAliases
decodedWithSafeCredential
}
} catch (_: Exception) {
null
@@ -396,10 +402,13 @@ private fun payloadFromApiUrl(
else -> return null
}
val host = uri.host?.takeIf { it.isNotBlank() } ?: return null
val normalizedKey = runCatching {
normalizeCredentialForHeader(apiKey, "API credential")
}.getOrNull() ?: return null
val payload = HermesPairingPayload(
host = host,
port = if (uri.port > 0) uri.port else 8642,
key = apiKey.trim(),
key = normalizedKey,
tls = tls,
dashboardUrl = dashboardUrl?.trim()?.takeIf { it.isNotBlank() },
relay = null,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,167 @@
package com.hermesandroid.relay.ui.components
import com.hermesandroid.relay.data.ChatSession
import com.hermesandroid.relay.data.SessionActivityState
import java.util.Locale
internal enum class SessionDrawerGrouping {
None,
Updated,
Project,
Status,
Profile,
}
internal enum class SessionDrawerOrdering {
Updated,
Created,
Title,
Status,
Tokens,
Cost,
}
internal enum class SessionDrawerStatus {
NeedsInput,
Working,
Idle,
}
internal enum class SessionDrawerPrState {
Open,
Draft,
Merged,
Closed,
None,
}
internal data class SessionDrawerViewOptions(
val grouping: SessionDrawerGrouping = SessionDrawerGrouping.None,
val ordering: SessionDrawerOrdering = SessionDrawerOrdering.Updated,
val statuses: Set<SessionDrawerStatus> = emptySet(),
val profiles: Set<String> = emptySet(),
val projects: Set<String> = emptySet(),
val pullRequests: Set<SessionDrawerPrState> = emptySet(),
val showProfile: Boolean = false,
val showUpdated: Boolean = true,
val showTokens: Boolean = false,
val showCost: Boolean = false,
)
internal data class SessionDrawerGroup(
val key: String,
val label: String?,
val rows: List<ProfileSessionRow>,
)
internal fun sessionRowKey(row: ProfileSessionRow): String =
"${row.profile.lowercase(Locale.ROOT)}:${row.session.sessionId}"
internal fun sessionProjectLabel(session: ChatSession): String {
val raw = (session.gitRepoRoot ?: session.workingDirectory)
?.trim()
?.trimEnd('/', '\\')
.orEmpty()
if (raw.isBlank()) return "No project"
return raw.substringAfterLast('/').substringAfterLast('\\').ifBlank { raw }
}
internal fun sessionDrawerStatus(
row: ProfileSessionRow,
activityStates: Map<String, SessionActivityState>,
): SessionDrawerStatus = when (
activityStates[sessionRowKey(row)] ?: activityStates[row.session.sessionId]
) {
SessionActivityState.NeedsInput -> SessionDrawerStatus.NeedsInput
SessionActivityState.Working -> SessionDrawerStatus.Working
null -> if (row.session.isActive) SessionDrawerStatus.Working else SessionDrawerStatus.Idle
}
internal fun sessionDrawerPrState(session: ChatSession): SessionDrawerPrState = when {
session.pullRequestNumber == null -> SessionDrawerPrState.None
session.pullRequestDraft -> SessionDrawerPrState.Draft
session.pullRequestState.equals("merged", ignoreCase = true) -> SessionDrawerPrState.Merged
session.pullRequestState.equals("closed", ignoreCase = true) -> SessionDrawerPrState.Closed
else -> SessionDrawerPrState.Open
}
internal fun filterAndSortSessionRows(
rows: List<ProfileSessionRow>,
options: SessionDrawerViewOptions,
activityStates: Map<String, SessionActivityState> = emptyMap(),
): List<ProfileSessionRow> {
val filtered = rows.asSequence()
.filter { options.statuses.isEmpty() || sessionDrawerStatus(it, activityStates) in options.statuses }
.filter { options.profiles.isEmpty() || it.profile in options.profiles }
.filter { options.projects.isEmpty() || sessionProjectLabel(it.session) in options.projects }
.filter { options.pullRequests.isEmpty() || sessionDrawerPrState(it.session) in options.pullRequests }
.toList()
val statusRank = mapOf(
SessionDrawerStatus.NeedsInput to 0,
SessionDrawerStatus.Working to 1,
SessionDrawerStatus.Idle to 2,
)
val comparator = when (options.ordering) {
SessionDrawerOrdering.Updated -> compareByDescending<ProfileSessionRow> { it.session.activityTimestamp }
SessionDrawerOrdering.Created -> compareByDescending { it.session.startTimestamp }
SessionDrawerOrdering.Title -> compareBy { it.session.title.orEmpty().lowercase(Locale.ROOT) }
SessionDrawerOrdering.Status -> compareBy { statusRank.getValue(sessionDrawerStatus(it, activityStates)) }
SessionDrawerOrdering.Tokens -> compareByDescending { it.session.totalTokens }
SessionDrawerOrdering.Cost -> compareByDescending { it.session.costUsd }
}
return filtered.sortedWith(
compareByDescending<ProfileSessionRow> { it.session.pinned }
.then(comparator)
.thenBy { it.session.title.orEmpty().lowercase(Locale.ROOT) },
)
}
internal fun groupSessionRows(
rows: List<ProfileSessionRow>,
grouping: SessionDrawerGrouping,
activityStates: Map<String, SessionActivityState> = emptyMap(),
nowMillis: Long = System.currentTimeMillis(),
): List<SessionDrawerGroup> {
if (rows.isEmpty()) return emptyList()
val grouped = rows.groupBy { row ->
when (grouping) {
SessionDrawerGrouping.None -> null
SessionDrawerGrouping.Updated -> updatedBucket(row.session.activityTimestamp, nowMillis)
SessionDrawerGrouping.Project -> sessionProjectLabel(row.session)
SessionDrawerGrouping.Status -> sessionDrawerStatus(row, activityStates).displayLabel
SessionDrawerGrouping.Profile -> row.profile
}
}
val groups = grouped.map { (label, groupRows) ->
SessionDrawerGroup(key = "${grouping.name}:$label", label = label, rows = groupRows)
}
return if (grouping == SessionDrawerGrouping.Project) {
groups.sortedWith(
compareBy<SessionDrawerGroup> { it.label != "No project" }
.thenByDescending { group -> group.rows.maxOfOrNull { it.session.activityTimestamp } ?: 0L }
.thenBy { it.label.orEmpty().lowercase(Locale.ROOT) },
)
} else {
groups
}
}
private val SessionDrawerStatus.displayLabel: String
get() = when (this) {
SessionDrawerStatus.NeedsInput -> "Needs input"
SessionDrawerStatus.Working -> "Working"
SessionDrawerStatus.Idle -> "Idle"
}
private fun updatedBucket(timestamp: Long, nowMillis: Long): String {
if (timestamp <= 0L) return "Older"
val age = (nowMillis - timestamp).coerceAtLeast(0L)
return when {
age < DAY_MILLIS -> "Today"
age < 2 * DAY_MILLIS -> "Yesterday"
age < 7 * DAY_MILLIS -> "Last 7 days"
else -> "Older"
}
}
private const val DAY_MILLIS = 24L * 60L * 60L * 1_000L
@@ -70,6 +70,8 @@ fun UnattendedAccessRow(
// should reflect that reality — otherwise users flip it and see no
// observable change, which reads as a broken control.
masterEnabled: Boolean = true,
screenControlAvailable: Boolean = true,
screenAccessUnlimited: Boolean = false,
) {
var showWarning by remember { mutableStateOf(false) }
var pendingEnableAfterWarning by remember { mutableStateOf(false) }
@@ -77,7 +79,7 @@ fun UnattendedAccessRow(
// "Effectively on" — the persisted preference AND the master gate.
// Drives the keyguard warning (no point showing it when master is
// off — the feature isn't active regardless of lock state).
val effectivelyOn = enabled && masterEnabled
val effectivelyOn = enabled && masterEnabled && screenControlAvailable
Card(
modifier = modifier.fillMaxWidth(),
@@ -104,6 +106,7 @@ fun UnattendedAccessRow(
Text(
text = when {
!masterEnabled -> stringResource(R.string.unattended_requires_master)
!screenControlAvailable -> stringResource(R.string.unattended_requires_timed_control)
enabled -> stringResource(R.string.unattended_on)
else -> stringResource(R.string.unattended_off)
},
@@ -113,7 +116,7 @@ fun UnattendedAccessRow(
}
Switch(
checked = enabled,
enabled = masterEnabled,
enabled = masterEnabled && screenControlAvailable,
onCheckedChange = { wantsOn ->
if (wantsOn && !warningSeen) {
// First enable → show the scary dialog and
@@ -129,7 +132,13 @@ fun UnattendedAccessRow(
}
Text(
text = stringResource(R.string.unattended_description),
text = stringResource(
if (screenAccessUnlimited) {
R.string.unattended_description_unlimited
} else {
R.string.unattended_description
},
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -190,17 +190,23 @@ fun VoiceWaveform(
// Three phase accumulators driven by a single per-frame ticker. Phase
// velocity scales with the current amplitude so the wave visibly surges
// when the user speaks instead of running on its own fixed clock.
val phases = rememberAmplitudeDrivenPhases(phaseDurationsMs, displayAmplitude)
val waitingForOutputAudio = state == VoiceState.Speaking && !outputAudioActive
val processing = state == VoiceState.Transcribing ||
state == VoiceState.Thinking ||
waitingForOutputAudio
val waveformMotionActive = compactBars || state == VoiceState.Listening ||
(state == VoiceState.Speaking && outputAudioActive)
val phases = rememberAmplitudeDrivenPhases(
phaseDurationsMs,
displayAmplitude,
active = waveformMotionActive,
)
val waveformUnfold by animateFloatAsState(
targetValue = if (processing) 0f else 1f,
animationSpec = tween(durationMillis = 360),
label = "waveformUnfold",
)
val spinnerPhase = rememberProcessingSpinnerPhase(processing)
val spinnerPhase = rememberProcessingSpinnerPhase(active = processing)
val canvasModifier = if (compactBars) {
modifier.height(height)
@@ -361,10 +367,12 @@ fun VoiceWaveform(
private fun rememberAmplitudeDrivenPhases(
baseDurationsMs: IntArray,
amplitude: Float,
active: Boolean,
): FloatArray {
val ampRef = rememberUpdatedState(amplitude)
var phases by remember { mutableStateOf(FloatArray(baseDurationsMs.size)) }
LaunchedEffect(Unit) {
LaunchedEffect(active) {
if (!active) return@LaunchedEffect
val twoPi = (2f * PI).toFloat()
// Precompute base angular velocities (rad/s) so we don't divide on
// every frame. Each wave's full cycle at silence = durationMs.
@@ -400,9 +408,9 @@ private fun rememberAmplitudeDrivenPhases(
@Composable
private fun rememberProcessingSpinnerPhase(active: Boolean): Float {
val activeRef = rememberUpdatedState(active)
var phase by remember { mutableStateOf(0f) }
LaunchedEffect(Unit) {
LaunchedEffect(active) {
if (!active) return@LaunchedEffect
var prevNanos = 0L
while (true) {
withFrameNanos { nanos ->
@@ -412,9 +420,7 @@ private fun rememberProcessingSpinnerPhase(active: Boolean): Float {
}
val dtSec = (nanos - prevNanos) / 1_000_000_000f
prevNanos = nanos
if (activeRef.value) {
phase = (phase + dtSec * 220f) % 360f
}
phase = (phase + dtSec * 220f) % 360f
}
}
}
@@ -0,0 +1,34 @@
package com.hermesandroid.relay.ui.components.avatar
import com.hermesandroid.relay.viewmodel.connection.ProfileController
import java.io.File
/** Adapt upstream `pet.info` geometry to the existing bounded sprite renderer. */
fun ProfileController.HermesPetPresentation.toAvatar(): PetAvatar? {
val sheet = File(spritesheetPath)
if (!sheet.isFile || frameWidth <= 0 || frameHeight <= 0 || framesPerState <= 0) return null
val fps = (framesPerState * 1000f / loopMs.coerceAtLeast(1)).coerceIn(1f, 60f)
val clips = stateRows.mapIndexedNotNull { row, name ->
val normalized = name.trim().takeIf { it.isNotEmpty() } ?: return@mapIndexedNotNull null
val count = (framesByRow[normalized] ?: framesByState[normalized] ?: framesPerState)
.coerceIn(1, framesPerState)
normalized to PetClipSpec(
sheet = sheet.name,
frameWidth = frameWidth,
frameHeight = frameHeight,
frameCount = count,
startFrame = row * framesPerState,
fps = fps,
)
}.toMap()
if (clips["idle"] == null) return null
return runCatching {
PetSpec(
id = "hermes:$slug",
label = displayName,
description = "Profile-scoped Hermes animated pet",
reactive = PetReactiveSpec(voice = false, tools = true, intensity = true),
states = clips,
).toAvatar(sheet.parentFile ?: return null)
}.getOrNull()
}
@@ -61,6 +61,9 @@ import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
import com.hermesandroid.relay.data.BridgeSafetySettings
import com.hermesandroid.relay.bridge.BridgeCapability
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
import com.hermesandroid.relay.bridge.BridgeSafetyManager
import com.hermesandroid.relay.data.DEFAULT_BLOCKLIST
import com.hermesandroid.relay.data.MAX_AUTO_DISABLE_MINUTES
import com.hermesandroid.relay.data.MAX_CONFIRMATION_TIMEOUT_SECONDS
@@ -85,11 +88,18 @@ import kotlinx.coroutines.launch
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BridgeSafetySettingsScreen(onBack: () -> Unit) {
fun BridgeSafetySettingsScreen(
connectionId: String? = null,
onBack: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val repo = remember { BridgeSafetyPreferencesRepository(context) }
val settings by repo.settings.collectAsState(initial = BridgeSafetySettings())
val safetyManager = BridgeSafetyManager.peek()
val capabilityPolicy by (safetyManager?.capabilityPolicy(connectionId)
?: remember { kotlinx.coroutines.flow.MutableStateFlow(BridgeCapabilityPolicy()) })
.collectAsState(initial = BridgeCapabilityPolicy())
// Overlay-permission live check — recompute on resume so returning
// from Settings flips the switch's availability without nav churn.
@@ -140,6 +150,22 @@ fun BridgeSafetySettingsScreen(onBack: () -> Unit) {
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
CapabilityGrantCards(
policy = capabilityPolicy,
timerMinutes = settings.autoDisableMinutes,
enabled = safetyManager != null && connectionId != null,
onPermanentChanged = { capability, allowed ->
scope.launch {
safetyManager?.setPermanentCapability(connectionId, capability, allowed)
}
},
onTimedChanged = { capability, allowed ->
scope.launch {
safetyManager?.setTimedCapability(connectionId, capability, allowed)
}
},
)
// ── Blocklist ───────────────────────────────────────────────
SectionCard(title = stringResource(R.string.bss_blocked_apps)) {
Text(
@@ -359,6 +385,152 @@ fun BridgeSafetySettingsScreen(onBack: () -> Unit) {
}
}
@Composable
internal fun CapabilityGrantCards(
policy: BridgeCapabilityPolicy,
timerMinutes: Int,
enabled: Boolean,
onPermanentChanged: (BridgeCapability, Boolean) -> Unit,
onTimedChanged: (BridgeCapability, Boolean) -> Unit,
) {
SectionCard(title = stringResource(R.string.bridge_access_read_group)) {
Text(
text = stringResource(R.string.bridge_access_read_group_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (!enabled) {
Text(
text = stringResource(R.string.bss_capabilities_unavailable),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(top = 8.dp),
)
}
Spacer(Modifier.size(8.dp))
listOf(
BridgeCapability.DEVICE_INFO,
BridgeCapability.CONTACTS_READ,
BridgeCapability.LOCATION_READ,
BridgeCapability.CLIPBOARD_READ,
).forEach { capability ->
val allowed = capability in policy.permanentGrants
CapabilityRow(
capability = capability,
checked = allowed,
stateLabel = stringResource(
if (allowed) R.string.bss_capability_always else R.string.bss_capability_never,
),
enabled = enabled,
onCheckedChange = { onPermanentChanged(capability, it) },
)
}
}
SectionCard(title = stringResource(R.string.bridge_access_actions_group)) {
Text(
text = stringResource(R.string.bridge_access_actions_group_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.size(8.dp))
listOf(
BridgeCapability.CLIPBOARD_WRITE,
BridgeCapability.MEDIA_CONTROL,
BridgeCapability.COMMUNICATIONS,
BridgeCapability.OUTBOUND_SHARING,
).forEach { capability ->
val allowed = capability in policy.permanentGrants
CapabilityRow(
capability = capability,
checked = allowed,
stateLabel = stringResource(
if (allowed) R.string.bss_capability_always else R.string.bss_capability_never,
),
enabled = enabled,
onCheckedChange = { onPermanentChanged(capability, it) },
)
}
}
SectionCard(title = stringResource(R.string.bss_timed_capabilities_title)) {
val now = System.currentTimeMillis()
val activeScreenCapabilities = BridgeCapability.entries
.filter { it.timed && policy.allows(it, now) }
val hasUnlimited = activeScreenCapabilities.any(policy::isUnlimited)
Text(
text = when {
hasUnlimited -> stringResource(R.string.bss_screen_access_unlimited_desc)
activeScreenCapabilities.isNotEmpty() ->
stringResource(R.string.bss_timed_capabilities_desc, timerMinutes)
else -> stringResource(R.string.bss_screen_access_off_desc, timerMinutes)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.size(8.dp))
BridgeCapability.entries.filter { it.timed }.forEach { capability ->
val active = (policy.expiryFor(capability) ?: 0L) > now
CapabilityRow(
capability = capability,
checked = active,
stateLabel = when {
policy.isUnlimited(capability) ->
stringResource(R.string.bridge_timed_until_off)
active -> stringResource(R.string.bss_capability_timed_on)
else -> stringResource(R.string.bss_capability_timed_off)
},
enabled = enabled,
onCheckedChange = { onTimedChanged(capability, it) },
)
}
}
}
@Composable
private fun CapabilityRow(
capability: BridgeCapability,
checked: Boolean,
stateLabel: String,
enabled: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f).padding(vertical = 6.dp)) {
Text(
text = stringResource(capability.titleResource()),
style = MaterialTheme.typography.bodyLarge,
)
Text(
text = stateLabel,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = checked,
enabled = enabled,
onCheckedChange = onCheckedChange,
)
}
}
private fun BridgeCapability.titleResource(): Int = when (this) {
BridgeCapability.DEVICE_INFO -> R.string.bss_capability_device_info
BridgeCapability.CONTACTS_READ -> R.string.bss_capability_contacts
BridgeCapability.LOCATION_READ -> R.string.bss_capability_location
BridgeCapability.CLIPBOARD_READ -> R.string.bss_capability_clipboard_read
BridgeCapability.CLIPBOARD_WRITE -> R.string.bss_capability_clipboard_write
BridgeCapability.MEDIA_CONTROL -> R.string.bss_capability_media
BridgeCapability.COMMUNICATIONS -> R.string.bss_capability_communications
BridgeCapability.OUTBOUND_SHARING -> R.string.bss_capability_sharing
BridgeCapability.SCREEN_INSPECTION -> R.string.bss_capability_screen_inspection
BridgeCapability.SCREEN_CONTROL -> R.string.bss_capability_screen_control
}
@Composable
private fun SectionCard(title: String, content: @Composable () -> Unit) {
Card(
@@ -44,6 +44,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -61,12 +62,23 @@ import androidx.lifecycle.viewmodel.compose.viewModel
// === PHASE3-safety-rails: safety summary card ===
import com.hermesandroid.relay.bridge.BridgeSafetyManager
import com.hermesandroid.relay.data.BridgeSafetySettings
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
import com.hermesandroid.relay.ui.components.BridgeSafetySummaryCard
// === END PHASE3-safety-rails ===
import com.hermesandroid.relay.ui.LocalSnackbarHost
import com.hermesandroid.relay.ui.components.BridgeActivityLog
import com.hermesandroid.relay.ui.components.BridgeMasterToggle
import com.hermesandroid.relay.ui.components.BridgePermissionChecklist
import com.hermesandroid.relay.ui.components.BridgeAccessPreset
import com.hermesandroid.relay.ui.components.BridgeAccessSetupSheet
import com.hermesandroid.relay.ui.components.BridgeAgentAccessCard
import com.hermesandroid.relay.ui.components.BridgeAndroidAccessSummaryCard
import com.hermesandroid.relay.ui.components.BridgeTimedAccessSheet
import com.hermesandroid.relay.ui.components.BridgeSelectedAndroidAccessCard
import com.hermesandroid.relay.ui.components.READ_CONFIRMED_BRIDGE_CAPABILITIES
import com.hermesandroid.relay.ui.components.READ_ONLY_BRIDGE_CAPABILITIES
import com.hermesandroid.relay.ui.components.activeTimedCapabilities
import com.hermesandroid.relay.ui.components.bridgeAndroidAccessSummary
import com.hermesandroid.relay.ui.components.RelayChromeIconButton
import com.hermesandroid.relay.ui.components.RelayHeroPanel
import com.hermesandroid.relay.ui.components.RelayReturnStrip
@@ -84,13 +96,15 @@ import kotlinx.coroutines.launch
* Bridge tab — phase 3 Wave 1 rewrite (Agent bridge-ui, `bridge-screen-ui`).
*
* Replaces the Phase 0 "Coming Soon" placeholder with the real control
* surface described in `Plans/Phase 3 — Bridge Channel.md` §5. Four stacked
* cards in a verticalScroll column:
* surface described in `Plans/Phase 3 — Bridge Channel.md` §5. The main page
* is a summary-first cockpit with complete drill-downs:
*
* 1. [BridgeMasterToggle] — "Allow Agent Control" + live status
* 2. [BridgePermissionChecklist] — accessibility / capture / overlay / notif
* 3. [BridgeActivityLog] — scrollable recent-command history
* 4. Safety placeholder — stub owned by Agent safety-rails in Wave 2
* 1. [BridgeMasterToggle] — global kill switch + live device status
* 2. [BridgeAgentAccessCard] — permanent and screen-access policy posture
* 3. Unattended access — single authoritative sideload control
* 4. Android readiness summary — selected requirements + expandable full matrix
* 5. Advanced safety controls — complete power-user controls
* 6. [BridgeActivityLog] — scrollable recent-command history
*
* State comes from [BridgeViewModel] which in turn reads from the
* [com.hermesandroid.relay.data.BridgePreferencesRepository] DataStore for
@@ -151,6 +165,9 @@ fun BridgeScreen(
// === END PHASE3-safety-rails-followup ===
val context = LocalContext.current
val accessScope = androidx.compose.runtime.rememberCoroutineScope()
val accessSavedMessage = stringResource(R.string.bridge_access_saved_review_android)
val timedAccessEndedMessage = stringResource(R.string.bridge_timed_ended_snackbar)
// Result callback used by every runtime-permission launcher on this screen.
// If the user has permanently denied the permission (two declines on
@@ -197,6 +214,63 @@ fun BridgeScreen(
val trustedVerbs by (safetyManager?.trustedDestructiveVerbs
?: remember { kotlinx.coroutines.flow.MutableStateFlow<Set<String>>(emptySet()) })
.collectAsState()
val activeConnectionId by (connectionViewModel?.activeConnectionId
?: remember { kotlinx.coroutines.flow.MutableStateFlow<String?>(null) })
.collectAsState()
val activeCapabilityPolicy by (safetyManager?.activeCapabilityPolicy
?: remember { kotlinx.coroutines.flow.MutableStateFlow(BridgeCapabilityPolicy()) })
.collectAsState()
val screenControlAvailable = activeCapabilityPolicy.allows(
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL,
System.currentTimeMillis(),
)
val screenControlUnlimited = activeCapabilityPolicy.isUnlimited(
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL,
)
val screenAccessActive = activeCapabilityPolicy.activeTimedCapabilities(
System.currentTimeMillis(),
).isNotEmpty()
val anyScreenAccessUnlimited = activeCapabilityPolicy.activeTimedCapabilities(
System.currentTimeMillis(),
).any(activeCapabilityPolicy::isUnlimited)
val overlayRequired = screenControlAvailable ||
com.hermesandroid.relay.bridge.BridgeCapability.COMMUNICATIONS in
activeCapabilityPolicy.permanentGrants ||
com.hermesandroid.relay.bridge.BridgeCapability.OUTBOUND_SHARING in
activeCapabilityPolicy.permanentGrants
var nowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }
if (autoDisableAtMs != null) {
LaunchedEffect(autoDisableAtMs) {
while (true) {
nowMs = System.currentTimeMillis()
kotlinx.coroutines.delay(1_000L)
}
}
}
val androidAccessSummary = bridgeAndroidAccessSummary(
policy = activeCapabilityPolicy,
status = permissionStatus,
nowMs = nowMs,
)
var permissionsExpanded by remember { mutableStateOf(false) }
var showSetupSheet by remember { mutableStateOf(false) }
var selectedPreset by remember { mutableStateOf(BridgeAccessPreset.READ_ONLY) }
var showTimedSheet by remember { mutableStateOf(false) }
var timedInspect by remember { mutableStateOf(true) }
var timedControl by remember { mutableStateOf(true) }
var timedMinutes by remember { mutableStateOf(safetySettings.autoDisableMinutes) }
var timedUnlimited by remember { mutableStateOf(false) }
val timedCurrentlyActive = activeCapabilityPolicy.activeTimedCapabilities(nowMs).isNotEmpty()
fun openTimedSheet() {
val current = activeCapabilityPolicy.activeTimedCapabilities(nowMs)
timedInspect = if (current.isEmpty()) true else
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_INSPECTION in current
timedControl = if (current.isEmpty()) true else
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL in current
timedMinutes = safetySettings.autoDisableMinutes
timedUnlimited = current.any(activeCapabilityPolicy::isUnlimited)
showTimedSheet = true
}
// === END PHASE3-safety-rails ===
// Re-run permission + system-status probes whenever the screen resumes.
@@ -328,6 +402,7 @@ fun BridgeScreen(
// needed and the nag would confuse users + reviewers.
if (BuildFlavor.isSideload &&
masterToggle &&
overlayRequired &&
!permissionStatus.overlayPermitted
) {
OverlayPermissionNagCard(
@@ -397,58 +472,20 @@ fun BridgeScreen(
stringResource(R.string.bridge_enable_bridge_mode),
)
// 2. Permissions — prerequisites come before advanced features.
BridgePermissionChecklist(
status = permissionStatus,
// === PHASE3-safety-rails-followup: in-app permission Test handlers ===
onTestAccessibility = { viewModel.testAccessibilityService() },
onTestScreenCapture = { viewModel.testScreenCapture() },
onTestOverlay = { viewModel.testOverlayPermission() },
// === END PHASE3-safety-rails-followup ===
// === PHASE3-bridge-ui-followup: extended interactions ===
onRequestScreenCapture = { viewModel.requestScreenCapture() },
onTestNotificationListener = { viewModel.testNotificationListener() },
// === END PHASE3-bridge-ui-followup ===
onRequestNotifications = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// Same "tap always goes to Settings" treatment as the
// other runtime-permission rows. The master-toggle
// auto-request path (BridgeMasterToggle onToggle) still
// uses the launcher directly since that's a programmatic
// flow where a dialog is appropriate.
{ openAppDetailsSettings(context) }
} else null,
// === v0.4.1 polish: runtime-permission row taps go to Settings ====
// Earlier iteration tried launcher.launch(permission) with a
// post-denial fallback to app-details Settings. That
// fallback depended on (context as? Activity) succeeding
// which quietly returned null in the Compose context chain
// — so taps after a permanent denial were a silent no-op.
// Simpler + matches user expectation: tap ALWAYS opens the
// app-details Settings page. Parity with Accessibility /
// Notification Listener / Overlay rows which also open
// Settings unconditionally. First-time grant is one extra
// tap vs. a system dialog — acceptable trade-off for
// "tap always does something visible".
onRequestMicrophone = { openAppDetailsSettings(context) },
onRequestCamera = { openAppDetailsSettings(context) },
onRequestContacts = { openAppDetailsSettings(context) },
onRequestSms = { openAppDetailsSettings(context) },
onRequestPhone = { openAppDetailsSettings(context) },
onRequestLocation = { openAppDetailsSettings(context) },
// === END v0.4.1 polish ====
// 2. Capability policy stays visible directly under the master.
// Detailed toggles remain one tap away on the full safety screen.
BridgeAgentAccessCard(
policy = activeCapabilityPolicy,
nowMs = nowMs,
onSetUp = { showSetupSheet = true },
onManage = onNavigateToBridgeSafety,
onAllowScreen = { openTimedSheet() },
)
// 3. Advanced section — unattended access + safety. Sideload
// only — these features don't exist on googlePlay (no wake
// lock, no destructive-verb routes).
// 3. One authoritative unattended control, kept beside the
// access policy it extends. Do not duplicate this state inside
// Agent access or Advanced: one switch owns one mode.
if (BuildFlavor.isSideload) {
AdvancedSectionHeader()
// 4. Unattended access — a SUB-FEATURE of the master
// toggle. Gated: Switch is non-interactive when the
// master toggle is off so users can't flip it and
// observe nothing happening (the acquire path
// short-circuits when master is off anyway).
UnattendedAccessRow(
enabled = unattendedEnabled,
warningSeen = unattendedWarningSeen,
@@ -456,15 +493,76 @@ fun BridgeScreen(
onToggle = { viewModel.setUnattendedAccessEnabled(it) },
onWarningSeen = { viewModel.markUnattendedWarningSeen() },
masterEnabled = masterToggle,
screenControlAvailable = screenControlAvailable,
screenAccessUnlimited = screenControlUnlimited,
)
}
// 5. Safety summary — auto-disable, destructive verbs,
// blocklist. Belongs adjacent to unattended because
// they share the "advanced / opt-in / sideload-only"
// mental model.
// 4. Android permission state is summarized against the selected
// policy. Expanding preserves the complete existing matrix and
// every Settings/Test action—no power-user surface is removed.
BridgeAndroidAccessSummaryCard(
summary = androidAccessSummary,
expanded = permissionsExpanded,
onToggle = { permissionsExpanded = !permissionsExpanded },
)
if (permissionsExpanded) {
BridgeSelectedAndroidAccessCard(
summary = androidAccessSummary,
onOpenAccessibility = {
runCatching {
context.startActivity(
Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
},
)
}
},
onOpenAppSettings = { openAppDetailsSettings(context) },
onOpenOverlay = {
runCatching {
context.startActivity(
Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:${context.packageName}"),
).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) },
)
}
},
)
BridgePermissionChecklist(
status = permissionStatus,
onTestAccessibility = { viewModel.testAccessibilityService() },
onTestScreenCapture = { viewModel.testScreenCapture() },
onTestOverlay = { viewModel.testOverlayPermission() },
onRequestScreenCapture = { viewModel.requestScreenCapture() },
onTestNotificationListener = { viewModel.testNotificationListener() },
onRequestNotifications = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
) {
{ openAppDetailsSettings(context) }
} else null,
onRequestMicrophone = { openAppDetailsSettings(context) },
onRequestCamera = { openAppDetailsSettings(context) },
onRequestContacts = { openAppDetailsSettings(context) },
onRequestSms = { openAppDetailsSettings(context) },
onRequestPhone = { openAppDetailsSettings(context) },
onRequestLocation = { openAppDetailsSettings(context) },
)
}
// 5. Advanced safety controls. Sideload only — these features
// don't exist on googlePlay (no destructive-verb routes).
if (BuildFlavor.isSideload) {
AdvancedSectionHeader()
// Safety summary — auto-disable, destructive verbs,
// blocklist, and the complete granular editor.
BridgeSafetySummaryCard(
settings = safetySettings,
autoDisableAtMs = autoDisableAtMs,
screenAccessActive = screenAccessActive,
screenAccessUnlimited = anyScreenAccessUnlimited,
onManage = onNavigateToBridgeSafety,
)
@@ -492,6 +590,102 @@ fun BridgeScreen(
Spacer(modifier = Modifier.height(16.dp))
}
}
if (showSetupSheet) {
BridgeAccessSetupSheet(
selected = selectedPreset,
onSelected = { selectedPreset = it },
onDismiss = { showSetupSheet = false },
onContinue = {
when (selectedPreset) {
BridgeAccessPreset.CUSTOM -> {
showSetupSheet = false
onNavigateToBridgeSafety()
}
BridgeAccessPreset.READ_ONLY,
BridgeAccessPreset.READ_CONFIRMED -> accessScope.launch {
val grants = if (selectedPreset == BridgeAccessPreset.READ_ONLY) {
READ_ONLY_BRIDGE_CAPABILITIES
} else {
READ_CONFIRMED_BRIDGE_CAPABILITIES
}
safetyManager?.replacePermanentCapabilities(activeConnectionId, grants)
showSetupSheet = false
permissionsExpanded = true
snackbarHost.showSnackbar(accessSavedMessage)
}
}
},
)
}
if (showTimedSheet) {
BridgeTimedAccessSheet(
inspectEnabled = timedInspect,
controlEnabled = timedControl,
durationMinutes = timedMinutes,
unlimited = timedUnlimited,
accessibilityReady = permissionStatus.accessibilityServiceEnabled,
overlayReady = permissionStatus.overlayPermitted,
currentlyActive = timedCurrentlyActive,
onInspectChanged = { timedInspect = it },
onControlChanged = { timedControl = it },
onDurationChanged = { timedMinutes = it },
onUnlimitedChanged = { timedUnlimited = it },
onOpenAccessibility = {
runCatching {
context.startActivity(
Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
},
)
}
},
onOpenOverlay = {
runCatching {
context.startActivity(
Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:${context.packageName}"),
).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) },
)
}
},
onDismiss = { showTimedSheet = false },
onAllow = {
accessScope.launch {
val capabilities = buildSet {
if (timedInspect) add(
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_INSPECTION,
)
if (timedControl) add(
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL,
)
}
viewModel.setTimedAccessMinutes(timedMinutes)
safetyManager?.replaceTimedCapabilities(
activeConnectionId,
capabilities,
timedMinutes,
unlimited = timedUnlimited,
)
showTimedSheet = false
}
},
onEndNow = {
accessScope.launch {
safetyManager?.replaceTimedCapabilities(
activeConnectionId,
emptySet(),
timedMinutes,
)
viewModel.setUnattendedAccessEnabled(false)
showTimedSheet = false
snackbarHost.showSnackbar(timedAccessEndedMessage)
}
},
)
}
}
/**
File diff suppressed because it is too large Load Diff
@@ -444,6 +444,34 @@ fun ChatSettingsScreen(
HorizontalDivider()
val convertLargePastesToAttachments by
connectionViewModel.convertLargePastesToAttachments.collectAsState()
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.chat_settings_large_pastes),
style = MaterialTheme.typography.bodyMedium,
)
Text(
text = stringResource(R.string.chat_settings_large_pastes_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = convertLargePastesToAttachments,
onCheckedChange = {
connectionViewModel.setConvertLargePastesToAttachments(it)
},
)
}
HorizontalDivider()
val physicalKeyboardEnterBehavior by
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -76,6 +76,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PrimaryScrollableTabRow
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
@@ -107,15 +108,20 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.GatewayProfileAuthChoice
import com.hermesandroid.relay.data.GatewayProfileCreateRequest
import com.hermesandroid.relay.data.GatewayProfileManagementUnsupportedException
import com.hermesandroid.relay.network.upstream.EncryptedDashboardCookieStore
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.DashboardCustomEndpointDraft
import com.hermesandroid.relay.network.upstream.McpOAuthFlowCoordinator
import com.hermesandroid.relay.network.upstream.DashboardCookieStore
import com.hermesandroid.relay.network.upstream.CronCreationDraft
import com.hermesandroid.relay.network.upstream.DashboardAuthProvider
import com.hermesandroid.relay.network.upstream.DashboardAuthSession
import com.hermesandroid.relay.network.upstream.DashboardComponentHealthRollup
import com.hermesandroid.relay.network.upstream.DashboardStatus
import com.hermesandroid.relay.network.upstream.parseFiniteRepeat
import com.hermesandroid.relay.network.upstream.importDashboardCookieHeader
import com.hermesandroid.relay.ui.components.RelayChromeIconButton
import com.hermesandroid.relay.ui.components.RelayMetricCard
@@ -388,6 +394,7 @@ private fun dashboardPayloadKey(
/** Section-level (not per-item) affordances rendered at the top of a tab. */
private enum class DashboardSectionAction {
ChangeMainModel,
CreateCron,
CreateProfile,
BrowseSkillsHub,
UpdateSkillsHub,
@@ -443,6 +450,17 @@ private data class PendingDashboardAction(
val action: DashboardItemAction,
)
internal fun shouldUseLegacyDashboardProfileCreate(
request: GatewayProfileCreateRequest,
failure: Throwable,
explicitlyAllowed: Boolean,
): Boolean =
explicitlyAllowed && failure is GatewayProfileManagementUnsupportedException &&
request.authChoice == GatewayProfileAuthChoice.Shared &&
(request.cloneFrom == null || request.cloneFrom == "default") &&
!request.cloneAll && !request.noSkills && request.soul == null &&
request.model == null && request.provider == null
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DashboardManagementScreen(
@@ -485,6 +503,7 @@ fun DashboardManagementScreen(
var inputAction by remember { mutableStateOf<PendingDashboardAction?>(null) }
var modelPickerTarget by remember { mutableStateOf<ModelPickerTarget?>(null) }
var showCreateProfile by remember { mutableStateOf(false) }
var showCreateCron by remember { mutableStateOf(false) }
var expensiveModelConfirm by remember { mutableStateOf<ExpensiveModelConfirm?>(null) }
var showSkillsHub by remember { mutableStateOf(false) }
var soulEditor by remember { mutableStateOf<SoulEditorState?>(null) }
@@ -882,35 +901,83 @@ fun DashboardManagementScreen(
}
fun submitCreateProfile(
name: String,
description: String,
cloneFromDefault: Boolean,
request: GatewayProfileCreateRequest,
mcpServers: List<String>,
allowLegacyDashboard: Boolean,
) {
if (dashboardUrl.isBlank() || actionInFlight) return
if (actionInFlight) return
val actionPayloadKey = payloadKey
actionInFlight = true
actionMessage = null
scope.launch {
val result = try {
withDashboardClient(clientFactory) { client ->
client.createProfile(
name = name,
cloneFromDefault = cloneFromDefault,
description = description.takeIf { it.isNotBlank() },
mcpServers = mcpServers,
val gatewayClient = connectionViewModel.activeGatewayChatClient()
val gatewayResult = gatewayClient
?.createProfile(request)
?: Result.failure(GatewayProfileManagementUnsupportedException("profiles.create"))
val result: Result<String> = gatewayResult.fold(
onSuccess = { created ->
val partial = created.partialMessages(request).toMutableList()
if (mcpServers.isNotEmpty()) {
val configured = gatewayClient
?.describeProfile(created.name)
?.mapCatching {
gatewayClient.configureProfile(
created.name,
com.hermesandroid.relay.data.GatewayProfilePatch(
enabledMcpServers = mcpServers,
),
).getOrThrow()
}
if (
configured == null || configured.isFailure ||
com.hermesandroid.relay.data.GatewayProfileSection.McpServers in
configured.getOrThrow().failed
) {
partial += context.getString(R.string.dashboard_profile_mcp_partial)
}
}
Result.success(
if (partial.isEmpty()) {
context.getString(R.string.dashboard_profile_created, created.name)
} else {
context.getString(
R.string.dashboard_profile_created_partial,
created.name,
partial.joinToString("; "),
)
},
)
},
onFailure = { gatewayFailure ->
// The authenticated Dashboard route remains the compatibility
// create surface for old hosts, but only for the legacy shared
// default. Never erase an explicit isolation choice.
if (shouldUseLegacyDashboardProfileCreate(request, gatewayFailure, allowLegacyDashboard)) {
try {
withDashboardClient(clientFactory) { client ->
client.createProfile(
name = request.name,
cloneFromDefault = request.cloneFrom != null,
description = request.description,
mcpServers = mcpServers,
)
}.map { context.getString(R.string.dashboard_profile_created_legacy, request.name) }
} catch (e: Exception) {
Result.failure(e)
}
} else {
Result.failure(gatewayFailure)
}
}
} catch (e: Exception) {
Result.failure(e)
}
)
actionMessage = result.fold(
onSuccess = {
onSuccess = { message ->
showCreateProfile = false
refreshingPayloads[actionPayloadKey] = true
forceReloadKey = actionPayloadKey
reloadNonce += 1
context.getString(R.string.dashboard_profile_created, name)
connectionViewModel.refreshGatewayProfiles()
message
},
onFailure = { err -> err.message ?: context.getString(R.string.dashboard_profile_create_failed) },
)
@@ -918,6 +985,29 @@ fun DashboardManagementScreen(
}
}
fun submitCreateCron(draft: CronCreationDraft) {
if (actionInFlight) return
val actionPayloadKey = payloadKey
actionInFlight = true
actionMessage = null
scope.launch {
val result = connectionViewModel.activeGatewayChatClient()
?.createCronJob(draft.copy(profile = effectiveProfileName))
?: Result.failure(IllegalStateException(context.getString(R.string.dashboard_cron_gateway_required)))
actionMessage = result.fold(
onSuccess = {
showCreateCron = false
refreshingPayloads[actionPayloadKey] = true
forceReloadKey = actionPayloadKey
reloadNonce += 1
context.getString(R.string.dashboard_cron_created, draft.name.trim())
},
onFailure = { err -> err.message ?: context.getString(R.string.dashboard_cron_create_failed) },
)
actionInFlight = false
}
}
fun runServerBackup() {
if (dashboardUrl.isBlank() || actionInFlight) return
actionInFlight = true
@@ -1146,11 +1236,17 @@ fun DashboardManagementScreen(
var newProfileDescription by remember { mutableStateOf("") }
var newProfileMcpServers by remember { mutableStateOf("") }
var cloneFromDefault by remember { mutableStateOf(true) }
var noSkills by remember { mutableStateOf(false) }
var authChoice by remember { mutableStateOf(GatewayProfileAuthChoice.Shared) }
var allowLegacyDashboard by remember { mutableStateOf(false) }
AlertDialog(
onDismissRequest = { showCreateProfile = false },
title = { Text(stringResource(R.string.dashboard_new_profile_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Column(
modifier = Modifier.heightIn(max = 560.dp).verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(
value = newProfileName,
onValueChange = { newProfileName = it },
@@ -1177,28 +1273,97 @@ fun DashboardManagementScreen(
) {
Checkbox(
checked = cloneFromDefault,
onCheckedChange = { cloneFromDefault = it },
onCheckedChange = {
cloneFromDefault = it
if (it) noSkills = false
},
)
Text(
text = stringResource(R.string.dashboard_clone_from_default),
style = MaterialTheme.typography.bodySmall,
)
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = noSkills,
enabled = !cloneFromDefault,
onCheckedChange = { noSkills = it },
)
Text(
text = stringResource(R.string.dashboard_profile_no_skills),
style = MaterialTheme.typography.bodySmall,
)
}
Text(
text = stringResource(R.string.dashboard_profile_auth_title),
style = MaterialTheme.typography.labelLarge,
)
listOf(
GatewayProfileAuthChoice.Shared to R.string.dashboard_profile_auth_shared,
GatewayProfileAuthChoice.Copied to R.string.dashboard_profile_auth_copied,
GatewayProfileAuthChoice.Isolated to R.string.dashboard_profile_auth_isolated,
).forEach { (choice, label) ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable {
authChoice = choice
if (choice != GatewayProfileAuthChoice.Shared) allowLegacyDashboard = false
},
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = authChoice == choice,
onClick = {
authChoice = choice
if (choice != GatewayProfileAuthChoice.Shared) allowLegacyDashboard = false
},
)
Text(text = stringResource(label), style = MaterialTheme.typography.bodySmall)
}
}
Text(
text = stringResource(R.string.dashboard_profile_auth_help),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = allowLegacyDashboard,
enabled = authChoice == GatewayProfileAuthChoice.Shared,
onCheckedChange = { allowLegacyDashboard = it },
)
Text(
text = stringResource(R.string.dashboard_profile_allow_legacy),
style = MaterialTheme.typography.bodySmall,
)
}
}
},
confirmButton = {
TextButton(
onClick = {
submitCreateProfile(
name = newProfileName.trim(),
description = newProfileDescription.trim(),
cloneFromDefault = cloneFromDefault,
request = GatewayProfileCreateRequest(
name = newProfileName.trim(),
description = newProfileDescription.trim().takeIf(String::isNotEmpty),
cloneFrom = "default".takeIf { cloneFromDefault },
noSkills = noSkills,
authChoice = authChoice,
),
mcpServers = newProfileMcpServers
.split(',', '\n')
.map(String::trim)
.filter(String::isNotBlank)
.distinct()
.take(64),
allowLegacyDashboard = allowLegacyDashboard,
)
},
enabled = newProfileName.isNotBlank() && !actionInFlight,
@@ -1210,6 +1375,14 @@ fun DashboardManagementScreen(
)
}
if (showCreateCron) {
CronCreationDialog(
actionInFlight = actionInFlight,
onDismiss = { showCreateCron = false },
onCreate = ::submitCreateCron,
)
}
expensiveModelConfirm?.let { confirm ->
AlertDialog(
onDismissRequest = { expensiveModelConfirm = null },
@@ -1529,6 +1702,8 @@ fun DashboardManagementScreen(
when (sectionAction) {
DashboardSectionAction.ChangeMainModel ->
modelPickerTarget = ModelPickerTarget.Main
DashboardSectionAction.CreateCron ->
showCreateCron = true
DashboardSectionAction.CreateProfile ->
showCreateProfile = true
DashboardSectionAction.BrowseSkillsHub ->
@@ -2587,6 +2762,7 @@ private fun LoadedBody(
// Pre-resolve action labels outside LazyColumn's non-Composable lambda
val actionLabelChangeMainModel = stringResource(R.string.dashboard_section_action_change_main_model)
val actionLabelNewProfile = stringResource(R.string.dashboard_section_action_new_profile)
val actionLabelNewSchedule = stringResource(R.string.dashboard_section_action_new_schedule)
val actionLabelBrowseHub = stringResource(R.string.dashboard_section_action_browse_hub)
val actionLabelUpdateInstalled = stringResource(R.string.dashboard_section_action_update_installed)
val actionLabelAddEndpoint = stringResource(R.string.dashboard_custom_endpoint_add)
@@ -2614,6 +2790,9 @@ private fun LoadedBody(
DashboardManagementSection.Profiles -> listOf(
DashboardSectionAction.CreateProfile to actionLabelNewProfile,
)
DashboardManagementSection.Cron -> listOf(
DashboardSectionAction.CreateCron to actionLabelNewSchedule,
)
DashboardManagementSection.Skills -> listOf(
DashboardSectionAction.BrowseSkillsHub to actionLabelBrowseHub,
DashboardSectionAction.UpdateSkillsHub to actionLabelUpdateInstalled,
@@ -3176,6 +3355,82 @@ private fun ActionMessageCard(message: String) {
}
}
@Composable
private fun CronCreationDialog(
actionInFlight: Boolean,
onDismiss: () -> Unit,
onCreate: (CronCreationDraft) -> Unit,
) {
var name by remember { mutableStateOf("") }
var schedule by remember { mutableStateOf("") }
var prompt by remember { mutableStateOf("") }
var repeatText by remember { mutableStateOf("") }
val repeat = parseFiniteRepeat(repeatText)
val draft = repeat.getOrNull()?.let {
CronCreationDraft(name = name, schedule = schedule, prompt = prompt, repeat = it)
} ?: if (repeat.isSuccess) {
CronCreationDraft(name = name, schedule = schedule, prompt = prompt)
} else {
null
}
val canCreate = draft?.validated()?.isSuccess == true && !actionInFlight
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.dashboard_cron_create_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.dashboard_cron_name)) },
singleLine = true,
)
OutlinedTextField(
value = schedule,
onValueChange = { schedule = it },
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.dashboard_cron_schedule)) },
supportingText = { Text(stringResource(R.string.dashboard_cron_schedule_hint)) },
singleLine = true,
)
OutlinedTextField(
value = prompt,
onValueChange = { prompt = it },
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.dashboard_cron_prompt)) },
minLines = 3,
maxLines = 6,
)
OutlinedTextField(
value = repeatText,
onValueChange = { repeatText = it.take(4) },
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.dashboard_cron_repeat)) },
supportingText = {
Text(
repeat.exceptionOrNull()?.message
?: stringResource(R.string.dashboard_cron_repeat_help),
)
},
isError = repeat.isFailure,
singleLine = true,
)
}
},
confirmButton = {
TextButton(
onClick = { draft?.let(onCreate) },
enabled = canCreate,
) { Text(stringResource(R.string.dashboard_create)) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dashboard_cancel)) }
},
)
}
@Composable
private fun DashboardDetailDialog(
detail: DashboardDetailResult,
@@ -264,14 +264,37 @@ fun DashboardSignInScreen(
operation = "dashboard_native_pkce",
)
Log.w(NATIVE_DASHBOARD_AUTH_LOG_TAG, failureDetail)
actionMessage = nativeDashboardSignInActionMessage(
failureStage = failureStage,
errorMessage = error.message,
fallbackMessage = resources.getString(R.string.dashboard_signin_failed),
transportRetryMessage = resources.getString(
actionMessage = when (nativeDashboardSignInMessageKind(failureStage)) {
NativeDashboardSignInMessageKind.CallbackRejected -> resources.getString(
R.string.dashboard_native_signin_callback_rejected,
)
NativeDashboardSignInMessageKind.CodeRejected -> resources.getString(
R.string.dashboard_native_signin_code_rejected,
)
NativeDashboardSignInMessageKind.GatewayRejected -> resources.getString(
R.string.dashboard_native_signin_gateway_rejected,
)
NativeDashboardSignInMessageKind.RateLimited -> resources.getString(
R.string.dashboard_native_signin_rate_limited,
)
NativeDashboardSignInMessageKind.GatewayUnavailable -> resources.getString(
R.string.dashboard_native_signin_gateway_unavailable,
)
NativeDashboardSignInMessageKind.ResponseUnsupported -> resources.getString(
R.string.dashboard_native_signin_response_unsupported,
)
NativeDashboardSignInMessageKind.AttemptInactive -> resources.getString(
R.string.dashboard_native_signin_attempt_inactive,
)
NativeDashboardSignInMessageKind.SecureStorage -> resources.getString(
R.string.dashboard_native_signin_storage_failed,
)
NativeDashboardSignInMessageKind.Transport -> resources.getString(
R.string.dashboard_native_signin_transport_retry,
),
)
)
NativeDashboardSignInMessageKind.Generic -> error.message
?: resources.getString(R.string.dashboard_signin_failed)
}
actionIsError = true
} finally {
actionInFlight = false
@@ -362,17 +385,34 @@ fun DashboardSignInScreen(
}
}
internal fun nativeDashboardSignInActionMessage(
failureStage: String,
errorMessage: String?,
fallbackMessage: String,
transportRetryMessage: String,
): String = if (failureStage.startsWith("token_transport")) {
transportRetryMessage
} else {
errorMessage ?: fallbackMessage
internal enum class NativeDashboardSignInMessageKind {
CallbackRejected,
CodeRejected,
GatewayRejected,
RateLimited,
GatewayUnavailable,
ResponseUnsupported,
AttemptInactive,
SecureStorage,
Transport,
Generic,
}
internal fun nativeDashboardSignInMessageKind(failureStage: String): NativeDashboardSignInMessageKind =
when {
failureStage == "callback_error" -> NativeDashboardSignInMessageKind.CallbackRejected
failureStage == "token_http_400" -> NativeDashboardSignInMessageKind.CodeRejected
failureStage == "token_http_401" || failureStage == "token_http_403" ->
NativeDashboardSignInMessageKind.GatewayRejected
failureStage == "token_http_429" -> NativeDashboardSignInMessageKind.RateLimited
failureStage.startsWith("token_http_5") -> NativeDashboardSignInMessageKind.GatewayUnavailable
failureStage == "token_shape" -> NativeDashboardSignInMessageKind.ResponseUnsupported
failureStage == "inactive_generation" -> NativeDashboardSignInMessageKind.AttemptInactive
failureStage == "token_store" -> NativeDashboardSignInMessageKind.SecureStorage
failureStage.startsWith("token_transport") -> NativeDashboardSignInMessageKind.Transport
else -> NativeDashboardSignInMessageKind.Generic
}
@Composable
private fun DashboardAuthenticationComplete(onContinue: () -> Unit) {
Column(
@@ -127,6 +127,7 @@ fun ProfileInspectorScreen(
val skillsState by viewModel.skillsState.collectAsState()
val source by viewModel.source.collectAsState()
val gatewayDescription by viewModel.gatewayDescription.collectAsState()
val gatewayWritable by viewModel.gatewayWritable.collectAsState()
// Lazy first-load on screen entry. Keyed on the profile name so a
// re-entry for a different profile (unlikely but possible via deep
@@ -248,7 +249,7 @@ fun ProfileInspectorScreen(
InspectorSection.Config -> ConfigPane(
state = configState,
onRetry = { viewModel.refreshSection(InspectorSection.Config) },
gatewayEditable = source == ProfileInspectorSource.Gateway,
gatewayEditable = source == ProfileInspectorSource.Gateway && gatewayWritable,
editing = viewModel.configEditing.collectAsState().value,
descriptionDraft = viewModel.configDescriptionDraft.collectAsState().value,
providerDraft = viewModel.configProviderDraft.collectAsState().value,
@@ -273,6 +274,7 @@ fun ProfileInspectorScreen(
onDraftChange = { viewModel.updateSoulDraft(it) },
onSave = { viewModel.saveSoulEdit() },
onCancelEdit = { viewModel.cancelSoulEdit() },
editable = source != ProfileInspectorSource.Gateway || gatewayWritable,
)
InspectorSection.Memory -> MemoryPane(
state = memoryState,
@@ -298,7 +300,7 @@ fun ProfileInspectorScreen(
onToggleSkill = { name, enabled ->
viewModel.toggleSkill(name, enabled)
},
gatewayNative = source == ProfileInspectorSource.Gateway,
gatewayNative = source == ProfileInspectorSource.Gateway && gatewayWritable,
skillDrafts = viewModel.skillDrafts.collectAsState().value,
toolsets = gatewayDescription?.toolsets.orEmpty(),
toolsetDrafts = viewModel.toolsetDrafts.collectAsState().value,
@@ -835,6 +837,7 @@ private fun SoulPane(
onDraftChange: (String) -> Unit,
onSave: () -> Unit,
onCancelEdit: () -> Unit,
editable: Boolean,
) {
PaneShell(state = state, onRetry = onRetry) { response ->
Column(
@@ -886,11 +889,13 @@ private fun SoulPane(
},
)
}
IconButton(onClick = onBeginEdit) {
Icon(
imageVector = Icons.Filled.Edit,
contentDescription = stringResource(R.string.profile_inspector_edit_soul),
)
if (editable) {
IconButton(onClick = onBeginEdit) {
Icon(
imageVector = Icons.Filled.Edit,
contentDescription = stringResource(R.string.profile_inspector_edit_soul),
)
}
}
} else {
IconButton(
@@ -910,14 +915,14 @@ private fun SoulPane(
MonospaceEditor(
content = draft,
onContentChange = onDraftChange,
enabled = !saving,
enabled = editable && !saving,
modifier = Modifier
.fillMaxWidth()
.weight(1f),
)
EditorBottomBar(
saving = saving,
canSave = true,
canSave = editable,
onSave = onSave,
onCancel = onCancelEdit,
)
@@ -0,0 +1,51 @@
package com.hermesandroid.relay.ui.theme
import androidx.compose.ui.graphics.Color
import java.util.Locale
import kotlin.math.abs
import kotlin.math.roundToInt
private const val PROFILE_SATURATION = 0.68f
private const val PROFILE_LIGHTNESS = 0.58f
/** The same evenly-spaced 12-hue picker model used by Hermes Desktop. */
val ProfileAccentSwatches: List<String> = (0 until 12).map { index ->
hslColor(index * 30f, PROFILE_SATURATION, PROFILE_LIGHTNESS).toRgbHex()
}
/** Desktop-compatible deterministic profile identity color; default remains neutral. */
fun resolveProfileAccent(name: String?, overrides: Map<String, String>): Color? {
val key = name?.trim().orEmpty()
if (key.isBlank() || key.equals("default", ignoreCase = true)) return null
return accentColor(overrides[key]) ?: deterministicProfileAccent(key)
}
internal fun deterministicProfileAccent(name: String): Color {
var hash = 0u
name.forEach { character -> hash = hash * 31u + character.code.toUInt() }
return hslColor((hash % 360u).toFloat(), PROFILE_SATURATION, PROFILE_LIGHTNESS)
}
private fun hslColor(hue: Float, saturation: Float, lightness: Float): Color {
val chroma = (1f - abs(2f * lightness - 1f)) * saturation
val section = (hue / 60f) % 6f
val x = chroma * (1f - abs(section % 2f - 1f))
val (red, green, blue) = when {
section < 1f -> Triple(chroma, x, 0f)
section < 2f -> Triple(x, chroma, 0f)
section < 3f -> Triple(0f, chroma, x)
section < 4f -> Triple(0f, x, chroma)
section < 5f -> Triple(x, 0f, chroma)
else -> Triple(chroma, 0f, x)
}
val match = lightness - chroma / 2f
return Color(red + match, green + match, blue + match)
}
private fun Color.toRgbHex(): String = String.format(
Locale.ROOT,
"#%02X%02X%02X",
(red * 255f).roundToInt(),
(green * 255f).roundToInt(),
(blue * 255f).roundToInt(),
)
@@ -0,0 +1,46 @@
package com.hermesandroid.relay.util
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.Base64
internal data class BoundedBase64Payload(
val base64: String,
val sizeBytes: Long,
)
internal class AttachmentTooLargeException(
val limitBytes: Long,
) : Exception("attachment exceeds the $limitBytes byte limit")
/**
* Base64-encode [input] while enforcing [limitBytes] before an oversized body
* is buffered. The picker previously called `readBytes()` and checked the cap
* afterwards, allowing a content provider to exhaust the app heap first.
*/
internal fun readBase64Bounded(
input: InputStream,
limitBytes: Long,
): BoundedBase64Payload {
require(limitBytes >= 0L) { "limitBytes must be non-negative" }
val initialCapacity = minOf(limitBytes, 64L * 1024L).toInt()
val encoded = ByteArrayOutputStream(initialCapacity)
var count = 0L
Base64.getEncoder().wrap(encoded).use { base64Out ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val remaining = limitBytes - count
val requested = minOf(buffer.size.toLong(), remaining + 1L).toInt()
val read = input.read(buffer, 0, requested)
if (read < 0) break
if (read == 0) continue
if (read.toLong() > remaining) throw AttachmentTooLargeException(limitBytes)
base64Out.write(buffer, 0, read)
count += read
}
}
return BoundedBase64Payload(
base64 = encoded.toString(Charsets.US_ASCII.name()),
sizeBytes = count,
)
}
@@ -75,7 +75,7 @@ import kotlinx.coroutines.launch
*
* 4. **`masterToggle`** write path — flipping the master switch persists via
* [BridgePreferencesRepository.setMasterEnabled]. accessibility's service reads the
* same DataStore key (`bridge_master_enabled`) and treats it as the
* same DataStore key (`bridge_master_enabled_v2`) and treats it as the
* runtime disable switch — when false, the service should ignore all
* incoming `bridge.command` envelopes. bridge-ui does not wire the service lifecycle
* to this toggle; that's accessibility's call.
@@ -230,20 +230,24 @@ class BridgeViewModel(application: Application) : AndroidViewModel(application)
// === END PHASE3-bridge-ui-followup ===
// === PHASE3-safety-rails: foreground service lifecycle ===
// Start/stop BridgeForegroundService based on the master toggle.
// distinctUntilChanged prevents re-firing the startForegroundService
// intent on every DataStore tick. Cancel the safety manager's
// auto-disable timer when the user flips the toggle off manually
// (otherwise we race a pending timer against the user).
// Start/stop BridgeForegroundService from the persisted settings Flow,
// not masterToggle's synthetic initial=false StateFlow value. Using the
// synthetic value here could revoke an unlimited lease during startup
// before DataStore reported that Master was actually persisted ON.
// distinctUntilChanged prevents duplicate service work. Cancel the safety manager's
// timed screen grants when the user flips the master off manually
// (otherwise stale authority could revive when master is re-enabled).
viewModelScope.launch {
masterToggle.collect { enabled ->
prefsRepo.settings
.map { it.masterEnabled }
.distinctUntilChanged()
.collect { enabled ->
val ctx = getApplication<Application>()
if (enabled) {
runCatching { BridgeForegroundService.start(ctx) }
BridgeSafetyManager.peek()?.rescheduleAutoDisable()
} else {
runCatching { BridgeForegroundService.stop(ctx) }
BridgeSafetyManager.peek()?.cancelAutoDisable()
BridgeSafetyManager.peek()?.revokeTimedCapabilities()
// Force the overlay chip off even if the user hasn't
// explicitly disabled it — no point showing "bridge
// active" when the toggle is off.
@@ -252,13 +256,9 @@ class BridgeViewModel(application: Application) : AndroidViewModel(application)
// drop it on toggle-off so the row goes back to red
// and the next bridge enable prompts for fresh consent.
MediaProjectionHolder.revoke()
// v0.4.1: drop the unattended-access wake lock immediately
// when the master toggle drops. The unattended toggle
// itself may still be persisted ON in DataStore — that's
// intentional, the user's "I want unattended when bridge
// is on" preference shouldn't be cleared by every bridge
// toggle cycle — but the wake lock is meaningless
// without an active bridge.
// Drop the unattended wake lock immediately. The safety
// manager also clears the persisted unattended preference,
// so re-enabling Master cannot silently revive it.
UnattendedAccessManager.release()
}
}
@@ -334,6 +334,12 @@ class BridgeViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setTimedAccessMinutes(minutes: Int) {
viewModelScope.launch {
safetyPrefsRepo.setAutoDisableMinutes(minutes)
}
}
/**
* Latch the "user has seen the warning" sentinel so the scary
* dialog never appears again after the first dismissal. Called
File diff suppressed because it is too large Load Diff
@@ -95,10 +95,12 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
import com.hermesandroid.relay.network.upstream.ActiveTurnKeepAliveRegistry
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.GatewayPetGalleryItem
import com.hermesandroid.relay.network.upstream.GatewayKeepAliveService
import com.hermesandroid.relay.network.upstream.HermesApiClient
import com.hermesandroid.relay.network.shared.RouteProbeOutcome
import com.hermesandroid.relay.network.shared.ProfileApiUrlResolver
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
import com.hermesandroid.relay.network.upstream.ServerCapabilities
import com.hermesandroid.relay.network.relay.RelayHttpClient
import com.hermesandroid.relay.network.relay.RelayUrlDeriver
@@ -156,6 +158,31 @@ internal data class RelayUiInputs(
val configured: Boolean,
)
data class HostResourcePressureStatus(
val memoryPressure: String? = null,
val memoryAvailableMb: Int? = null,
val diskPressure: String? = null,
val diskFreeMb: Int? = null,
val lastBootSuspectedOom: Boolean = false,
) {
val needsAttention: Boolean
get() = memoryPressure in setOf("elevated", "critical") ||
diskPressure in setOf("elevated", "critical") ||
lastBootSuspectedOom
val critical: Boolean
get() = memoryPressure == "critical" || diskPressure == "critical" || lastBootSuspectedOom
}
internal fun DashboardStatus.hostResourcePressure(): HostResourcePressureStatus =
HostResourcePressureStatus(
memoryPressure = memory?.pressure,
memoryAvailableMb = memory?.systemAvailableMb,
diskPressure = disk?.pressure,
diskFreeMb = disk?.freeMb,
lastBootSuspectedOom = memory?.lastBootSuspectedOom == true,
)
internal fun RelayUiInputs.requiresReconnectGrace(): Boolean =
configured &&
url.isNotBlank() &&
@@ -765,6 +792,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
},
rebuildChatApiClient = { rebuildChatApiClient() },
relayHttpClient = relayHttpClient,
gatewayClientProvider = { upstreamTransport.activeGatewayChatClient() },
)
// --- Relay connection state ---
@@ -1071,6 +1099,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
val standardVoiceAvailability: StateFlow<StandardVoiceAvailability> =
_standardVoiceAvailability.asStateFlow()
private val _hostResourcePressure = MutableStateFlow(HostResourcePressureStatus())
val hostResourcePressure: StateFlow<HostResourcePressureStatus> =
_hostResourcePressure.asStateFlow()
private val _standardAudioApiReachable = MutableStateFlow(false)
val standardAudioApiReachable: StateFlow<Boolean> = _standardAudioApiReachable.asStateFlow()
@@ -1571,11 +1603,30 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
suspend fun listAllProfileSessions(limit: Int = 200): Result<List<SessionItem>>? =
profileController.listAllProfileSessions(limit)
suspend fun deleteSession(profileName: String, sessionId: String): Boolean =
profileController.deleteSession(profileName, sessionId)
suspend fun renameSession(profileName: String, sessionId: String, title: String): Boolean =
profileController.renameSession(profileName, sessionId, title)
suspend fun setSessionPinned(profileName: String, sessionId: String, pinned: Boolean): Boolean =
profileController.setSessionPinned(profileName, sessionId, pinned)
suspend fun setSessionArchived(profileName: String, sessionId: String, archived: Boolean): Boolean =
profileController.setSessionArchived(profileName, sessionId, archived)
suspend fun loadProfileScopedMessages(
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
suspend fun loadProfileScopedMessages(
profileName: String?,
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? =
profileController.loadProfileScopedMessages(profileName, sessionId, mode)
/**
* Delete a session scoped to the ACTIVE PROFILE via the dashboard
* `DELETE /api/sessions/{id}?profile=` surface — the write twin of
@@ -1624,6 +1675,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
fun setProfileHidden(profileName: String?, hidden: Boolean) =
profileController.setProfileHidden(profileName, hidden)
fun setProfileColor(profileName: String, colorHex: String?) =
profileController.setProfileColor(profileName, colorHex)
fun resetProfilePresentation() = profileController.resetProfilePresentation()
/**
@@ -1640,6 +1694,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
/** The active profile's local agent-icon path (client-side, never sent to Hermes). */
val profileIcon: StateFlow<String?> get() = profileController.profileIcon
val localProfileIcon: StateFlow<String?> get() = profileController.localProfileIcon
val serverProfileAvatar: StateFlow<String?> get() = profileController.serverProfileAvatar
val useLocalProfileIconOverride: StateFlow<Boolean>
get() = profileController.useLocalProfileIconOverride
val sharedProfileAvatarState: StateFlow<ProfileController.SharedAvatarState>
get() = profileController.sharedAvatarState
val hermesPetState: StateFlow<ProfileController.HermesPetState>
get() = profileController.hermesPetState
/** A local icon path for a specific profile identity on the active connection. */
fun profileIconFlow(profileName: String?) = profileController.profileIconFlow(profileName)
@@ -1649,10 +1711,32 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
fun setProfileIcon(uri: Uri) = profileController.setProfileIcon(uri)
fun setSharedProfileAvatar(uri: Uri) = profileController.setSharedProfileAvatar(uri)
fun setUseLocalProfileIconOverride(enabled: Boolean) =
profileController.setUseLocalProfileIconOverride(enabled)
fun importProfileIconFromHost() = profileController.importProfileIconFromHost()
fun clearProfileIcon() = profileController.clearProfileIcon()
fun uploadLocalProfileIconToHermes() = profileController.uploadLocalProfileIconToHermes()
fun clearSharedProfileAvatar() = profileController.clearSharedProfileAvatar()
fun refreshHermesPet() = profileController.refreshHermesPet()
fun loadHermesPetGallery() = profileController.loadHermesPetGallery()
fun selectHermesPet(slug: String) = profileController.selectHermesPet(slug)
fun loadHermesPetThumbnail(pet: GatewayPetGalleryItem) =
profileController.loadHermesPetThumbnail(pet)
fun disableHermesPet() = profileController.disableHermesPet()
fun refreshGatewayProfiles() = profileController.refreshGatewayProfiles()
fun selectProfile(profile: Profile?) = profileController.selectProfile(profile)
// --- Profile lock (per-connection pin to one profile) ------------------
@@ -2204,6 +2288,16 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
}
val convertLargePastesToAttachments: StateFlow<Boolean> =
chatInputPreferencesRepository.convertLargePastesToAttachments
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
fun setConvertLargePastesToAttachments(enabled: Boolean) {
viewModelScope.launch {
chatInputPreferencesRepository.setConvertLargePastesToAttachments(enabled)
}
}
// Turn-complete notification (default ON). RelayApp mirrors this into
// ChatViewModel.notifyOnTurnComplete; ChatSettingsScreen owns the toggle
// + the POST_NOTIFICATIONS runtime request on first enable.
@@ -2287,6 +2381,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
if (BuildFlavor.isSideload) com.hermesandroid.relay.bridge.BridgeSafetyManager.install(
context = application,
scope = viewModelScope,
activeConnectionId = connectionStore.activeConnectionId,
).also {
com.hermesandroid.relay.bridge.BridgeStatusOverlay.install(application)
} else null
@@ -2363,6 +2458,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
receivedAt = msg.sentAt ?: System.currentTimeMillis(),
chatId = msg.chatId,
connectionId = connectionStore.activeConnectionId.value,
arrivedWhileAway = msg.arrivedWhileAway,
),
)
}
@@ -3401,6 +3497,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
profileController.profileSessionStore.clearConnection(connectionId)
profileController.profileDisplayAliasStore.clearConnection(connectionId)
profileController.profileIconStore.clearConnection(connectionId)
com.hermesandroid.relay.data.BridgeCapabilityPolicyRepository(getApplication())
.clearConnection(connectionId)
}
private suspend fun readStoredDeviceIdForRemoval(
@@ -4236,6 +4334,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
.collectLatest {
_standardVoiceAvailability.value = StandardVoiceAvailability.Unknown
_standardAudioApiReachable.value = false
_hostResourcePressure.value = HostResourcePressureStatus()
_serverChatDisplaySettings.value = null
updateGatewayAvailability(GatewayAvailability.Unknown)
probeStandardVoice()
@@ -4535,6 +4634,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
if (connectionId == null || dashboardUrl.isNullOrBlank()) {
_standardVoiceAvailability.value = StandardVoiceAvailability.Unknown
_standardAudioApiReachable.value = false
_hostResourcePressure.value = HostResourcePressureStatus()
_serverChatDisplaySettings.value = null
updateGatewayAvailability(GatewayAvailability.Unknown)
return
@@ -4553,11 +4653,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
updateDashboardTopology(connectionId, null)
_standardVoiceAvailability.value = StandardVoiceAvailability.Unreachable
_standardAudioApiReachable.value = false
_hostResourcePressure.value = HostResourcePressureStatus()
_serverChatDisplaySettings.value = null
updateGatewayAvailability(GatewayAvailability.Unreachable)
recordDashboardStatusIfChanged(connectionId, status = null, session = null)
return
}
_hostResourcePressure.value = status.hostResourcePressure()
updateDashboardTopology(connectionId, status)
val session = if (status.authRequired) client.currentSession().getOrNull() else null
val authed = !status.authRequired || session?.authenticated == true
@@ -4595,6 +4697,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
android.util.Log.w("ConnectionVM", "probeStandardVoice failed: ${e.message}")
_standardVoiceAvailability.value = StandardVoiceAvailability.Unreachable
_standardAudioApiReachable.value = false
_hostResourcePressure.value = HostResourcePressureStatus()
_serverChatDisplaySettings.value = null
updateGatewayAvailability(GatewayAvailability.Unreachable)
} finally {
@@ -5314,6 +5417,19 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
routeCandidatesOverride: List<EndpointCandidate>? = null,
onResult: (StandardApiSetupResult) -> Unit,
) {
val normalizedApiKey = runCatching {
normalizeCredentialForHeader(apiKey, "API credential")
}.getOrElse {
onResult(
StandardApiSetupResult(
ok = false,
message = it.message ?: "Invalid API credential",
apiReachable = false,
relayPaired = authState.value is AuthState.Paired,
),
)
return
}
// Bare host/IP input gets http:// and the surface's default port —
// typing `192.168.1.10` or a Tailscale `100.x.y.z` without a scheme
// is the common case and used to either block the wizard or silently
@@ -5375,8 +5491,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
relayUrl = routeRelayUrl,
routeCandidates = routeCandidates,
)
if (apiKey.isNotBlank()) {
authManager.setApiKey(apiKey.trim())
if (normalizedApiKey.isNotBlank()) {
authManager.setApiKey(normalizedApiKey)
}
getApplication<Application>().relayDataStore.edit { preferences ->
@@ -5579,6 +5695,21 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
manualRelayUrlOverride: String?,
onResult: (ApiVoiceSetupResult) -> Unit,
) {
val normalizedApiKey = runCatching {
normalizeCredentialForHeader(apiKey, "API credential")
}.getOrElse {
onResult(
ApiVoiceSetupResult(
apiReachable = false,
relayUrl = null,
relayAutoDerived = false,
voiceConfigReachable = false,
voiceConfigError = it.message,
voiceRoute = "none",
),
)
return
}
val trimmedApiUrl = apiUrl.trim()
val trimmedOverride = manualRelayUrlOverride?.trim().orEmpty()
val derivedRelayUrl = RelayUrlDeriver.deriveFromApiUrl(trimmedApiUrl)
@@ -5597,8 +5728,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
viewModelScope.launch {
if (apiKey.isNotBlank()) {
authManager.setApiKey(apiKey.trim())
if (normalizedApiKey.isNotBlank()) {
authManager.setApiKey(normalizedApiKey)
}
getApplication<Application>().relayDataStore.edit { preferences ->
preferences[KEY_API_SERVER_URL] = trimmedApiUrl
@@ -5677,8 +5808,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
fun updateApiKey(key: String) {
viewModelScope.launch {
authManager.setApiKey(key)
rebuildApiClient()
runCatching {
authManager.setApiKey(key)
rebuildApiClient()
}.onFailure {
DiagnosticsLog.record(
category = DiagnosticCategory.Api,
severity = DiagnosticSeverity.Warning,
title = "API credential was not saved",
detail = it.message,
)
}
}
}
@@ -58,6 +58,9 @@ class ProfileInspectorViewModel(
private val _gatewayDescription = MutableStateFlow<GatewayProfileDescription?>(null)
val gatewayDescription: StateFlow<GatewayProfileDescription?> = _gatewayDescription.asStateFlow()
private val _gatewayWritable = MutableStateFlow(false)
val gatewayWritable: StateFlow<Boolean> = _gatewayWritable.asStateFlow()
private var gatewayConfigureUnsupported = false
private val _configState = MutableStateFlow<LoadState<ProfileConfigResponse>>(LoadState.Idle)
val configState: StateFlow<LoadState<ProfileConfigResponse>> = _configState.asStateFlow()
@@ -351,6 +354,7 @@ class ProfileInspectorViewModel(
if (configResult.isSuccess || soulResult.isSuccess || skillsResult.isSuccess) {
_source.value = ProfileInspectorSource.Relay
_gatewayDescription.value = null
_gatewayWritable.value = false
}
val fallbackMessage = gatewayError
?.takeUnless { it is GatewayProfileEditorUnsupportedException }
@@ -375,7 +379,8 @@ class ProfileInspectorViewModel(
private fun applyGatewayDescription(description: GatewayProfileDescription) {
if (description.name != profileName) return
_gatewayDescription.value = description
_skillToggleSupported.value = true
_gatewayWritable.value = !gatewayConfigureUnsupported
_skillToggleSupported.value = !gatewayConfigureUnsupported
_configState.value = LoadState.Loaded(description.toConfigResponse())
_soulState.value = LoadState.Loaded(description.toSoulResponse())
_skillsState.value = LoadState.Loaded(description.toSkillsResponse())
@@ -393,6 +398,11 @@ class ProfileInspectorViewModel(
viewModelScope.launch {
val configured = client.configureProfile(profileName, patch)
if (configured.isFailure) {
if (configured.exceptionOrNull() is GatewayProfileEditorUnsupportedException) {
gatewayConfigureUnsupported = true
_gatewayWritable.value = false
_skillToggleSupported.value = false
}
clearSavingFlags()
_editEvents.tryEmit(EditEvent.Error(configured.exceptionOrNull()?.message ?: "Save failed"))
return@launch
@@ -961,7 +961,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
private var bargeInPreferences: BargeInPreferencesRepository? = null
private var vadEngineFactory: (() -> VadEngine)? = null
private var bargeInListenerFactory: ((VadEngine, () -> Int) -> BargeInListener)? = null
private var bargeInListenerFactory: ((VadEngine) -> BargeInListener)? = null
private var bargeInPreferencesJob: Job? = null
/**
@@ -1090,7 +1090,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
// must be complete; we log and disable barge-in if not. ===
bargeInPreferences: BargeInPreferencesRepository? = null,
vadEngineFactory: (() -> VadEngine)? = null,
bargeInListenerFactory: ((VadEngine, () -> Int) -> BargeInListener)? = null,
bargeInListenerFactory: ((VadEngine) -> BargeInListener)? = null,
// === 2026-04-17 fix: persist interactionMode across app restarts ===
// Optional so pre-fix call sites keep compiling. When non-null, the
// VM subscribes to the settings flow and mirrors `interactionMode`
@@ -3405,9 +3405,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
responseText = "",
)
}
beginBargeInTurnIfEnabled(
audioSessionIdProvider = { realtimePcmPlayer?.audioSessionId ?: 0 },
)
beginBargeInTurnIfEnabled()
}
// Per-turn event state is hoisted to fields so one session-lived callback
@@ -4171,9 +4169,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
responseText = "",
)
}
beginBargeInTurnIfEnabled(
audioSessionIdProvider = { realtimePcmPlayer?.audioSessionId ?: 0 },
)
beginBargeInTurnIfEnabled()
val deliveryResult = CompletableDeferred<Result<Unit>>()
val queued = channel.trySend(
RealtimeTurnInput(
@@ -5082,9 +5078,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
val firstAudioChunk = bargeInStarted.compareAndSet(false, true)
if (firstAudioChunk) {
if (bargeInListener == null) {
startBargeInListenerIfEnabled(
audioSessionIdProvider = { pcmPlayer.audioSessionId },
)
startBargeInListenerIfEnabled()
}
// Freeze quiet-room calibration before the first PCM write can
// reach AudioTrack and leak speaker output into the noise floor.
@@ -5584,32 +5578,23 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
* listener's internal poll loop can watch it flip from 0 to non-zero
* as playback begins.
*/
private fun beginBargeInTurnIfEnabled(
audioSessionIdProvider: (() -> Int)? = null,
) {
private fun beginBargeInTurnIfEnabled() {
val previousReader = stopBargeInListener()
val epoch = bargeInTurnEpoch.incrementAndGet()
activeBargeInTurnEpoch = epoch
if (previousReader == null) {
startBargeInListenerIfEnabled(
audioSessionIdProvider = audioSessionIdProvider,
epoch = epoch,
)
startBargeInListenerIfEnabled(epoch = epoch)
} else {
viewModelScope.launch {
previousReader.join()
if (activeBargeInTurnEpoch == epoch) {
startBargeInListenerIfEnabled(
audioSessionIdProvider = audioSessionIdProvider,
epoch = epoch,
)
startBargeInListenerIfEnabled(epoch = epoch)
}
}
}
}
private fun startBargeInListenerIfEnabled(
audioSessionIdProvider: (() -> Int)? = null,
epoch: Long = bargeInTurnEpoch.incrementAndGet(),
) {
// Already running → no-op. One listener spans generation and playback,
@@ -5634,17 +5619,6 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
return
}
val sessionProvider: () -> Int = if (audioSessionIdProvider != null) {
audioSessionIdProvider
} else {
val p = player
if (p == null) {
Log.i(TAG, "Barge-in listener skipped; legacy player not ready")
return
}
fun(): Int { return p.audioSessionId }
}
val vad = try {
vadFactory().also { it.setSensitivity(prefs.sensitivity) }
} catch (t: Throwable) {
@@ -5654,7 +5628,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
bargeInVadEngine = vad
val listener = try {
factory(vad, sessionProvider)
factory(vad)
} catch (t: Throwable) {
Log.w(TAG, "BargeInListener construction failed; skipping barge-in: ${t.message}")
try { vad.close() } catch (_: Throwable) { /* ignore */ }
@@ -5682,8 +5656,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
Log.i(
TAG,
"Starting barge-in listener; sensitivity=${prefs.sensitivity} " +
"source=${if (audioSessionIdProvider != null) "realtime_pcm" else "legacy_player"} " +
"session=${sessionProvider()}",
"effects=capture_session",
)
try {
listener.start(viewModelScope)
@@ -4,9 +4,13 @@ import android.content.Context
import android.net.Uri
import com.hermesandroid.relay.auth.AuthManager
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.GatewayProfileManagementUnsupportedException
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.ProfileDisplayAliasStore
import com.hermesandroid.relay.data.ProfileIconStore
import com.hermesandroid.relay.data.prepareProfileAvatar
import com.hermesandroid.relay.data.profileAvatarMime
import com.hermesandroid.relay.data.preferredProfileIcon
import com.hermesandroid.relay.data.ProfileLockStore
import com.hermesandroid.relay.data.ProfilePresentation
import com.hermesandroid.relay.data.ProfilePresentationPolicy
@@ -17,6 +21,10 @@ import com.hermesandroid.relay.data.SessionTransport
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.DashboardProfileScope
import com.hermesandroid.relay.network.upstream.GatewayAvailability
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.GatewayPetGalleryItem
import com.hermesandroid.relay.network.upstream.GatewayPetInfo
import com.hermesandroid.relay.network.upstream.GatewayRpcException
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
import com.hermesandroid.relay.network.upstream.models.SessionItem
@@ -39,7 +47,46 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.security.MessageDigest
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
internal fun isCurrentProfileAvatarRefresh(
requestConnectionId: String,
activeConnectionId: String?,
requestGeneration: Long,
currentGeneration: Long,
): Boolean = requestConnectionId == activeConnectionId && requestGeneration == currentGeneration
internal fun mergeGatewayProfileRoster(
gateway: List<Profile>,
fallback: List<Profile>,
): List<Profile> = gateway.map { authoritative ->
val extension = fallback.firstOrNull { it.name == authoritative.name }
?: return@map authoritative
authoritative.copy(
systemMessage = extension.systemMessage,
gatewayRunning = extension.gatewayRunning,
hasSoul = extension.hasSoul,
apiServerEnabled = extension.apiServerEnabled,
apiServerUrl = extension.apiServerUrl,
apiServerHost = extension.apiServerHost,
apiServerPort = extension.apiServerPort,
apiServerKeyPresent = extension.apiServerKeyPresent,
)
}
internal fun selectProfileRoster(
gatewayAuthoritative: Boolean,
gateway: List<Profile>,
fallback: List<Profile>,
): List<Profile> = if (gatewayAuthoritative) {
mergeGatewayProfileRoster(gateway, fallback)
} else {
fallback
}
/**
* Owns the **agent-profiles cluster** of
@@ -93,6 +140,8 @@ class ProfileController(
private val rebuildChatApiClient: suspend () -> Unit,
/** Optional Relay client used only for importing an icon from the host. */
private val relayHttpClient: RelayHttpClient? = null,
/** Current per-connection Gateway client; profile management stays upstream-owned. */
private val gatewayClientProvider: () -> GatewayChatClient? = { null },
) {
// Server-advertised named agent configs, flattened to a StateFlow the
@@ -101,15 +150,24 @@ class ProfileController(
// underlying AuthManager instance is replaced and the public flow needs to
// repoint at the new manager's backing state.
private val _dashboardProfiles = MutableStateFlow<List<Profile>>(emptyList())
private val _gatewayProfiles = MutableStateFlow<List<Profile>>(emptyList())
private val _gatewayRosterAuthoritative = MutableStateFlow(false)
private val avatarRefreshGeneration = AtomicLong(0L)
private val petRefreshGeneration = AtomicLong(0L)
private val petGalleryGeneration = AtomicLong(0L)
private val petThumbnailRequests = ConcurrentHashMap.newKeySet<String>()
val agentProfiles: StateFlow<List<Profile>> = combine(
authManagerFlow.flatMapLatest { it.agentProfiles },
_dashboardProfiles,
) { relay, dashboard ->
// Prefer the relay's list when it has entries (richer runtime metadata);
// fall back to the dashboard list so a dashboard-only connection still
// sees its server profiles in the chat picker.
relay.ifEmpty { dashboard }
_gatewayProfiles,
_gatewayRosterAuthoritative,
) { relay, dashboard, gateway, gatewayAuthoritative ->
// Current Gateway rows are authoritative for shared profile metadata and
// avatar presence. Relay-only runtime/API routing fields are joined by
// exact name so adopting the roster never drops an isolated profile route.
val fallback = relay.ifEmpty { dashboard }
selectProfileRoster(gatewayAuthoritative, gateway, fallback)
}.stateIn(scope, SharingStarted.Eagerly, authManagerFlow.value.agentProfiles.value)
private val _selectedProfile = MutableStateFlow<Profile?>(null)
@@ -257,8 +315,8 @@ class ProfileController(
val profileIconStore: ProfileIconStore = ProfileIconStore(context)
/** The active profile's local agent-icon path (twin of [profileDisplayAlias]). */
val profileIcon: StateFlow<String?> = combine(
/** The active profile's device-local fallback icon. */
val localProfileIcon: StateFlow<String?> = combine(
activeConnectionId,
selectedProfile,
) { connectionId, profile ->
@@ -271,11 +329,63 @@ class ProfileController(
}
}.stateIn(scope, SharingStarted.Eagerly, null)
private val activeServerAvatarIdentity: Flow<Pair<String?, String?>> = combine(
activeConnectionId,
selectedProfile,
serverDefaultProfileScope,
_gatewayProfiles,
) { connectionId, selected, serverDefault, gatewayProfiles ->
connectionId to (
selected?.name ?: serverDefault?.active
?: gatewayProfiles.firstOrNull(Profile::isDefault)?.name
)
}
/** Cached bytes fetched from Hermes; always preferred over the local fallback. */
val serverProfileAvatar: StateFlow<String?> = activeServerAvatarIdentity
.flatMapLatest { (connectionId, profileName) ->
if (connectionId == null || profileName.isNullOrBlank()) flowOf(null)
else profileIconStore.serverAvatarFlow(connectionId, profileName)
}.stateIn(scope, SharingStarted.Eagerly, null)
/** Whether this phone should prefer its local image over Hermes' shared avatar. */
val useLocalProfileIconOverride: StateFlow<Boolean> = combine(
activeConnectionId,
selectedProfile,
) { connectionId, profile ->
connectionId to AgentDisplay.profileRequestName(profile?.name)
}.flatMapLatest { (connectionId, profileName) ->
if (connectionId == null) flowOf(false)
else profileIconStore.localOverrideFlow(connectionId, profileName)
}.stateIn(scope, SharingStarted.Eagerly, false)
val profileIcon: StateFlow<String?> = combine(
serverProfileAvatar,
localProfileIcon,
useLocalProfileIconOverride,
) { server, local, localOverride -> preferredProfileIcon(server, local, localOverride) }
.stateIn(scope, SharingStarted.Eagerly, null)
/** Local icon for any profile identity on the active connection. */
fun profileIconFlow(profileName: String?): Flow<String?> = activeConnectionId
.flatMapLatest { connectionId ->
if (connectionId == null) flowOf(null)
else profileIconStore.iconFlow(connectionId, profileName)
fun profileIconFlow(profileName: String?): Flow<String?> = combine(
activeConnectionId,
serverDefaultProfileScope,
_gatewayProfiles,
) { connectionId, serverDefault, gatewayProfiles ->
connectionId to (
profileName ?: serverDefault?.active
?: gatewayProfiles.firstOrNull(Profile::isDefault)?.name
)
}
.flatMapLatest { (connectionId, serverProfileName) ->
if (connectionId == null) return@flatMapLatest flowOf(null)
val local = profileIconStore.iconFlow(connectionId, profileName)
val localOverride = profileIconStore.localOverrideFlow(connectionId, profileName)
if (serverProfileName.isNullOrBlank()) local else combine(
profileIconStore.serverAvatarFlow(connectionId, serverProfileName),
local,
localOverride,
) { server, fallback, override -> preferredProfileIcon(server, fallback, override) }
}
data class HostIconImportState(
@@ -287,6 +397,44 @@ class ProfileController(
val hostIconImportState: StateFlow<HostIconImportState> =
_hostIconImportState.asStateFlow()
data class SharedAvatarState(
val loading: Boolean = false,
val error: String? = null,
)
private val _sharedAvatarState = MutableStateFlow(SharedAvatarState())
val sharedAvatarState: StateFlow<SharedAvatarState> = _sharedAvatarState.asStateFlow()
data class HermesPetPresentation(
val connectionId: String,
val profileName: String?,
val slug: String,
val displayName: String,
val spritesheetPath: String,
val spritesheetRevision: String,
val frameWidth: Int,
val frameHeight: Int,
val framesPerState: Int,
val framesByState: Map<String, Int>,
val framesByRow: Map<String, Int>,
val loopMs: Int,
val scale: Float,
val stateRows: List<String>,
)
data class HermesPetState(
val supported: Boolean? = null,
val loading: Boolean = false,
val galleryLoading: Boolean = false,
val active: HermesPetPresentation? = null,
val gallery: List<GatewayPetGalleryItem> = emptyList(),
val thumbnails: Map<String, String> = emptyMap(),
val error: String? = null,
)
private val _hermesPetState = MutableStateFlow(HermesPetState())
val hermesPetState: StateFlow<HermesPetState> = _hermesPetState.asStateFlow()
/**
* Load the host's agent profiles from the dashboard `/api/profiles` into
* [agentProfiles] (merged in the combine above). Lets the chat agent sheet
@@ -302,6 +450,8 @@ class ProfileController(
return
}
scope.launch {
refreshGatewayProfiles(connectionId)
refreshHermesPet(connectionId)
val client = dashboardClientFactory(connectionId, dashboardUrl)
val defaultScope = client.getActiveProfileScope().getOrNull()
if (activeConnectionId.value != connectionId) return@launch
@@ -324,6 +474,258 @@ class ProfileController(
}
}
fun refreshGatewayProfiles() {
val connectionId = activeConnectionId.value ?: return
scope.launch {
refreshGatewayProfiles(connectionId)
refreshHermesPet(connectionId)
}
}
private suspend fun refreshGatewayProfiles(connectionId: String) {
val gateway = gatewayClientProvider() ?: return
val generation = avatarRefreshGeneration.incrementAndGet()
gateway.listProfiles().onSuccess { profiles ->
if (!isCurrentProfileAvatarRefresh(connectionId, activeConnectionId.value, generation, avatarRefreshGeneration.get())) return@onSuccess
_gatewayProfiles.value = profiles
_gatewayRosterAuthoritative.value = true
profiles.forEach { profile ->
if (!profile.hasAvatar) {
clearServerAvatarCache(connectionId, profile.name, generation)
} else {
gateway.getProfileAvatar(profile.name).onSuccess { asset ->
if (!isCurrentProfileAvatarRefresh(connectionId, activeConnectionId.value, generation, avatarRefreshGeneration.get())) {
return@onSuccess
}
if (asset == null) {
clearServerAvatarCache(connectionId, profile.name, generation)
} else {
val path = copyServerAvatarBytes(connectionId, profile.name, asset.data, asset.mime)
if (path != null && avatarRefreshGeneration.get() == generation) {
profileIconStore.setServerAvatar(connectionId, profile.name, path)
}
}
}
}
}
}.onFailure { failure ->
if (
failure is GatewayProfileManagementUnsupportedException &&
isCurrentProfileAvatarRefresh(
connectionId,
activeConnectionId.value,
generation,
avatarRefreshGeneration.get(),
)
) {
_gatewayProfiles.value = emptyList()
_gatewayRosterAuthoritative.value = false
}
}
}
private suspend fun clearServerAvatarCache(connectionId: String, profileName: String, generation: Long) {
if (avatarRefreshGeneration.get() != generation) return
profileIconStore.serverAvatarFlow(connectionId, profileName).first()?.let { runCatching { File(it).delete() } }
profileIconStore.setServerAvatar(connectionId, profileName, null)
}
/** Refresh the active profile's upstream sprite contract without re-sending an unchanged sheet. */
fun refreshHermesPet() {
val connectionId = activeConnectionId.value ?: return
scope.launch { refreshHermesPet(connectionId) }
}
private suspend fun refreshHermesPet(connectionId: String) {
val gateway = gatewayClientProvider() ?: run {
_hermesPetState.value = HermesPetState(supported = null)
return
}
val profileName = resolveSessionProfileName()
val generation = petRefreshGeneration.incrementAndGet()
val previous = _hermesPetState.value.active?.takeIf {
it.connectionId == connectionId && it.profileName == profileName
}
_hermesPetState.value = _hermesPetState.value.copy(loading = true, error = null)
gateway.petInfo(profile = profileName, knownRevision = previous?.spritesheetRevision).fold(
onSuccess = { info ->
if (!isCurrentPetRefresh(connectionId, generation)) return@fold
if (!info.enabled) {
_hermesPetState.value = HermesPetState(supported = true)
return@fold
}
val presentation = cacheHermesPet(connectionId, profileName, info, previous)
_hermesPetState.value = if (presentation == null) {
HermesPetState(
supported = true,
error = "Hermes returned an animated pet that this phone could not cache",
)
} else {
_hermesPetState.value.copy(
supported = true,
loading = false,
active = presentation,
error = null,
)
}
},
onFailure = { failure ->
if (!isCurrentPetRefresh(connectionId, generation)) return@fold
_hermesPetState.value = if ((failure as? GatewayRpcException)?.code == -32601) {
HermesPetState(supported = false)
} else {
_hermesPetState.value.copy(
loading = false,
error = failure.message ?: "Could not load the Hermes animated pet",
)
}
},
)
}
/** Load the profile-scoped upstream gallery only when the user opens the picker. */
fun loadHermesPetGallery() {
val connectionId = activeConnectionId.value ?: return
val gateway = gatewayClientProvider() ?: return
val profileName = resolveSessionProfileName()
val generation = petGalleryGeneration.incrementAndGet()
scope.launch {
_hermesPetState.value = _hermesPetState.value.copy(galleryLoading = true, error = null)
gateway.petGallery(profile = profileName).fold(
onSuccess = { gallery ->
if (!isCurrentPetGallery(connectionId, profileName, generation)) return@fold
_hermesPetState.value = _hermesPetState.value.copy(
supported = true,
galleryLoading = false,
gallery = gallery.pets,
error = null,
)
},
onFailure = { failure ->
if (!isCurrentPetGallery(connectionId, profileName, generation)) return@fold
_hermesPetState.value = _hermesPetState.value.copy(
galleryLoading = false,
error = failure.message ?: "Could not load the Hermes pet gallery",
)
},
)
}
}
fun selectHermesPet(slug: String) = mutateHermesPet { gateway, profile ->
gateway.selectPet(slug, profile)
}
/** Lazily fetch one upstream-cropped idle frame for a visible gallery row. */
fun loadHermesPetThumbnail(pet: GatewayPetGalleryItem) {
if (_hermesPetState.value.thumbnails.containsKey(pet.slug)) return
val connectionId = activeConnectionId.value ?: return
val gateway = gatewayClientProvider() ?: return
val profileName = resolveSessionProfileName()
val requestKey = "$connectionId\u0000${AgentDisplay.profileSessionKey(profileName)}\u0000${pet.slug}"
if (!petThumbnailRequests.add(requestKey)) return
scope.launch {
try {
gateway.petThumbnail(
slug = pet.slug,
spritesheetUrl = pet.spritesheetUrl,
profile = profileName,
).onSuccess { dataUri ->
if (
dataUri != null && activeConnectionId.value == connectionId &&
resolveSessionProfileName() == profileName
) {
_hermesPetState.value = _hermesPetState.value.copy(
thumbnails = _hermesPetState.value.thumbnails + (pet.slug to dataUri),
)
}
}
} finally {
petThumbnailRequests.remove(requestKey)
}
}
}
fun disableHermesPet() = mutateHermesPet { gateway, profile ->
gateway.disablePet(profile)
}
private fun mutateHermesPet(
mutation: suspend (GatewayChatClient, String?) -> Result<Unit>,
) {
val connectionId = activeConnectionId.value ?: return
val gateway = gatewayClientProvider() ?: return
val profileName = resolveSessionProfileName()
scope.launch {
_hermesPetState.value = _hermesPetState.value.copy(loading = true, error = null)
mutation(gateway, profileName).fold(
onSuccess = { refreshHermesPet(connectionId) },
onFailure = { failure ->
_hermesPetState.value = _hermesPetState.value.copy(
loading = false,
error = failure.message ?: "Could not update the Hermes animated pet",
)
},
)
}
}
private fun isCurrentPetRefresh(connectionId: String, generation: Long): Boolean =
activeConnectionId.value == connectionId && petRefreshGeneration.get() == generation
private fun isCurrentPetGallery(connectionId: String, profileName: String?, generation: Long): Boolean =
activeConnectionId.value == connectionId &&
resolveSessionProfileName() == profileName &&
petGalleryGeneration.get() == generation
private suspend fun cacheHermesPet(
connectionId: String,
profileName: String?,
info: GatewayPetInfo,
previous: HermesPetPresentation?,
): HermesPetPresentation? = withContext(Dispatchers.IO) {
val slug = info.slug ?: return@withContext null
val revision = info.spritesheetRevision ?: return@withContext null
val path = if (info.spritesheetUnchanged && previous?.spritesheetRevision == revision) {
previous.spritesheetPath.takeIf { File(it).isFile }
} else {
val bytes = info.spritesheet ?: return@withContext null
val dir = File(context.filesDir, "hermes-profile-pets").apply { mkdirs() }
val key = MessageDigest.getInstance("SHA-256")
.digest("$connectionId\u0000${AgentDisplay.profileSessionKey(profileName)}".toByteArray())
.take(12)
.joinToString("") { "%02x".format(it) }
val extension = if (info.mime == "image/webp") "webp" else "png"
val target = File(dir, "$key.$extension")
val pending = File(dir, "$key.$extension.tmp")
runCatching {
pending.writeBytes(bytes)
if (!pending.renameTo(target)) {
target.writeBytes(bytes)
pending.delete()
}
target.absolutePath
}.getOrNull()
} ?: return@withContext null
HermesPetPresentation(
connectionId = connectionId,
profileName = profileName,
slug = slug,
displayName = info.displayName ?: slug,
spritesheetPath = path,
spritesheetRevision = revision,
frameWidth = info.frameWidth,
frameHeight = info.frameHeight,
framesPerState = info.framesPerState,
framesByState = info.framesByState,
framesByRow = info.framesByRow,
loopMs = info.loopMs,
scale = info.scale,
stateRows = info.stateRows,
)
}
/** Effective profile namespace for Gateway and profile-scoped session I/O. */
fun resolveSessionProfileName(selectedProfileName: String? = _selectedProfile.value?.name): String? =
AgentDisplay.effectiveSessionProfileName(
@@ -350,6 +752,38 @@ class ProfileController(
return dashboardClientFactory(connectionId, dashboardUrl).listAllProfileSessions(limit)
}
suspend fun deleteSession(profileName: String, sessionId: String): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.deleteSession(sessionId, profileName)
.isSuccess
}
suspend fun renameSession(profileName: String, sessionId: String, title: String): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.renameSession(sessionId, title, profileName)
.isSuccess
}
suspend fun setSessionPinned(profileName: String, sessionId: String, pinned: Boolean): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.setSessionPinned(sessionId, pinned, profileName)
.isSuccess
}
suspend fun setSessionArchived(profileName: String, sessionId: String, archived: Boolean): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.setSessionArchived(sessionId, archived, profileName)
.isSuccess
}
/**
* A session's transcript, scoped to the active profile via the dashboard
* `/api/sessions/{id}/messages?profile=`. Returns `null` off the dashboard
@@ -358,10 +792,19 @@ class ProfileController(
suspend fun loadProfileScopedMessages(
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? = loadProfileScopedMessages(
profileName = resolveSessionProfileName(),
sessionId = sessionId,
mode = mode,
)
suspend fun loadProfileScopedMessages(
profileName: String?,
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? {
val connectionId = activeConnectionId.value ?: return null
val dashboardUrl = activeDashboardUrlProvider() ?: return null
val profileName = resolveSessionProfileName()
return dashboardClientFactory(connectionId, dashboardUrl)
.getSessionMessages(sessionId, profileName, mode)
}
@@ -431,6 +874,7 @@ class ProfileController(
scope.launch {
val path = copyIcon(connectionId, profileName, uri) ?: return@launch
profileIconStore.setIcon(connectionId, profileName, path)
profileIconStore.setLocalOverride(connectionId, profileName, true)
}
}
@@ -456,6 +900,7 @@ class ProfileController(
)
} else {
profileIconStore.setIcon(connectionId, profileName, path)
profileIconStore.setLocalOverride(connectionId, profileName, true)
_hostIconImportState.value = HostIconImportState()
}
},
@@ -479,23 +924,120 @@ class ProfileController(
}
}
fun setUseLocalProfileIconOverride(enabled: Boolean) {
val connectionId = activeConnectionId.value ?: return
val profileName = AgentDisplay.profileRequestName(_selectedProfile.value?.name)
scope.launch { profileIconStore.setLocalOverride(connectionId, profileName, enabled) }
}
/** Upload a selected static image directly to Hermes without changing this phone's override. */
fun setSharedProfileAvatar(uri: Uri) {
val connectionId = activeConnectionId.value ?: return
val profileName = resolveSharedAssetProfileName()
val gateway = gatewayClientProvider()
if (profileName.isNullOrBlank() || gateway == null) {
_sharedAvatarState.value = SharedAvatarState(error = "Shared avatars require a current Hermes Gateway")
return
}
scope.launch {
_sharedAvatarState.value = SharedAvatarState(loading = true)
val bytes = withContext(Dispatchers.IO) {
prepareProfileAvatar(context, uri, GatewayChatClient.PROFILE_AVATAR_MAX_BYTES)
}
if (bytes == null) {
_sharedAvatarState.value = SharedAvatarState(error = "That image could not be prepared for Hermes")
return@launch
}
gateway.setProfileAvatar(profileName, bytes).fold(
onSuccess = {
cacheAcknowledgedSharedAvatar(connectionId, profileName, bytes)
_sharedAvatarState.value = SharedAvatarState()
},
onFailure = { failure ->
_sharedAvatarState.value = SharedAvatarState(
error = failure.message ?: "Shared avatar upload failed",
)
},
)
}
}
/** Explicit migration: upload the current device-local fallback to Hermes. */
fun uploadLocalProfileIconToHermes() {
val connectionId = activeConnectionId.value ?: return
val profileName = resolveSharedAssetProfileName()
if (profileName.isNullOrBlank()) {
_sharedAvatarState.value = SharedAvatarState(error = "Hermes profile identity is not available")
return
}
val gateway = gatewayClientProvider()
if (gateway == null) {
_sharedAvatarState.value = SharedAvatarState(error = "Shared avatars require a current Hermes Gateway")
return
}
scope.launch {
_sharedAvatarState.value = SharedAvatarState(loading = true)
val path = profileIconStore.iconFlow(
connectionId,
AgentDisplay.profileRequestName(_selectedProfile.value?.name),
).first()
val file = path?.let(::File)
val bytes = when {
file == null || !file.isFile -> null
file.length() > GatewayChatClient.PROFILE_AVATAR_MAX_BYTES -> null
else -> withContext(Dispatchers.IO) { runCatching { file.readBytes() }.getOrNull() }
}
if (bytes == null) {
_sharedAvatarState.value = SharedAvatarState(error = "Choose a local PNG, JPEG, or WebP under 2 MB first")
return@launch
}
gateway.setProfileAvatar(profileName, bytes).fold(
onSuccess = {
cacheAcknowledgedSharedAvatar(connectionId, profileName, bytes)
_sharedAvatarState.value = SharedAvatarState()
},
onFailure = { failure ->
_sharedAvatarState.value = SharedAvatarState(
error = failure.message ?: "Shared avatar upload failed",
)
},
)
}
}
/** Clear only Hermes' shared asset; the device-local fallback remains untouched. */
fun clearSharedProfileAvatar() {
val connectionId = activeConnectionId.value ?: return
val profileName = resolveSharedAssetProfileName()
val gateway = gatewayClientProvider()
if (profileName.isNullOrBlank() || gateway == null) {
_sharedAvatarState.value = SharedAvatarState(error = "Shared avatars require a current Hermes Gateway")
return
}
scope.launch {
_sharedAvatarState.value = SharedAvatarState(loading = true)
gateway.clearProfileAvatar(profileName).fold(
onSuccess = {
val generation = avatarRefreshGeneration.incrementAndGet()
clearServerAvatarCache(connectionId, profileName, generation)
_gatewayProfiles.value = _gatewayProfiles.value.map { profile ->
if (profile.name == profileName) profile.copy(hasAvatar = false) else profile
}
_sharedAvatarState.value = SharedAvatarState()
},
onFailure = { failure ->
_sharedAvatarState.value = SharedAvatarState(
error = failure.message ?: "Shared avatar clear failed",
)
},
)
}
}
/** Copy [uri]'s image bytes into app-internal storage; returns the path or null. */
private suspend fun copyIcon(connectionId: String, profileName: String?, uri: Uri): String? =
withContext(Dispatchers.IO) {
try {
val dir = File(context.filesDir, "profile-icons").apply { mkdirs() }
val key = AgentDisplay.profileSessionKey(profileName)
val safe = "${connectionId}_$key"
.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }
.joinToString("")
val out = File(dir, "$safe.png")
context.contentResolver.openInputStream(uri)?.use { input ->
out.outputStream().use { input.copyTo(it) }
} ?: return@withContext null
out.absolutePath
} catch (t: Throwable) {
null
}
readBoundedUri(uri, LOCAL_PROFILE_ICON_MAX_BYTES)?.let { bytes ->
copyIconBytes(connectionId, profileName, bytes)
}
private suspend fun copyIconBytes(
@@ -504,17 +1046,131 @@ class ProfileController(
bytes: ByteArray,
): String? = withContext(Dispatchers.IO) {
try {
val extension = localImageExtension(bytes) ?: return@withContext null
val dir = File(context.filesDir, "profile-icons").apply { mkdirs() }
val key = AgentDisplay.profileSessionKey(profileName)
val safe = "${connectionId}_$key"
.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }
.joinToString("")
File(dir, "$safe.png").also { it.writeBytes(bytes) }.absolutePath
val target = File(dir, "$safe.$extension")
target.writeBytes(bytes)
LOCAL_PROFILE_ICON_EXTENSIONS
.filterNot(extension::equals)
.forEach { stale -> runCatching { File(dir, "$safe.$stale").delete() } }
target.absolutePath
} catch (_: Throwable) {
null
}
}
private suspend fun readBoundedUri(uri: Uri, maxBytes: Int): ByteArray? =
withContext(Dispatchers.IO) {
runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val output = ByteArrayOutputStream(minOf(maxBytes, 64 * 1024))
val buffer = ByteArray(16 * 1024)
var total = 0
while (true) {
val read = input.read(buffer)
if (read < 0) break
total += read
if (total > maxBytes) return@use null
output.write(buffer, 0, read)
}
output.toByteArray()
}
}.getOrNull()
}
private fun localImageExtension(bytes: ByteArray): String? = when {
bytes.size >= 8 && bytes.copyOfRange(0, 8).contentEquals(
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a),
) -> "png"
bytes.size >= 3 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte() &&
bytes[2] == 0xff.toByte() -> "jpg"
bytes.size >= 6 && (
bytes.copyOfRange(0, 6).contentEquals("GIF87a".toByteArray()) ||
bytes.copyOfRange(0, 6).contentEquals("GIF89a".toByteArray())
) -> "gif"
bytes.size >= 12 && bytes.copyOfRange(0, 4).contentEquals("RIFF".toByteArray()) &&
bytes.copyOfRange(8, 12).contentEquals("WEBP".toByteArray()) -> "webp"
else -> null
}
private suspend fun copyServerAvatarBytes(
connectionId: String,
profileName: String,
bytes: ByteArray,
mime: String,
): String? = withContext(Dispatchers.IO) {
try {
val extension = when (mime) {
"image/png" -> "png"
"image/jpeg" -> "jpg"
"image/webp" -> "webp"
else -> return@withContext null
}
val dir = File(context.filesDir, "profile-avatars-server").apply { mkdirs() }
val safe = MessageDigest.getInstance("SHA-256")
.digest("$connectionId\u0000${AgentDisplay.profileSessionKey(profileName)}".toByteArray())
.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
val target = File(dir, "$safe.$extension")
val temp = File(dir, "$safe.$extension.tmp")
temp.writeBytes(bytes)
try {
java.nio.file.Files.move(
temp.toPath(),
target.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE,
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
)
} catch (_: java.nio.file.AtomicMoveNotSupportedException) {
java.nio.file.Files.move(
temp.toPath(),
target.toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
)
}
listOf("png", "jpg", "webp")
.filterNot(extension::equals)
.forEach { stale -> runCatching { File(dir, "$safe.$stale").delete() } }
target.absolutePath
} catch (_: Throwable) {
null
}
}
private suspend fun cacheAcknowledgedSharedAvatar(
connectionId: String,
profileName: String,
bytes: ByteArray,
) {
if (activeConnectionId.value != connectionId) return
val mime = profileAvatarMime(bytes) ?: return
val generation = avatarRefreshGeneration.incrementAndGet()
val path = copyServerAvatarBytes(connectionId, profileName, bytes, mime) ?: return
if (!isCurrentProfileAvatarRefresh(
connectionId,
activeConnectionId.value,
generation,
avatarRefreshGeneration.get(),
)
) return
profileIconStore.setServerAvatar(connectionId, profileName, path)
_gatewayProfiles.value = _gatewayProfiles.value.map { profile ->
if (profile.name == profileName) profile.copy(hasAvatar = true) else profile
}
}
private fun resolveSharedAssetProfileName(): String? =
resolveSessionProfileName()
?: _gatewayProfiles.value.firstOrNull(Profile::isDefault)?.name
private companion object {
const val LOCAL_PROFILE_ICON_MAX_BYTES = 8_000_000
val LOCAL_PROFILE_ICON_EXTENSIONS = listOf("png", "jpg", "gif", "webp")
}
/**
* The stored lock-token for a (possibly null) profile. Server default —
* A null selection maps to [AgentDisplay.SERVER_DEFAULT_PROFILE_KEY]; a
@@ -583,6 +1239,24 @@ class ProfileController(
}
}
/** Persist or clear a local cosmetic accent for a named profile. */
fun setProfileColor(profileName: String, colorHex: String?) {
val connectionId = activeConnectionId.value ?: return
val key = profileName.trim()
if (key.isBlank() || key.equals("default", ignoreCase = true)) return
scope.launch {
profilePresentationWriteMutex.withLock {
val updated = profilePresentationStore
.presentationFlow(connectionId)
.first()
.colors
.toMutableMap()
.apply { if (colorHex == null) remove(key) else put(key, colorHex) }
profilePresentationStore.setColors(connectionId, updated)
}
}
}
fun resetProfilePresentation() {
val connectionId = activeConnectionId.value ?: return
scope.launch {
@@ -600,6 +1274,11 @@ class ProfileController(
* [selectProfile] is the gated public entry point.
*/
private fun applyProfileSelection(normalizedProfile: Profile?) {
_sharedAvatarState.value = SharedAvatarState()
_hostIconImportState.value = HostIconImportState()
petRefreshGeneration.incrementAndGet()
petGalleryGeneration.incrementAndGet()
_hermesPetState.value = HermesPetState()
_selectedProfile.value = normalizedProfile
setLastSessionId(null)
val connectionId = activeConnectionId.value ?: return
@@ -608,6 +1287,7 @@ class ProfileController(
scope.launch {
profileSelectionStore.setSelectedProfile(connectionId, normalizedProfile?.name)
rebuildChatApiClient()
refreshHermesPet(connectionId)
}
refreshLastSessionForProfile(connectionId, normalizedProfile?.name)
}
@@ -781,6 +1461,12 @@ class ProfileController(
// pending persisted name can't resolve against the previous connection's
// profiles before the new connection's list arrives.
_dashboardProfiles.value = emptyList()
_gatewayProfiles.value = emptyList()
_gatewayRosterAuthoritative.value = false
avatarRefreshGeneration.incrementAndGet()
petRefreshGeneration.incrementAndGet()
petGalleryGeneration.incrementAndGet()
_hermesPetState.value = HermesPetState()
}
/** Clear just the in-memory selection + pending state (resetAppData). */
@@ -790,6 +1476,9 @@ class ProfileController(
_pendingSelectedProfileName.value = null
_serverDefaultProfileScope.value = null
_serverDefaultProfileSettled.value = false
petRefreshGeneration.incrementAndGet()
petGalleryGeneration.incrementAndGet()
_hermesPetState.value = HermesPetState()
}
fun clearSelectedProfile() {
@@ -16,6 +16,7 @@ import com.hermesandroid.relay.network.upstream.isNativeDashboardTransportEligib
import com.hermesandroid.relay.network.upstream.ServerCapabilities
import com.hermesandroid.relay.network.upstream.resolveStreamingEndpointPreference
import com.hermesandroid.relay.network.upstream.trustedDashboardBearerAuthOrNull
import com.hermesandroid.relay.network.shutdownOffMainThread
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -80,6 +81,10 @@ class UpstreamTransportController(
/** Applies pairing-bound TLS to a standard authenticated client when needed. */
private val pinnedClientProvider: (String, okhttp3.OkHttpClient) -> okhttp3.OkHttpClient? =
{ _, _ -> null },
private val dashboardHttpClientFactory:
(DashboardCookieStore, DashboardBearerAuth?) -> okhttp3.OkHttpClient = { cookieStore, bearerAuth ->
DashboardApiClient.defaultClient(cookieStore, bearerAuth)
},
) {
// --- Per-connection dashboard cookie stores ----------------------------
@@ -151,9 +156,9 @@ class UpstreamTransportController(
* scoping, the gateway client, standard-API setup probe) route through.
*/
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient {
val base = DashboardApiClient.defaultClient(
cookieStore = dashboardCookieStoreFor(connectionId),
bearerAuth = bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
val base = dashboardHttpClientFactory(
dashboardCookieStoreFor(connectionId),
bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
)
return DashboardApiClient(
baseUrl = dashboardUrl,
@@ -167,9 +172,9 @@ class UpstreamTransportController(
* no active connection (the standard-voice probe path).
*/
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient {
val base = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let {
val base = dashboardHttpClientFactory(
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
activeConnectionIdProvider()?.let {
bearerAuthForTrustedDashboard(it, dashboardUrl)
},
)
@@ -219,9 +224,9 @@ class UpstreamTransportController(
disposeDashboardHttpClient(client)
dashboardHttpClientCache = null
}
val base = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let { activeId ->
val base = dashboardHttpClientFactory(
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
activeConnectionIdProvider()?.let { activeId ->
bearerAuthForTrustedDashboard(activeId, dashboardUrl)
},
)
@@ -250,10 +255,12 @@ class UpstreamTransportController(
}
private fun disposeDashboardHttpClient(client: okhttp3.OkHttpClient) {
client.dispatcher.cancelAll()
client.connectionPool.evictAll()
runCatching { client.cache?.close() }
client.dispatcher.executorService.shutdown()
shutdownOffMainThread("DashboardHttpClient-shutdown") {
client.dispatcher.cancelAll()
client.connectionPool.evictAll()
runCatching { client.cache?.close() }
client.dispatcher.executorService.shutdown()
}
}
// --- Gateway availability ----------------------------------------------

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