Compare commits

...
Author SHA1 Message Date
Bailey Dixon de8f5558c2 Merge origin/dev into fix/android-emulator-testing 2026-08-31 16:37:42 -04:00
Bailey Dixon adcf4ded79 Merge pull request #517 from Codename-11/fix/android-supervised-parent-secret
fix(android): require app-specific supervised parent access
2026-08-31 16:36:44 -04:00
Bailey Dixon 05d6ee4d7c Merge origin/dev into fix/android-emulator-testing 2026-08-31 16:25:48 -04:00
Bailey Dixon 41cbafddba Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 16:24:21 -04:00
Bailey Dixon 8632ced503 Merge pull request #516 from Codename-11/fix/android-on-demand-dispatch
fix(ci): route Android presets through registered workflow
2026-08-31 16:21:53 -04:00
Bailey Dixon ae18bbee24 Merge origin/dev into fix/android-emulator-testing
# Conflicts:
#	AGENTS.md
#	app/src/main/kotlin/com/hermesandroid/relay/network/upstream/DashboardApiClient.kt
#	app/src/main/kotlin/com/hermesandroid/relay/runtime/HermesRuntimeBinder.kt
#	app/src/main/kotlin/com/hermesandroid/relay/viewmodel/ChatViewModel.kt
#	app/src/test/kotlin/com/hermesandroid/relay/network/upstream/DashboardApiClientTest.kt
2026-08-31 16:13:34 -04:00
Bailey Dixon 55a838cb78 merge: refresh Android dispatcher with dev 2026-08-31 16:04:29 -04:00
Bailey Dixon d367cd3a24 Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 15:59:55 -04:00
Bailey Dixon 5bd0b2acaf Merge pull request #513 from Codename-11/fix/android-dashboard-history-auth-recovery
fix(android): recover Dashboard history auth failures
2026-08-31 15:59:09 -04:00
Bailey Dixon 6f0948ca01 Merge remote-tracking branch 'origin/dev' into fix/android-supervised-parent-secret 2026-08-31 15:58:43 -04:00
Bailey Dixon 541a7c078d fix(android): require app-specific supervised parent access 2026-08-31 15:51:20 -04:00
Bailey Dixon 8865a31013 fix(ci): route Android presets through registered workflow 2026-08-31 15:49:43 -04:00
Bailey Dixon a199c35377 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 15:47:36 -04:00
Bailey Dixon 6a495b6e06 Merge pull request #511 from Codename-11/chore/android-cloud-verification
ci(android): prefer cloud verification lanes
2026-08-31 15:43:32 -04:00
Bailey Dixon 105da550e7 docs: note Android history auth recovery 2026-08-31 15:32:40 -04:00
Bailey Dixon 23c06d60b9 ci(android): prefer cloud verification lanes 2026-08-31 15:29:06 -04:00
Bailey Dixon febc26fe35 Merge origin/dev into fix/android-emulator-testing 2026-08-31 15:12:55 -04:00
Bailey Dixon 28a906215d test(android): add managed emulator coverage 2026-08-31 15:12:44 -04:00
Bailey Dixon 1617f75f1a Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 14:32:44 -04:00
Bailey Dixon 78203fd8a1 Merge pull request #510 from Codename-11/fix/android-generated-image-retention
fix(android): retain generated image results
2026-08-31 14:03:44 -04:00
Bailey Dixon c519502551 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 13:38:13 -04:00
Bailey Dixon 814afc56da fix(android): retain generated image results 2026-08-31 13:37:22 -04:00
Bailey Dixon 1f055cb91f Merge pull request #507 from Codename-11/fix/android-supervised-gateway-salvage
fix(android): harden supervised Gateway setup
2026-08-31 13:36:26 -04:00
Bailey Dixon 936b9bed8a Merge pull request #508 from Codename-11/feature/android-release-notes-expansion
feat(android): make What's New a complete release record
2026-08-31 13:31:19 -04:00
Bailey Dixon dafa6f3a18 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 13:23:33 -04:00
Bailey Dixon 245362d58e Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion 2026-08-31 13:21:40 -04:00
Bailey Dixon 95e78e0657 Merge pull request #509 from Codename-11/chore/android-build-lane
chore(android): serialize Windows build lanes
2026-08-31 13:14:56 -04:00
Bailey Dixon 246d9f1010 Merge origin/dev into fix/android-dashboard-history-auth-recovery 2026-08-31 12:49:28 -04:00
Bailey Dixon e9f32673be fix(android): recover dashboard history auth failures 2026-08-31 12:49:13 -04:00
Bailey DixonandUpbeat7898 7b390fa99f fix(android): harden supervised gateway setup
Co-authored-by: Upbeat7898 <upbeat7898@noreply.git.meberthosting.de>
2026-08-31 12:47:41 -04:00
Bailey Dixon cd856da6a0 Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion
# Conflicts:
#	app/src/test/kotlin/com/hermesandroid/relay/screenshots/ChangelogHistoryScreenshotTest.kt
#	app/src/test/kotlin/com/hermesandroid/relay/screenshots/WhatsNewToastScreenshotTest.kt
2026-08-31 12:46:18 -04:00
Bailey Dixon 9a40aedb7d chore(android): serialize Windows build lanes 2026-08-31 12:46:03 -04:00
Bailey Dixon 30eb70daa3 Merge pull request #506 from Codename-11/fix/android-whats-new-tests
test(android): refresh v1.14 What's New assertions
2026-08-31 12:14:32 -04:00
Bailey Dixon 6be6cec201 test(android): refresh v1.14 What's New assertions 2026-08-31 12:03:24 -04:00
Bailey Dixon 4f5f3fac10 Merge remote-tracking branch 'origin/dev' into feature/android-release-notes-expansion
# Conflicts:
#	CHANGELOG.md
2026-08-31 11:43:28 -04:00
Bailey Dixon 7f7112caf2 feat(android): expand in-app release notes 2026-08-31 11:42:53 -04:00
Bailey Dixon 4c00e8edb7 Merge pull request #499 from Codename-11/dependabot/github_actions/dev/actions/setup-java-6
chore(deps): bump actions/setup-java from 5 to 6
2026-08-31 11:08:59 -04:00
Bailey Dixon 44f0acec94 Merge pull request #505 from Codename-11/fix/android-bot-chat-binding-lifecycle-refresh
fix(android): render Bot Chat history after binding
2026-08-31 11:08:15 -04:00
Bailey Dixonandlayerflex c8cd13e5bc fix(android): render bot chat history after binding
Preserve the route-owned ChatHandler as the rendered state source from first composition and cover fast/delayed history plus handler replacement and on-device lifecycle recovery.

Supersedes PR #453 while preserving contributor credit.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-31 11:56:27 +00:00
Bailey Dixon bca3cd0e48 fix(plugin): harden Git workspace path containment (#492) 2026-08-30 23:30:51 -04:00
87 changed files with 4980 additions and 1147 deletions
-38
View File
@@ -1,38 +0,0 @@
## Summary
<!-- Brief description of what this PR does -->
## Changes
-
## Verification
<!-- List the checks you ran, or explain why a check is not applicable. -->
-
## Lineage / contributor credit
<!--
If this PR salvages or supersedes earlier work, link every source PR and name
the original contributor(s). Preserve original commit authors where practical;
otherwise use verified Co-authored-by trailers. Write "N/A" for original work.
-->
- Source PR(s): N/A
- Attribution preserved by: N/A
## Checklist
- [ ] Target branch is `dev`, unless this is a `dev` → `main` release PR or a focused production-tag hotfix PR to `main`
- [ ] Android changes: lint and focused unit tests ran, or rationale is listed above
- [ ] Translation changes: locale status/review references are accurate, `python scripts/check-android-locales.py` ran, and device/emulator review is documented, or N/A
- [ ] Server changes: focused `python -m unittest ...` checks ran, or rationale is listed above
- [ ] Desktop changes: `npm run build` or a narrower documented check ran, or rationale is listed above
- [ ] Docs/site changes: docs build or link check ran, or rationale is listed above
- [ ] UI changes were tested on emulator/device or desktop surface when applicable
- [ ] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
- [ ] CHANGELOG.md updated (if user-facing)
- [ ] Public writing hygiene checked: no secrets, private infrastructure, personal names, or AI/process narration
- [ ] Salvaged work links the source PR and preserves contributor authorship, or N/A
+5 -4
View File
@@ -5,9 +5,8 @@ not `AGENTS.md`) picks up the project's agent guidance.
**Read [AGENTS.md](../AGENTS.md) first — it is the single source of truth**
for agent guidance: the entry point, the non-negotiables, and the public-repo
writing hygiene. It links on to `CLAUDE.md` for the deep reference
(architecture, upstream Hermes API, repository layout, per-language code style,
the dev loop, and the Key Files map). Follow those; don't restate them here.
writing hygiene. `CLAUDE.md` imports that same canonical file. Follow
`AGENTS.md` and its linked project records; don't restate them here.
Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
@@ -17,6 +16,8 @@ Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
- **Conventional Commits**, `main`/`dev` branching — feature branches off
`dev`, `--no-ff` merges, tags cut from `main`.
- **Android:** Jetpack Compose (no XML), kotlinx.serialization (no Gson),
OkHttp (no Ktor), `wss://` only; run `./gradlew lint` before pushing Kotlin.
OkHttp (no Ktor), `wss://` only. Narrow local checks use the Android lane;
pushed exact SHAs prefer `Android On-Demand` for heavy verification; full
local pre-push remains an explicit fallback.
- **Public repo:** no personal names, no private infrastructure, no
AI/assistant self-narration in committed prose.
+4 -1
View File
@@ -18,8 +18,11 @@ function classifyCiPaths(paths) {
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
'scripts/check-android-collection-apis.py', 'scripts/check-android-native-compat.py',
'scripts/check-android-release-notes.py',
'scripts/android-lane.ps1', 'scripts/android-prepush.py', 'scripts/dev.bat', 'scripts/dev.sh',
'scripts/tests/android_prepush_test.py',
'scripts/tests/check_android_native_compat_test.py',
'scripts/tests/check_android_release_notes_test.py', '.github/workflows/ci-android.yml',
'scripts/tests/check_android_release_notes_test.py',
'.github/workflows/android-on-demand.yml', '.github/workflows/ci-android.yml',
'.github/workflows/play-preflight-android.yml',
'.github/workflows/approve-release-android.yml',
'.github/workflows/release-android.yml',
@@ -18,6 +18,12 @@ assert.deepEqual(classifyCiPaths(['relay-core/src/main/kotlin/Wire.kt']), { ...n
assert.deepEqual(classifyCiPaths(['scripts/check-android-release-notes.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/check-android-native-compat.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_native_compat_test.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/android-lane.ps1']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/android-prepush.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/dev.bat']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/dev.sh']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['scripts/tests/android_prepush_test.py']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['.github/workflows/android-on-demand.yml']), { ...none, android: true });
assert.deepEqual(classifyCiPaths(['plugin/relay/server.py']), { ...none, plugin: true });
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
assert.deepEqual(classifyCiPaths(['user-docs/index.md']), { ...none, docs: true });
+226
View File
@@ -0,0 +1,226 @@
name: Android On-Demand
run-name: Android ${{ inputs.preset }} · ${{ inputs.head_sha }}
on:
workflow_call:
inputs:
head_sha:
required: true
type: string
preset:
required: true
type: string
permissions:
contents: read
concurrency:
group: android-on-demand-${{ inputs.head_sha }}-${{ inputs.preset }}
cancel-in-progress: false
jobs:
validate:
name: Validate exact SHA
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Validate input shape
shell: bash
env:
REQUESTED_SHA: ${{ inputs.head_sha }}
REQUESTED_PRESET: ${{ inputs.preset }}
run: |
if [[ ! "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]; then
echo "head_sha must be a full lowercase 40-character commit SHA" >&2
exit 2
fi
case "$REQUESTED_PRESET" in
focused|lint|assemble-debug|release-smoke|all-final) ;;
*)
echo "unsupported Android preset: $REQUESTED_PRESET" >&2
exit 2
;;
esac
- name: Checkout exact commit
uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
fetch-depth: 1
- name: Confirm checkout identity
shell: bash
env:
REQUESTED_SHA: ${{ inputs.head_sha }}
run: test "$(git rev-parse HEAD)" = "$REQUESTED_SHA"
focused:
name: Focused Android checks
needs: validate
if: ${{ inputs.preset == 'focused' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Run repository checks and focused sideload tests
run: python3 scripts/android-prepush.py --skip-lint
- name: Run the same focused tests for Google Play
shell: bash
run: |
mapfile -t focused_tests < <(python3 -c \
"import runpy; print(*runpy.run_path('scripts/android-prepush.py')['FOCUSED_TESTS'], sep='\n')")
test_args=()
for test_name in "${focused_tests[@]}"; do
test_args+=(--tests "$test_name")
done
./gradlew :app:testGooglePlayDebugUnitTest "${test_args[@]}" --console=plain
- name: Upload failed test reports
uses: actions/upload-artifact@v7
if: failure()
with:
name: focused-test-reports-${{ inputs.head_sha }}
path: app/build/reports/tests/
if-no-files-found: ignore
retention-days: 7
lint:
name: Android lint
needs: validate
if: ${{ inputs.preset == 'lint' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Validate Android repository inputs
run: |
python3 scripts/check-android-locales.py
python3 scripts/check-user-docs-locales.py
python3 scripts/check-android-collection-apis.py
python3 scripts/check-android-release-notes.py
python3 scripts/check-version-tracks.py
if [[ -f scripts/tests/android_prepush_test.py ]]; then
python3 -m unittest scripts.tests.android_prepush_test
fi
python3 -m unittest scripts.tests.check_android_release_notes_test
python3 -m unittest scripts.tests.check_android_native_compat_test
- name: Run Android lint
run: ./gradlew lint --console=plain
- name: Upload lint reports
uses: actions/upload-artifact@v7
if: always()
with:
name: lint-reports-${{ inputs.head_sha }}
path: app/build/reports/lint-results*
if-no-files-found: ignore
retention-days: 7
assemble-debug:
name: Assemble both debug flavors
needs: validate
if: ${{ inputs.preset == 'assemble-debug' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Build debug APKs
run: ./gradlew assembleDebug --console=plain
- name: Verify packaged native compatibility
run: |
python3 scripts/check-android-native-compat.py \
app/build/outputs/apk/googlePlay/debug/*.apk \
app/build/outputs/apk/sideload/debug/*.apk
- name: Upload debug APKs
uses: actions/upload-artifact@v7
with:
name: debug-apks-${{ inputs.head_sha }}
path: app/build/outputs/apk/*/debug/*.apk
if-no-files-found: error
retention-days: 7
release-smoke:
name: Release build smoke
needs: validate
if: ${{ inputs.preset == 'release-smoke' || inputs.preset == 'all-final' }}
runs-on: ubuntu-latest
timeout-minutes: 35
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.head_sha }}
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v6.3.0
with:
cache-read-only: true
- name: Build release bundles and APKs
run: ./gradlew bundleRelease assembleRelease --console=plain
- name: Scan release DEX for unsupported collection APIs
run: |
python3 scripts/check-android-collection-apis.py \
--apk app/build/outputs/apk/googlePlay/release/*.apk \
--apk app/build/outputs/apk/sideload/release/*.apk
- name: Verify packaged native compatibility
run: |
python3 scripts/check-android-native-compat.py \
app/build/outputs/apk/googlePlay/release/*.apk \
app/build/outputs/apk/sideload/release/*.apk
- name: Upload release smoke artifacts
uses: actions/upload-artifact@v7
with:
name: release-smoke-${{ inputs.head_sha }}
path: |
app/build/outputs/apk/*/release/*.apk
app/build/outputs/bundle/**/*.aab
if-no-files-found: error
retention-days: 7
+11 -4
View File
@@ -30,6 +30,11 @@ on:
- "gradle.properties"
- "gradlew"
- "gradlew.bat"
- "scripts/android-lane.ps1"
- "scripts/android-prepush.py"
- "scripts/dev.bat"
- "scripts/dev.sh"
- "scripts/tests/android_prepush_test.py"
- "scripts/check-android-locales.py"
- "scripts/android-locale-harness.py"
- "scripts/check-android-collection-apis.py"
@@ -38,6 +43,7 @@ on:
- "scripts/tests/check_android_native_compat_test.py"
- "scripts/tests/check_android_release_notes_test.py"
- ".github/workflows/ci-android.yml"
- ".github/workflows/android-on-demand.yml"
- ".github/workflows/play-preflight-android.yml"
- ".github/workflows/approve-release-android.yml"
- ".github/workflows/release-android.yml"
@@ -61,7 +67,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -80,6 +86,7 @@ jobs:
- name: Validate Android release notes
run: |
python3 scripts/check-android-release-notes.py
python3 -m unittest scripts.tests.android_prepush_test
python3 -m unittest scripts.tests.check_android_release_notes_test
- name: Test Android native compatibility checker
@@ -101,7 +108,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -151,7 +158,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -215,7 +222,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+30 -9
View File
@@ -20,13 +20,25 @@ on:
description: "Exact candidate commit to check"
required: true
type: string
android_preset:
description: "Optional Android-only compute lane"
required: false
default: auto
type: choice
options:
- auto
- focused
- lint
- assemble-debug
- release-smoke
- all-final
permissions:
contents: read
pull-requests: read
concurrency:
group: ci-required-${{ github.ref }}
group: ci-required-${{ github.event_name == 'workflow_dispatch' && format('{0}-{1}', inputs.head_sha, inputs.android_preset) || github.ref }}
cancel-in-progress: true
jobs:
@@ -113,33 +125,41 @@ jobs:
android:
needs: changes
if: needs.changes.outputs.android == 'true'
if: needs.changes.outputs.android == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-android.yml
android_on_demand:
needs: changes
if: github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto'
uses: ./.github/workflows/android-on-demand.yml
with:
head_sha: ${{ inputs.head_sha }}
preset: ${{ inputs.android_preset }}
desktop:
needs: changes
if: needs.changes.outputs.desktop == 'true'
if: needs.changes.outputs.desktop == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-desktop.yml
plugin:
needs: changes
if: needs.changes.outputs.plugin == 'true'
if: needs.changes.outputs.plugin == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-plugin.yml
dashboard:
needs: changes
if: needs.changes.outputs.dashboard == 'true'
if: needs.changes.outputs.dashboard == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-dashboard.yml
contract:
needs: changes
if: needs.changes.outputs.contract == 'true'
if: needs.changes.outputs.contract == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
uses: ./.github/workflows/ci-contract.yml
docs:
name: Build public docs
needs: changes
if: needs.changes.outputs.docs == 'true'
if: needs.changes.outputs.docs == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
runs-on: ubuntu-latest
defaults:
run:
@@ -161,11 +181,12 @@ jobs:
guard:
name: Required checks
if: always()
needs: [changes, android, desktop, plugin, dashboard, contract, docs]
needs: [changes, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
runs-on: ubuntu-latest
env:
CHANGES_RESULT: ${{ needs.changes.result }}
ANDROID_RESULT: ${{ needs.android.result }}
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
DESKTOP_RESULT: ${{ needs.desktop.result }}
PLUGIN_RESULT: ${{ needs.plugin.result }}
DASHBOARD_RESULT: ${{ needs.dashboard.result }}
@@ -176,7 +197,7 @@ jobs:
shell: bash
run: |
failed=0
for check in CHANGES ANDROID DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
for check in CHANGES ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
result_var="${check}_RESULT"
result="${!result_var}"
echo "$check: $result"
+1 -1
View File
@@ -70,7 +70,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+1 -1
View File
@@ -68,7 +68,7 @@ jobs:
fi
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+2 -2
View File
@@ -137,7 +137,7 @@ jobs:
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
@@ -176,7 +176,7 @@ jobs:
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+1 -1
View File
@@ -83,7 +83,7 @@ jobs:
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
- name: Set up JDK 17
uses: actions/setup-java@v5
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: 17
+18 -10
View File
@@ -7,12 +7,15 @@ coding agent (Claude Code, Codex, Cursor, etc.).
This file is the provider-neutral canonical agent context. Read it before
touching code, then `docs/spec.md` and `docs/decisions.md`. Provider adapters
such as **[CLAUDE.md](CLAUDE.md)** may add tool-specific guidance, but they do
not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
such as **[CLAUDE.md](CLAUDE.md)** import this file instead of duplicating
policy. They do not redefine the branch, release, hotfix, or verification
contract here and in `RELEASE.md`.
- Release process → **[RELEASE.md](RELEASE.md)**
- Contributor setup → **[CONTRIBUTING.md](CONTRIBUTING.md)**
- Gateway/session/reconnect testing → **[docs/gateway-contract-testing.md](docs/gateway-contract-testing.md)**
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
@@ -83,16 +86,21 @@ PR; never resolve those cases by choosing a side automatically.
Version bumps happen only on a release-prep branch targeting `dev`, and
production tags are cut only from `main`.
- **Android:** Jetpack Compose only (no XML), kotlinx.serialization (no Gson),
OkHttp (no Ktor), `wss://` only. Run `./gradlew lint` before pushing Kotlin.
For interactive device-review loops, run focused tests plus the affected
assemble/install task; run the full affected-variant lint once when the
combined candidate is final, or earlier only for lint-sensitive resource,
manifest, dependency, or build-configuration changes. Do not repeat full
variant lint after every small Kotlin iteration.
OkHttp (no Ktor), `wss://` only. While editing, use only the narrow local
compile or focused test needed for feedback, through `scripts/android-lane.ps1`
on Windows. Once an exact commit is already pushed, prefer the `Android
On-Demand` workflow for lint, the focused shards, both-flavor assemblies, and
release smoke; isolated cloud jobs may run concurrently. Do not push solely
to obtain cloud compute without push authorization, and do not duplicate a
preset already running for the same SHA. Full local verification remains
available through `scripts/dev.bat prepush` (or `./scripts/dev.sh prepush`)
when explicitly wanted or when cloud execution is unavailable.
Physical-device checks and APK installation remain separately owned local
evidence.
- **Plugin (Python 3.11+):** aiohttp + asyncio (no threading), type hints
everywhere, structured `logging` (no `print`). **Desktop CLI (Node ≥21):**
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Full
per-language style and the dev loop live in CLAUDE.md → "Code Style".
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Contributor
commands and the development loop live in `CONTRIBUTING.md`.
## Review guidelines
+12
View File
@@ -6,6 +6,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
## [Unreleased]
### Changed
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
### Fixed
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
## [Android 1.14.0] - 2026-08-30
### Added
+1 -525
View File
@@ -1,525 +1 @@
# Hermes-Relay — Claude Code Adapter
> Read [AGENTS.md](AGENTS.md) first. It is the provider-neutral canonical agent
> context. Branch, release, staging, and hotfix rules live in `AGENTS.md` and
> [RELEASE.md](RELEASE.md); this file only adds Claude-specific project and tool
> guidance. Then read `docs/spec.md` and `docs/decisions.md`.
## What This Is
A native Android app (Kotlin + Jetpack Compose) paired with an optional Python relay plugin/server (aiohttp) for the Hermes agent platform. Vanilla Hermes chat, Manage, and dashboard voice work against unmodified upstream Hermes. The Relay plugin adds phone control, terminal, remote desktop tooling, extra voice engines, and dashboard Relay management via the official Hermes web dashboard.
**Current state:** Reference latest released version for stable state and current dev branch for working state. The default no-plugin path supports chat, Manage, and voice on vanilla upstream Hermes. Chat auto-prefers the dashboard `/api/ws` gateway transport when Manage auth is ready, then falls back to API-server SSE routes. Vanilla Hermes voice uses dashboard `/api/audio/*` with the Manage session. Relay remains an additive power path for terminal, bridge/device control, notification companion, extra/provider-native voice, remote access, and desktop tooling. Two Android product flavors ship: `googlePlay` (conservative, no unattended Device Control surface) and `sideload` (full-capability).
## Architecture
```
Phone (WS) -> Hermes dashboard (:9119) [vanilla Hermes gateway chat, live thinking]
Phone (HTTP/SSE) -> Hermes API Server (:8642) [vanilla Hermes chat fallback, sessions, runs]
Phone (HTTP) -> Hermes dashboard (:9119) [vanilla Hermes Manage + voice]
Phone (WSS/HTTP) -> Relay plugin/server (:8767) [optional bridge, terminal, relay voice, remote tools]
```
The Vanilla Hermes path must stay upstream-only. API-server bearer auth and dashboard cookie auth are separate. Terminal and bridge require Relay pairing; Vanilla Hermes chat, Manage, and dashboard voice must not.
### Upstream Hermes API Reference
**IMPORTANT:** Always verify endpoints against the actual hermes-agent source (`gateway/platforms/api_server.py`). The upstream repo is the source of truth — not our docs, not our memory, not assumptions from other frontends.
**Vanilla Hermes endpoints (confirmed in hermes-agent source):**
| Endpoint | Purpose | Tool Call Format |
| --------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `POST /v1/chat/completions` | OpenAI-compatible chat (stream=true for SSE) | Inline markdown text (``💻 terminal``) — no separate tool events |
| `POST /v1/runs` | Start an agent run | Returns `run_id` |
| `GET /v1/runs/{run_id}/events` | SSE stream of run lifecycle events | **Structured events**: `tool.started`, `tool.completed`, `message.delta`, `reasoning.available`, `run.completed`, `run.failed` |
| `POST /v1/responses` | OpenAI Responses API format | Structured `function_call` objects (non-streaming only) |
| `GET /v1/capabilities` | Machine-readable feature + endpoint discovery | Use before assuming optional surfaces exist |
| `GET /v1/models` | List available models | — |
| `GET /v1/skills` | Read-only skill list for the API-server agent | `{"object":"list","data":[...]}` |
| `GET /v1/toolsets` | Read-only API-server toolset inventory | `{"object":"list","platform":"api_server","data":[...]}` |
| `GET/POST/PATCH/DELETE /api/sessions/*` | Native session CRUD, messages, fork, sync chat, SSE chat | Upstream merged via NousResearch/hermes-agent PR #33134 |
| `GET /health` | Health check | — |
| `GET/POST/PATCH/DELETE /api/jobs/*` | Cron job management (api_server surface) | — |
**Compatibility endpoints (not all native upstream API-server routes):**
Upstream main now contains the focused session-control API (`#33134`) and read-only skills/toolsets (`#33016`). The original broad PR [#8556](https://github.com/NousResearch/hermes-agent/pull/8556) was closed as superseded. Keep these distinctions straight:
1. **Native upstream** — `/api/sessions`, `/api/sessions/{id}/messages`, `/api/sessions/{id}/chat`, `/api/sessions/{id}/chat/stream`, `/v1/capabilities`, `/v1/skills`, and `/v1/toolsets` exist in current `gateway/platforms/api_server.py`.
2. **Bootstrap compatibility** (`plugin/hermes_relay_bootstrap/`) — monkey-patches aiohttp on startup via `.pth` file, injecting only compatibility-only surfaces (session search, memory, legacy skill detail/toggle, config, available-models, slash middleware). Sessions CRUD/messages/fork and the legacy skills list are **retired** — native upstream owns them (#33134/#33016) and the bootstrap carries no fallback for old builds. Native routes still win per method/path for the remaining set. The repo-root `hermes_relay_bootstrap/` package is a legacy import shim.
3. **Legacy fork branches** — useful as lineage only. Do not cite `feat/session-api` / `#8556` as the current upstream contract.
| Endpoint | Purpose | Provided by |
| -------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
| `GET /api/sessions` (CRUD) | Session list/create/rename/delete/fork | Native upstream (#33134); bootstrap injection retired |
| `GET /api/sessions/{id}/messages` | Conversation history | Native upstream (#33134); bootstrap injection retired |
| `POST /api/sessions/{id}/chat` | Synchronous session chat | Native upstream (#33134) |
| `POST /api/sessions/{id}/chat/stream` | Session-based SSE chat | Native upstream (#33134); bootstrap does NOT inject |
| `GET /v1/skills`, `GET /v1/toolsets` | Read-only skill/toolset discovery | Native upstream (#33016) |
| `GET /api/sessions/search` | Full-text message search | Bootstrap/fork legacy; not in current upstream main |
| `GET /api/config`, `PATCH /api/config` | Personalities + model config | Bootstrap/fork legacy or dashboard web-server surface; not current API-server upstream |
| `GET /api/skills/{name}` | Legacy skill detail | Bootstrap compat; list (`GET /api/skills`) retired — use native `/v1/skills` |
| `PUT /api/skills/toggle` | Enable/disable installed skill | `hermes_cli/web_server.py` dashboard surface; bootstrap stub returns 501 |
| `GET/POST/PATCH/DELETE /api/memory` | Memory CRUD | Bootstrap/fork legacy; not current API-server upstream |
| `GET /api/available-models` | Provider model list | Bootstrap/fork legacy; not current API-server upstream |
The Android client probes per-endpoint capability via `HermesApiClient.probeCapabilities()` (returns `ServerCapabilities`). When `streamingEndpoint = "auto"`, `ConnectionViewModel.resolveStreamingEndpoint()` picks `sessions`, `completions`, or `runs` based on the capability snapshot.
**Dashboard web server (separate surface — standard Manage / Desktop remote gateway):**
hermes-agent ships a second web server at `hermes_cli/web_server.py` that hosts the React admin dashboard at `hermes_cli/web_dist/`. It has its **own** `/api/*` routes that **do not live on `api_server.py`** — notably: `GET/PUT /api/config` (full tree), `GET /api/config/schema`, `GET /api/config/defaults`, `GET/PUT /api/config/raw` (YAML text), `GET/PUT/DELETE /api/env` + `POST /api/env/reveal`, `PUT /api/skills/toggle`, `/api/cron/jobs/*` (different shape from `/api/jobs/*`), `/api/providers/oauth/*`, `/api/dashboard/themes`, `/api/dashboard/plugins`, `/api/model/info` + `/api/model/options` + `POST /api/model/set`, `/api/profiles/*` (CRUD, `POST /api/profiles/active`, per-profile soul/description/model), `/api/mcp/*`, `/api/logs`, `/api/analytics/usage`, and `**POST /api/audio/transcribe` + `POST /api/audio/speak`** (base64 data-url contract, built for hermes-desktop voice). The API server has **no audio routes** — its `/v1/capabilities` advertises `audio_api: false`; PR #8199 (`/v1/audio/*`) is the canonical future surface but is unmerged. Android's **Vanilla Hermes (no-plugin) voice** therefore rides this dashboard surface via `StandardHermesVoiceClient` with the per-connection dashboard cookie session (Manage sign-in unlocks voice); `AutoVoiceAudioClient` prefers Relay when paired and falls back to standard.
Current upstream supports two auth modes on this surface. Loopback dashboards still use the injected `window.__HERMES_SESSION_TOKEN__` path. Remote/non-loopback dashboards use the Desktop-style dashboard auth gate: `/api/status` advertises `auth_required` and providers, `/auth/password-login` handles password providers, `/auth/login?provider=...` handles Nous/OIDC redirects, `/api/auth/me` returns the verified session, and `/api/auth/ws-ticket` mints a short-lived ticket for `/api/ws` / `/api/pty`. This dashboard session is **not** an `API_SERVER_KEY`. Android uses it for Manage, Vanilla Hermes voice, and the gateway chat transport. `/api/ws` is backed by `tui_gateway/server.py` (what hermes-desktop + the Ink TUI speak) and is the only upstream surface with **live** `reasoning.delta`/`thinking.delta` streaming; the api_server SSE paths remain the SSE fallback. Relay-only capabilities remain behind Relay pairing. **Do not proxy dashboard auth or dashboard admin APIs over the relay.**
**Tool call rendering paths:**
1. **Runs API** — Emits `tool.started`/`tool.completed` as real SSE events → `ToolProgressCard` in real-time.
2. **Sessions API** — Native upstream emits structured SSE (`run.started`, `message.started`, `assistant.delta`, `tool.progress`, `tool.started/completed/failed`, `assistant.completed`, `run.completed`, `done`). `run.completed.messages` can reconcile authoritative per-turn transcript.
3. **Annotation parser** — Fallback for servers emitting inline markdown annotations (``💻 terminal``).
## Key Instructions
- **Vanilla Hermes path = upstream-only.** The default (no-plugin) connection path — gateway/API chat, Manage, and Vanilla Hermes voice via the dashboard surface — must work against **unmodified upstream hermes-agent**: no fork patches, no bespoke server config as a dependency. The app ships on Google Play to users whose servers we don't control. Features that need server-side changes go through upstream PRs (with graceful degradation until merged) or live behind the opt-in relay plugin.
- **Always verify upstream before assuming an endpoint exists.** Check `gateway/platforms/api_server.py` in hermes-agent. If an endpoint isn't there, document whether bootstrap injects it or it requires the fork.
- If we use a non-standard endpoint, ensure `probeCapabilities()` covers it and the auto-resolver degrades gracefully.
- **Bootstrap maintenance:** Retire `plugin/hermes_relay_bootstrap/` per surface. Done: sessions CRUD/messages/fork and the legacy skills list are retired from the bootstrap (native upstream #33134/#33016, no old-build fallback kept). Remaining: config, memory, legacy skill detail/toggle, available-models, session search, and slash middleware still need explicit replacement decisions before full removal.
## Repository Layout
```
hermes-android/
├── app/src/main/kotlin/com/hermesandroid/relay/
│ ├── ui/ # Screens, components, theme
│ ├── network/ # ConnectionManager, ChannelMultiplexer, handlers
│ ├── auth/ # AuthManager (pairing + tokens)
│ ├── viewmodel/ # ChatViewModel, ConnectionViewModel
│ ├── data/ # ChatMessage, ToolCall models, FeatureFlags
│ ├── audio/ # VoiceRecorder, VoicePlayer, VoiceSfxPlayer
│ ├── voice/ # VoiceViewModel, VoiceBridgeIntentHandler
│ ├── accessibility/ # HermesAccessibilityService, ScreenReader, ActionExecutor
│ ├── bridge/ # BridgeSafetyManager, BridgeForegroundService, BridgeStatusOverlay
│ └── notifications/ # HermesNotificationCompanion
├── relay-core/ ← [EXPERIMENTAL] Quest/XR shared core lib (com.axiomlabs.hermesrelay.core) — pairing, transport, terminal, voice, wire
├── relay-ui/ ← [EXPERIMENTAL] Quest/XR shared Compose UI lib — sphere, terminal WebView, QR scanner
├── quest/ ← [EXPERIMENTAL] Meta Spatial SDK Quest/XR app (gradle includeBuild; in development, not shipped)
├── ui-preview/ ← Desktop Compose Hot Reload harness for PC UI iteration (NOT shipped; shares MorphingSphereCore)
├── desktop/ ← Node thin-client CLI (`@hermes-relay/cli`)
│ ├── bin/hermes-relay.js # #!/usr/bin/env node shim → dist/cli.js
│ ├── src/
│ │ ├── cli.ts # argv parser + subcommand dispatcher (bare → shell)
│ │ ├── commands/ # chat, shell, pair, status, tools, devices
│ │ ├── banner.ts # contextual connect line (LAN / Tailscale / Plain / Secure)
│ │ ├── renderer.ts # GatewayEvent → plain-line stdout formatter (chat only)
│ │ ├── endpoint.ts # ADR 24 EndpointCandidate + role helpers
│ │ ├── pairingQr.ts # v3 QR decode + priority-raced reachability probe
│ │ ├── pairing.ts # readline 6-char prompt + payload validator
│ │ ├── credentials.ts # token → pair-qr → code → stored → prompt precedence
│ │ ├── certPin.ts # TOFU SPKI sha256 extract / pinKey / compare
│ │ ├── tools/ # desktop.command router + fs/terminal/search handlers + consent
│ │ ├── transport/ # RelayTransport (reconnect state machine + TLS probe TOFU)
│ │ └── lib/ # gracefulExit, rpc, circularBuffer (vendored)
│ └── scripts/ # install.sh + install.ps1 curl/iwr one-liners
├── website/ ← Astro product/marketing site (static Coolify/Nixpacks deployment)
├── plugin/ ← Hermes agent plugin
│ ├── android_tool.py # 18 android_* tool handlers
│ ├── pair.py # QR pairing implementation
│ ├── relay/ # Canonical WSS relay (server.py, auth.py, channels/, media.py, voice.py)
│ ├── tools/ # android_navigate.py, android_notifications.py
│ └── dashboard/ # hermes-agent dashboard plugin — manifest, React UI, FastAPI proxy
├── relay_server/ ← Thin compat shim → plugin.relay (legacy entrypoint)
├── hermes_relay_bootstrap/ ← Legacy import shim for older startup hooks
├── skills/devops/hermes-relay-pair/ ← /hermes-relay-pair slash command
├── scripts/ ← dev.bat, bridge-smoke.sh, bump-version.sh
└── docs/ ← spec, decisions, security, relay-server, mcp-tooling
```
## Project Conventions
### File Structure
- **Root-level:** README.md, CLAUDE.md, AGENTS.md, DEVLOG.md, TODO.md, .gitignore
- **docs/** — spec, decisions, security, and any other long-form documentation
- **DEVLOG.md** — update at end of each work session with what was done + verification (the factual record of *what happened*). It churns; do NOT park forward work here.
- **TODO.md** — the single home for follow-ups / deferred work / known gaps ("what's next"). Record them here — never buried in DEVLOG or scattered through code/doc comments where they get lost.
- **CLAUDE.md hygiene:** Key Files entries must stay one line — implementation detail belongs in the file or `docs/`. Run `/revise-claude-md` after feature-heavy sessions to trim drift.
### Public-repo writing hygiene
This is a **public, distributed repo** — every committed file (CHANGELOG, DEVLOG, README, docs, release notes) is public-facing. Write accordingly:
- **No personal names** in prose — attribute impersonally ("a user reported", "observed"). Author identity lives in git history + the signing cert, not the changelog.
- **No private infrastructure** — real server hostnames/IPs, internal deployment names, `~/SYSTEM.md` contents. (Generic example IPs like `192.168.1.100` in setup docs are fine.)
- **No AI/assistant process self-narration** — no "I should have…", no course-correction confessionals. State the technical conclusion, not the path to it.
- **No internal jargon / fork-branch plumbing** in user-facing notes — keep *what changed*, drop *where we staged it*.
- **CHANGELOG** uses Keep-a-Changelog grouping (Added / Changed / Fixed). Detail may accumulate during iteration, but at **release-prep the version block is condensed to crisp public bullets** (1–2 lines each) — deep "how we debugged it" stays in commits/DEVLOG. See [RELEASE.md](RELEASE.md) §2 "Scrub for public distribution".
- **DEVLOG.md** is a committed, factual engineering log — what changed, why, and verification — depersonalized and third-person, not a diary.
### Code Style — Android (Kotlin)
- **Jetpack Compose** — no XML layouts. Material 3 / Material You.
- **kotlinx.serialization** — not Gson. Type-safe, faster.
- **OkHttp** for WebSocket + SSE — `okhttp` for WSS relay, `okhttp-sse` for API streaming
- **Single-activity** — Compose Navigation for all routing
- **Namespace (Kotlin source tree):** `com.hermesandroid.relay` — stable, drives on-disk layout + class FQCNs
- **applicationId:** `com.axiomlabs.hermesrelay` (googlePlay), `com.axiomlabs.hermesrelay.sideload` (sideload)
- **Min SDK 26, Target SDK 35, Compile SDK 37** / **Kotlin 2.0+**, JVM toolchain 17
### Code Style — Desktop CLI (Node/TypeScript)
- **Node ≥21** — uses built-in global `WebSocket` (no `ws`/`undici` dep). Strict TS, ES modules, `NodeNext` resolution.
- **Zero runtime deps** — `@types/node` + `tsx`/`rimraf`/`typescript` are devDeps only. Ship compiled `dist/`, not tsx.
- **One binary, subcommands** — idiomatic for Node CLIs (codex, continue, vite pattern). Bare invocation is `chat`.
- **Vendor-for-now** — transport/gateway/types are copied verbatim from `hermes-agent-tui-smoke/ui-tui/src/` with a header note. Extract to a shared package when the TUI and CLI stabilize.
- **Dev loop:** `npx tsx src/cli.ts <args>` (no rebuild). `npm run build` + `npm link` before pushing to verify the bin shim. Never ship tsx in the published tarball — pre-build with `tsc` so Windows `npm install -g` can cmd-shim the JS directly.
### Code Style — Server (Python)
- **aiohttp** — async, matches existing Hermes relay patterns
- **Type hints everywhere** — Python 3.11+ syntax
- **asyncio** — no threading; **structured logging** — use `logging`, not print()
### Git
- **Conventional Commits:** `feat`, `fix`, `docs`, `refactor`, `test`, `chore`
- **Branch/release policy:** follow the branch-contract table in `AGENTS.md` and
the executable release and hotfix procedures in `RELEASE.md`. Do not maintain
a Claude-specific parallel policy here.
### Testing
- **Android:** JUnit + Compose testing for UI, MockK for mocks
- **Gateway/session/reconnect work:** follow the on-demand scenario,
current-upstream conformance, Android instrumentation, and physical-proof
routing in `docs/gateway-contract-testing.md`; do not infer device behavior
from fixture or source checks.
- **Python:** `python -m unittest plugin.tests.test_<name>` — avoid bare `pytest` (conftest imports `responses` which may not be installed in the venv)
- **CI and release gates:** follow the repository-wide requirements in
`AGENTS.md` and `RELEASE.md`; Claude-specific guidance does not redefine them.
## Key Files
| File | Why |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `docs/spec.md` | Full specification — protocol, UI layouts, phases, dependencies |
| `docs/decisions.md` | Architecture decisions — framework choice, channel design, auth model |
| `docs/gateway-contract-testing.md` | On-demand reusable Gateway scenarios, upstream conformance, Android instrumentation, and ADB certification |
| `AGENTS.md` | Universal agent entry point — points here + the non-negotiables (standard-path, commits, writing hygiene) |
| `docs/mcp-tooling.md` | MCP server setup — android-tools-mcp + mobile-mcp; `android_*` tool usage patterns |
| **App — Core** | |
| `ui/RelayApp.kt` | Main scaffold (Scaffold + Compose nav); Chat is home — no mode strip, Manage/Bridge reached via Settings; `bottomBar` is a status pill, not a NavigationBar |
| `viewmodel/ChatViewModel.kt` | Chat orchestration — send, stream, cancel, slash commands |
| `viewmodel/ConnectionViewModel.kt` | Dual connection model (API + relay); `resolveStreamingEndpoint()`; derived `relayUiState` flow + `markPaired` hook stamp the active Connection |
| `viewmodel/RelayUiState.kt` | Shared sealed state for the relay row — 5 cases + `asBadgeState()` / `statusText()` extensions; 5s grace window before Stale |
| `network/HermesApiClient.kt` | Direct HTTP/SSE — `sendRunStream()`, `sendChatStream()`, `probeCapabilities()` |
| `network/GatewayChatClient.kt` | Gateway chat transport — JSON-RPC over dashboard `/api/ws` (tui_gateway); live `reasoning.delta`; fresh ws-ticket per connect; per-turn SSE fallback via `onPreflightFailure`; `prewarm()` (connect+resume off the send path); `setKeepAliveInBackground()` suppresses the 120s idle-close |
| `network/GatewayKeepAliveService.kt` | Opt-in `specialUse` foreground service (BOTH flavors; declared in main manifest; Play needs a Console FGS declaration) holding the process up so the gateway socket survives background/Doze; driven by ConnectionViewModel from the `KEY_GATEWAY_KEEP_ALIVE` toggle; stops on task-removal |
| `data/GatewayKeepAlivePrefs.kt` | Shared `KEY_GATEWAY_KEEP_ALIVE` pref key + `Context.setGatewayKeepAlive()` — used by ConnectionViewModel (StateFlow/setter) and the FGS Stop action |
| `network/GatewayEventMapper.kt` | Pure-JVM gateway event→callback mapping for one turn; unknown event types silently ignored; tui_gateway usage-key translation |
| `network/GatewayModels.kt` | `GatewayAvailability`, `ActiveTurnHandle`, `GatewayTurnCallbacks` (all members REQUIRED — forces dispatchOn main-thread wrap), `GatewayAsk`, `GatewaySubagentEvent`, `resolveStreamingEndpointPreference()` |
| `ui/components/ChatInputBar.kt` | Redesigned input bar — pill field, one trailing slot morphing Send/Voice/Stop/Steer/Queue, no slash button (long-press + opens palette) |
| `ui/components/SubagentLane.kt` | Per-taskIndex subagent progress lane — guide rail, compact tool rows, auto-collapse |
| `notifications/TurnCompleteNotifier.kt` | Turn-complete local notification when backgrounded — channel `chat_turn_complete`, cancel on resume, settings-gated |
| `network/ConnectionManager.kt` | WSS to relay with auto-reconnect; rebuilds OkHttpClient with fresh CertPinner on connect |
| `network/ChannelMultiplexer.kt` | Envelope routing by channel; `sendNotification()` for notification outbound |
| `network/handlers/ChatHandler.kt` | Chat message state, streaming events, tool annotation parser |
| `network/models/SessionModels.kt` | Session, message, SSE event data models |
| `data/FeatureFlags.kt` | Feature gating — DEV_MODE + DataStore overrides; `BuildFlavor` (googlePlay/sideload Tier flags) |
| **App — Auth** | |
| `auth/AuthManager.kt` | Wires SessionTokenStore + CertPinStore; parses auth.ok; `applyServerIssuedCodeAndReset()` |
| `auth/SessionTokenStore.kt` | Keystore (StrongBox) + EncryptedSharedPrefs fallback; lossless migration on upgrade |
| `auth/CertPinStore.kt` | TOFU cert pinning — SHA-256 SPKI per host:port in DataStore |
| `auth/PairedSession.kt` | PairedSession state + PairedDeviceInfo wire model |
| `data/Endpoint.kt` | `EndpointCandidate` / `ApiEndpoint` / `RelayEndpoint` — multi-endpoint pairing (ADR 24); `displayLabel()` for LAN/Tailscale/Public/Custom chips |
| `network/RelayHttpClient.kt` | OkHttp for /media, /sessions (list/revoke/extend), /health |
| **App — Bridge** | |
| `network/handlers/BridgeCommandHandler.kt` | Routes `bridge.command` → ActionExecutor; full path inventory + safety-rail integration |
| `viewmodel/BridgeViewModel.kt` | BridgeScreen VM — masterToggle, bridgeStatus, permissionStatus, activityLog |
| `bridge/BridgeSafetyManager.kt` | Connection-scoped capabilities + timed screen expiry + blocklist + destructive confirmation; unknown, denied, and expired commands fail closed |
| `bridge/BridgeCapabilities.kt` / `data/BridgeCapabilityPolicyRepository.kt` | Closed method/path registry + no-backup-bound per-Connection Always/Never/Timed policy; global safety vocabulary and timer duration remain in `BridgeSafetyPreferences.kt` |
| `ui/screens/BridgeScreen.kt` | Bridge cockpit — master → Agent access posture/setup → single Unattended Access control → capability-scoped Android readiness (expandable full matrix) → Advanced safety/full editor → activity log |
| `ui/components/BridgeAccessCards.kt` | Native access cockpit + first-use preset and screen-lease sheets (renewable idle limits or warned Until-off dedicated-device mode); preserves full permission/safety drilldowns while keeping selected policy/readiness above the fold |
| `ui/components/UnattendedAccessRow.kt` | Unattended toggle card (sideload); `enabled=masterEnabled`; inline `KeyguardDetectedAlert` |
| `ui/components/UnattendedGlobalBanner.kt` | 28dp amber strip at scaffold top when master+unattended on (sideload); tap → Bridge tab |
| `bridge/BridgeStatusOverlay.kt` | WindowManager overlay; `ConfirmationOverlayHost`; requires `SavedStateRegistryOwner` init order (CREATED→restore→RESUMED) |
| `accessibility/HermesAccessibilityService.kt` | AccessibilityService subclass; `@Volatile instance` singleton for BridgeCommandHandler |
| `accessibility/ScreenReader.kt` | UI tree → ScreenContent; `findNodeBoundsByText()`, `findFocusedInput()` |
| `accessibility/ActionExecutor.kt` | Gesture/text dispatch via GestureDescription + ACTION_SET_TEXT; pressKey maps vocab only |
| **App — Voice** | |
| `voice/VoiceViewModel.kt` | Voice turn state machine; TTS queue; `ignoreAssistantId`; `errorEvents: SharedFlow` |
| `audio/VoiceRecorder.kt` | MediaRecorder wrapper; perceptual amplitude curve; `.m4a` at 16kHz/64kbps |
| `audio/VoicePlayer.kt` | Media3 ExoPlayer (gapless TTS queue) + Visualizer; amplitude StateFlow; `awaitCompletion()` via coroutine; `audioSessionId` is a thread-safe `@Volatile` cache |
| `network/RelayVoiceClient.kt` | OkHttp for `/voice/transcribe`, `/synthesize`, `/config` |
| `voice/VoiceBridgeIntentHandler.kt` | Interface routing voice utterances to bridge; impls per flavor via factory |
| `voice/VoiceIntentClassifier.kt` | Regex phone-control classifier (sideload only); false-negatives preferred over false-positives |
| `ui/components/VoiceModeOverlay.kt` | Full-screen voice UI — MorphingSphere + VoiceWaveform + mic button |
| `ui/components/MorphingSphere.kt` | Compose renderer for the agent sphere — delegates math to `MorphingSphereCore` |
| `ui/components/MorphingSphereCore.kt` | Platform-agnostic sphere algorithm (`kotlin.math` only) — single source of truth; mirrored byte-for-byte in `preview/web/sphere.js` |
| `preview/web/` | Zero-dep browser harness — live `index.html` preview + `parity-check.mjs`; paired with `MorphingSphereCoreParityTest` (JVM) for struct/full checksum diffing |
| `user-docs/.vitepress/theme/components/SphereMark.vue` | Docs-site sphere embed — imports `preview/web/sphere.js` directly; autonomous fbm drift + pointer-proximity gaze/state blend; `<ClientOnly>` + `IntersectionObserver` + `prefers-reduced-motion` aware |
| **App — Media + Notifications** | |
| `util/MediaCacheWriter.kt` | `cacheDir/hermes-media/` LRU writer; returns FileProvider URIs |
| `util/MediaSaver.kt` | Save/share/open for chat media — MediaStore scoped-storage save (Pictures/Download `Hermes-Relay`, no perms on API 29+; pre-Q → share sheet); FileProvider share staging; remote-byte fetch; magic-byte image-MIME sniff for correct extensions |
| `ui/components/ChatImageViewer.kt` | Full-screen image viewer — pinch-zoom/pan (`detectTransformGestures`), double-tap 1×/2.5×, Share/Save/Close; `ChatImageViewerSource` decouples Coil-model/bitmap display from a suspend `bytesProvider` so Save keeps original bytes |
| `ui/components/InboundAttachmentCard.kt` | Discord-style attachment card for images/video/audio/pdf/text/generic; image tap → ChatImageViewer, file card long-press → Open/Share/Save menu |
| `ui/components/ChatImageContent.kt` | Parses `![alt](src)` out of assistant content; remote http(s) → Coil (tap → ChatImageViewer), server-local/failed → inline "can't render" notice with the path |
| `data/HermesCard.kt` | `CARD:{json}` envelope (ADR 26) — type/accent/fields/actions; kotlinx.serialization |
| `ui/components/HermesCardBubble.kt` | Rich-card renderer — accent stripe + FlowRow actions + dispatch stamp collapse |
| `viewmodel/CardDispatchSyncBuilder.kt` | Twin of VoiceIntentSyncBuilder — synthesizes card dispatches as `hermes_card_action` OpenAI pairs for session memory |
| `notifications/HermesNotificationCompanion.kt` | NotificationListenerService; cold-start buffer (50); forwards via ChannelMultiplexer |
| `util/RelayErrorClassifier.kt` | `classifyError(Throwable, context) → HumanError`; used by Voice/Chat/Connection |
| `util/TurnLatencyTracer.kt` | One `TurnLatency` INFO line per chat turn — `warm/cold` + `connect/session/submit/ttfe/ttft/done@…ms`; gateway + 3 SSE paths use it for desktop-comparable latency diagnosis; durations only |
| **Relay — Server** | |
| `plugin/relay/server.py` | Canonical relay — WSS + HTTP routes; bridge, media, voice, session, pairing handlers. `handle_pairing_mint` mirrors `pair.py:762` — top-level = API server, `relay.{url,code}` nested |
| `plugin/relay/auth.py` | PairingManager, SessionManager, RateLimiter; `math.inf` for never-expire |
| `plugin/relay/channels/bridge.py` | Bridge handler — `handle_command()` mints request_id, awaits response, 30s timeout |
| `plugin/relay/channels/notifications.py` | Bounded deque (100) of notification metadata; in-memory only |
| `plugin/relay/media.py` | MediaRegistry — LRU token store; `strict_sandbox` off by default for `/media/by-path` |
| `plugin/relay/voice.py` | Voice endpoints — transcribe, synthesize, voice_config; lazy tool imports |
| `plugin/relay/qr_sign.py` | HMAC-SHA256 QR signing; secret at `~/.hermes/hermes-relay-qr-secret`; canonical form preserves `endpoints` array order + role strings verbatim (ADR 24) |
| `plugin/relay/tailscale.py` | First-class Tailscale helper (ADR 25) — `status()` / `enable(port)` / `disable(port)` / `canonical_upstream_present()`; safe-absent via shell-out to `tailscale` CLI |
| `plugin/relay/_env_bootstrap.py` | Loads `~/.hermes/.env` before relay imports; called from both entry points |
| **Plugin — Tools + Installer** | |
| `plugin/tools/android_tool.py` | 18 `android_*` tool handlers (14 baseline + send_sms, call, search_contacts, return_to_hermes); `android_screenshot` first consumer of `register_media()` |
| `plugin/tools/android_navigate.py` | Vision-driven navigation loop; up to 20 iterations; `llm_gap` error until vision client wired |
| `plugin/pair.py` | QR payload builder + CLI; `build_payload(sign=True)`; `--register-code` fallback |
| `plugin/doctor.py` | `hermes relay doctor`; checks standard upstream API/dashboard reachability, Relay loopback state, plugin layout, and compat hook state |
| `plugin/compat.py` | `hermes relay compat status/install/remove`; owns the optional `hermes_relay_bootstrap.pth` lifecycle |
| `plugin/hermes_relay_bootstrap/` | Plugin-owned runtime compatibility patch — compat-only surfaces (session search, memory, skill detail/toggle, config, available-models, slash middleware); sessions + skills-list injection retired (#33134/#33016) |
| `install.sh` | Canonical installer — 6 steps; idempotent; drops `hermes-relay-update` shim |
| `uninstall.sh` | Canonical uninstaller; reverses install.sh; never touches `.env` or `state.db` |
| `hermes_relay_bootstrap/` | Legacy import shim for old `.pth` files and editable installs |
| **Plugin — Dashboard** | |
| `plugin/dashboard/manifest.json` | Declares tab, entry bundle, and FastAPI module for hermes-agent discovery |
| `plugin/dashboard/plugin_api.py` | FastAPI router proxying 5 routes to relay over loopback; `/pairing` body = API-server overrides (host/port/tls/api_key), relay URL auto-derived |
| `plugin/dashboard/src/index.jsx` | React root registering `hermes-relay` plugin with 4-tab shell |
| `plugin/dashboard/dist/index.js` | Committed IIFE bundle loaded verbatim by dashboard |
| **Desktop CLI** | |
| `desktop/package.json` | `@hermes-relay/cli` package manifest — Node ≥21, one `hermes-relay` bin, pre-built dist |
| `desktop/bin/hermes-relay.js` | Tiny shim: `import('../dist/cli.js').then(m => m.main())` + error surfacing |
| `desktop/src/chatAttach.ts` | captureClipboardImage / captureScreenshot / readImageFile; ships base64 to server via `image.attach.bytes` RPC before next prompt.submit |
| `desktop/src/cli.ts` | argv parser + subcommand dispatcher — bare → `shell` (PTY), positional-only → `chat`; command-scoped `--help` falls through to each command |
| `desktop/src/lib/theme.ts` | Shared ANSI palette + `colorEnabled()` + `Theme` (semantic helpers, `statusDot`) — single visual language; `--no-color`/`NO_COLOR`/TTY aware |
| `desktop/src/lib/table.ts` | Zero-dep column-aligned table renderer (ANSI-width aware, last column flexes to terminal width) — used by devices/sessions/audit |
| `desktop/src/lib/spinner.ts` | Stderr braille spinner for slow ops (pair probe, gateway connect); no-op when piped/quiet/json |
| `desktop/src/lib/usage.ts` | `UsageSpec` + `renderUsage`/`printUsage`/`unknownSubcommand` — per-subcommand `--help` + self-documenting sub-verb fallback |
| `desktop/src/lib/hints.ts` | `suggestedFix(err, ctx)` → next-step command (re-pair on auth fail, etc.); `formatError` renders error + hint |
| `desktop/src/lib/logo.ts` | Slim box-drawing "Hermes Relay" wordmark; shown atop `--help`, first-run welcome, REPL header, and `hermes-relay logo`; theme/no-color aware |
| `desktop/src/lib/auditLog.ts` | Local desktop-tool audit JSONL (`~/.hermes/desktop-audit.jsonl`); router appends per dispatch; backs `audit` command (relay's ring is loopback-only) |
| `desktop/src/lib/daemonStatus.ts` | Daemon heartbeat file (`~/.hermes/daemon-status.json`) + `isPidAlive` liveness; backs `daemon --status` |
| `desktop/src/commands/audit.ts` | `hermes-relay audit` — tails the local audit log into a table (WHEN/TOOL/STATUS/DETAIL); `--limit`, `--json` |
| `desktop/src/commands/relay.ts` | `hermes-relay relay info/security/context/queue` — relay-server management surface; info/security/queue loopback-only, context works remote with bearer; `queue` lists/cancels the agent→phone outbound buffer (`--clear` / `--cancel <id>`) |
| `desktop/src/commands/chat.ts` | REPL + one-shot + piped-stdin; `runOneTurn` returns `{promise, cancel}` for safe SIGINT; auto-wires `DesktopToolRouter` when consented |
| `desktop/src/commands/shell.ts` | Pipes the `terminal` relay channel to raw-mode stdin/stdout; post-attach `exec hermes` 350ms after tmux settles; `Ctrl+A .` detach / `Ctrl+A k` kill / `Ctrl+A Ctrl+A` literal |
| `desktop/src/commands/pair.ts` | Either 6-char code + `--remote`, or full v3 QR via `--pair-qr` — probes + picks endpoint, records role; `--grant-tools` (TTY prompt) / `--auto-grant-tools` (silent) stamp `toolsConsented` so `daemon` works without a `shell` round-trip |
| `desktop/src/commands/tools.ts` | `tools.list` RPC → enabled/available toolsets; `--verbose` lists individual tools |
| `desktop/src/commands/status.ts` | Local read of `~/.hermes/remote-sessions.json`; renders `grants:` + `expires:` + `route:`; `--json` redacts tokens, `--reveal-tokens` opts in |
| `desktop/src/commands/devices.ts` | Server-side session management — `GET/DELETE/PATCH /sessions` via `fetch` over http(s)://host:port; `list` / `revoke <prefix>` / `extend <prefix> --ttl <s>` |
| `desktop/src/banner.ts` | `buildConnectBanner({url, meta, endpointRole})` → "Connected via LAN (plain) — server 0.6.0"; `humanExpiry()` for TTL formatting |
| `desktop/src/endpoint.ts` | `EndpointCandidate` / `EndpointRole` types + `displayLabel()` — mirrors Android `data/Endpoint.kt` |
| `desktop/src/pairingQr.ts` | `decodePairingPayload` (JSON or base64), `payloadToCandidates` (v3 verbatim / v1–v2 synthesized), `probeCandidatesByPriority` (`Promise.any` within tier, `AbortSignal.any`, 4s timeout, 60s cache) |
| `desktop/src/certPin.ts` | `extractSpkiSha256(der)` via `crypto.X509Certificate` + `publicKey.export({type:'spki'})`; `pinKey(url)`, `comparePins()`, `isSecureUrl()` |
| `desktop/src/tools/router.ts` | `DesktopToolRouter.attach(relay)` — `onChannel('desktop')` dispatch under 30s `AbortController`; heartbeat enriched with host/platform/version/uptime_ms + sticky `last_error` for `desktop_health` |
| `desktop/src/tools/handlerSet.ts` | Single source of truth for the desktop tool map — `DESKTOP_HANDLERS` + `DESKTOP_ADVERTISED_TOOLS`; consumed by `chat.ts` / `shell.ts` / `daemon.ts` so adding a tool is a one-file change |
| `desktop/src/tools/consent.ts` | `ensureToolsConsent(url)` — stored per-URL in `toolsConsented`; TTY prompt; non-TTY fails closed |
| `desktop/src/tools/handlers/fs.ts` | `readFileHandler` / `writeFileHandler` / `patchHandler` — strict unified-diff applier, no fuzz |
| `desktop/src/tools/handlers/terminal.ts` | `bash -lc` / `cmd /c`, SIGKILL on timeout or abort, returns `{stdout, stderr, exit_code, duration_ms}` |
| `desktop/src/tools/handlers/powershell.ts` | Spawns `pwsh`/`powershell` directly with `-Command -`, script piped via stdin — no cmd.exe quote-mangling; auto-picks pwsh &gt; powershell |
| `desktop/src/tools/handlers/process.ts` | `spawn_detached` (unref'd, returns pid+log_path), `list_processes` (tasklist /FO CSV — no /V to dodge window-title latency), `kill_process`, `find_pid_by_port` (netstat/lsof/ss) |
| `desktop/src/tools/handlers/jobs.ts` | Job API — `~/.hermes/desktop-jobs/<id>/{stdout.log, stderr.log, meta.json}` is source of truth across daemon restarts; `taskkill /T` on Windows so build trees die fully |
| `desktop/src/tools/handlers/transfer.ts` | `copy_directory` via `fs.cp`, `zip`/`unzip` via tar &gt; zip &gt; PowerShell probe, `checksum` streamed (sha256/sha1/md5) |
| `desktop/src/tools/handlers/search.ts` | ripgrep with pure-Node fallback, skips `.git`/`node_modules`/`dist`/`.next`/`.cache` |
| `desktop/src/renderer.ts` | Streams `message.delta` → stdout, tool events → decorated lines; NO_COLOR / --json / --quiet aware |
| `desktop/src/pairing.ts` | readline-based 6-char prompt (`A-Z0-9`); headless mirror of TUI's Ink prompt; `validatePairingPayloadString` discriminated-union wrapper |
| `desktop/src/credentials.ts` | Precedence: `--token` → `--pair-qr` (probe+pair) → `--code` → stored → prompt; returns `Credentials{sessionToken?, pairingCode?, resolvedEndpoint?}` |
| `desktop/src/transport/RelayTransport.ts` | Fork of ui-tui's transport + reconnect state machine (`idle/connecting/connected/reconnecting`, exp backoff 1→30s, 5min on 429, gate re-check post-sleep) + pre-WS TLS probe for TOFU |
| `desktop/src/remoteSessions.ts` | Same file path as TUI (`~/.hermes/remote-sessions.json`, 0600); schema widened with `grants`, `ttlExpiresAt`, `endpointRole`, `toolsConsented`; `saveSession` back-compat overload |
| `desktop/src/commands/daemon.ts` | Headless WSS + tool router for always-on access; JSON-line logs; fails closed on missing consent unless `--allow-tools` with explicit `--token` |
| `desktop/src/commands/doctor.ts` | Local-only diagnostic report — version / binary path / PATH / sessions / daemon detection; `--json` for support-paste; omits tokens entirely |
| `desktop/src/relayUrlPrompt.ts` | First-run URL fallback — `resolveFirstRunUrl()` auto-picks single stored session, numbered picker for multiple, welcome banner for zero; throws on non-interactive + ambiguous |
| `desktop/src/version.ts` | Build-time-generated constant (`npm run gen:version` before every build) — Bun compiled binaries can't read package.json via `__dirname` so version is embedded at build |
| `desktop/scripts/install.sh` / `install.ps1` | curl/iwr one-liner installers — download prebuilt Bun binary (no Node required), SHA256-verified, API-resolver for `latest` that includes prereleases, version-aware pre/post-install readback |
| `desktop/scripts/uninstall.sh` / `uninstall.ps1` | 3-tier removal — default (binary + PATH), `--purge` (also wipes `~/.hermes/remote-sessions.json`), `--service` (stub for future service installers); Windows iex-safe env-var fallback |
| `desktop/README.md` | User-facing install + usage reference |
| **Desktop CLI — dev iteration** | |
| `npm run smoke` (in `desktop/`) | Builds Windows binary + runs `--version` / `--help` / `doctor`, fails loud on zero-output. Local pre-flight before cutting any tag. |
| `npm run gen:version` | Regenerates `src/version.ts` from `package.json`. Runs automatically before every `build` / `build:bin:*`. |
| `release-cli.yml → Smoke-test Linux binary` step | CI-side equivalent: runs compiled Linux binary through the same 3-command check before uploading assets. Catches silent-exit-0 + segfault classes. |
| **Server — Desktop tool routing (Phase B)** | |
| `plugin/relay/channels/desktop.py` | Mirrors `bridge.py` — `desktop.command`/`desktop.response`/`desktop.status`, UUID-correlated futures, 30s timeout, single-client MVP, per-session advertised-tools set |
| `plugin/tools/desktop_tool.py` | 24 `desktop_*` tools (fs/shell/powershell/process/jobs/transfer/health) — registers with `tools.registry` under `desktop` toolset; per-tool `check_fn` pings `/desktop/_ping?tool=<name>`; `desktop_health` is `_RELAY_ONLY` and pings `/desktop/health` so it works even when the client is wedged |
| **Gradle modules — experimental Quest/XR (in development)** | |
| `relay-core/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.core`) — shared pairing/transport/terminal/voice/wire for the Quest port; not yet wired into the shipped `:app` |
| `relay-ui/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.ui`) — shared Compose UI (sphere, terminal WebView, QR scanner) for the Quest port; carries its own sphere copy |
| `quest/` | [EXPERIMENTAL] Meta Spatial SDK Quest/XR app — gradle `includeBuild("quest")`; needs further development, not shipped |
| **Tooling — dev iteration (not shipped)** | |
| `ui-preview/` | Desktop Compose Hot Reload harness — JVM Compose for Desktop; source-shares `MorphingSphereCore` from `:relay-ui`; `Main.kt` gallery; see `ui-preview/README.md` |
| `app/src/test/.../screenshots/StoreScreenshotTest.kt` | Roborazzi host-side store/docs screenshot renderer — deterministic, no device, exact 1080×2160; reuses real components+chrome with mock data; `capture(name, themeId){…}` renders any view; see `docs/screenshot-automation.md` §Deterministic rendering (JDK-21 + no-plugin gotchas) |
## What NOT to Do
- **Don't use XML layouts** — Compose only
- **Don't use Gson** — kotlinx.serialization
- **Don't use Ktor for networking** — OkHttp for WebSocket
- **Don't use plaintext WebSocket** — `wss://` only, even in development
- **Don't put documentation in root** — long-form docs go in `docs/`
- **Don't forget DEVLOG.md** — update it (record *what happened*)
- **Don't bury follow-ups** — deferred work / known gaps go in `TODO.md`, never in DEVLOG or one-off code/doc comments
- **Don't touch production / remote hosts** — automation and orchestrated agents must NEVER SSH into, deploy to, pull/restart/reconfigure, or push code to a live/remote Hermes host. Building, on-device testing, and server deployment are owner-driven (see Server Deployment). Stop at committing on your branch; surface "this needs a deploy/on-device check" rather than doing it.
## MCP Tooling
Two MCP servers are configured for AI-assisted development. See `docs/mcp-tooling.md` for full reference.
| Server | Layer | Requires |
| ------------------- | --------------------------------------------------------------- | ---------------------------------------- |
| `android-tools-mcp` | IDE/Build — Compose previews, Gradle, code search, Android docs | Android Studio running with project open |
| `mobile-mcp` | Device/Runtime — tap, swipe, screenshot, app management | ADB + connected device/emulator |
## Dev Workflow
```bash
scripts/dev.bat build # Build debug APK (DEV_MODE=true)
scripts/dev.bat release # Build signed release APK (DEV_MODE=false)
scripts/dev.bat bundle # Build release AAB for Google Play upload
scripts/dev.bat run # Build + install + launch + logcat
scripts/dev.bat test # Run unit tests
scripts/dev.bat version # Show current version from libs.versions.toml
scripts/dev.bat relay # Start relay server (dev mode, no SSL)
```
### Bridge smoke test (run on hermes-host, not local PC)
```bash
scripts/bridge-smoke.sh # full suite, destructive ON
scripts/bridge-smoke.sh --no-destructive # read-only paths only
scripts/bridge-smoke.sh --filter open_app # re-run a single test
scripts/bridge-smoke.sh --pair ABCDEF # register pairing code first
```
Curls every bridge HTTP route via `localhost:8767`. Catches the silent-drop regression class (Python relay registers a route but Kotlin dispatcher's `when (path)` has no matching branch). Run after every relay restart.
### Typical Dev Loop
1. **Edit locally** — Windows checkout. Both plugin (`plugin/`) and app (`app/`) live here.
2. **Python syntax check** — `python -m py_compile plugin/<file>.py`. Full tests run on the server.
3. **Kotlin changes** — do NOT run `gradle build`. Bailey builds via Android Studio's ▶ button. Never `adb install` from Claude.
4. **Before pushing Kotlin changes** — run `./gradlew lint` locally. It's the exact task CI runs and catches errors Android Studio's live inspections miss — e.g. `UnsafeOptInUsageError` with `kotlin.OptIn` vs `androidx.annotation.OptIn`, `FlowOperatorInvokedInComposition` (mapped flows inside Composables), Media3 `@UnstableApi` propagation. Android CI runs lint alongside build/test for faster feedback, but a local lint run still surfaces issues before the workflow spends runner time compiling and packaging.
5. **Commit + push** — follow `AGENTS.md` and `RELEASE.md`; normal work PRs to `dev`.
6. **Pull + restart on server** — see Server Deployment below.
7. **Test on phone** — Bailey builds from Studio, installs to Samsung device, pairs via `/hermes-relay-pair`.
### Server Deployment
Server is a Linux box running hermes-agent with hermes-relay editable-installed (`pip install -e`). Sensitive details (IP, user, secrets) in `~/SYSTEM.md` on the server — not in this repo.
| What | Where |
| ------------------ | ------------------------------------------------------------------ |
| hermes-agent repo | `~/.hermes/hermes-agent/` |
| hermes-relay clone | `~/.hermes/hermes-relay/` |
| Plugin symlink | `~/.hermes/plugins/hermes-relay` → `~/.hermes/hermes-relay/plugin` |
| Config | `~/.hermes/config.yaml` + `~/.hermes/.env` |
| Relay log | `journalctl --user -u hermes-relay -f` |
**Update:** `hermes-relay-update` (idempotent, re-fetches install.sh). Or manually: `git pull --ff-only && systemctl --user restart hermes-relay`.
**Compat hook:** `hermes relay compat status/install/remove` manages only the
optional `hermes_relay_bootstrap.pth` startup hook. New installs load the
plugin-owned bootstrap from `plugin/hermes_relay_bootstrap/`; the repo-root
package is only a legacy import shim. Vanilla Hermes chat, Manage, and dashboard voice
must not depend on this hook.
**Key conventions:**
- Phone pairing **survives** relay restart — `SessionManager` persists sessions to `~/.hermes/hermes-relay-sessions.json` (`server.py:88-90`, `persistence_path` from `RelayConfig.from_env`); a trusted-device refresh token recovers a lost/revoked/reset session without a new QR scan. (Only the in-memory *live-connection presence* clears on restart; the phone reconnects automatically.)
- Use `python -m unittest` not `pytest` — conftest imports `responses` which may not be installed
- `_env_bootstrap.py` loads `~/.hermes/.env` on every relay start — no stale API keys
### Where Python vs. Kotlin changes land
| Change type | Who restarts? | Command |
| ------------------------------------ | ------------------------ | -------------------------------------------------- |
| Plugin tool (`android_tool.py` etc.) | `hermes-gateway.service` | `systemctl --user restart hermes-gateway` |
| Relay code (`plugin/relay/*.py`) | `hermes-relay.service` | `systemctl --user restart hermes-relay` |
| Pair CLI / skill files | — | No restart — fresh process / scanned on invocation |
| Android app | Bailey (Studio) | Studio run button |
### Release Process
See [AGENTS.md](AGENTS.md) for the canonical branch contract and
[RELEASE.md](RELEASE.md) for version sources, release trains, surface tags,
hotfixes, secrets, publishing, and verification. Claude-specific automation
must not infer release authority from feature completion.
## Integration Points
| Surface | Endpoint | Notes |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chat (gateway) | Dashboard `POST /api/auth/ws-ticket` -&gt; WS `/api/ws` | Vanilla Hermes dashboard/tui_gateway path; live thinking/reasoning; requires dashboard auth |
| Chat streaming | `POST /v1/runs` → `GET /v1/runs/{id}/events` | Structured tool events; async run-control path |
| Chat (sessions) | `POST /api/sessions/{id}/chat/stream` | Native upstream session-persisted SSE; preferred when capability probe finds it |
| Chat (compat) | `POST /v1/chat/completions` (stream=true) | Inline tool annotations only |
| Session CRUD | `GET/POST/PATCH/DELETE /api/sessions` | Native upstream (#33134); bootstrap fallback retired |
| Manage | Dashboard `/api/status`, `/api/auth/me`, `/api/config`, `/api/profiles/*`, `/api/env`, `/api/model/*`, `/api/mcp/*` | Vanilla Hermes dashboard surface; do not proxy through Relay |
| Vanilla Hermes voice | Dashboard `POST /api/audio/transcribe`, `POST /api/audio/speak` | Vanilla Hermes no-plugin voice; uses dashboard session from Manage |
| Pairing (QR) | `POST /pairing/register` (loopback only) | Via `/hermes-relay-pair` or `hermes-pair` shim; accepts optional `endpoints` for multi-endpoint QRs |
| Pairing (multi-endpoint) | QR `endpoints` array (ADR 24) | `hermes: 3` schema; ordered `lan`/`tailscale`/`public`/... candidates; phone re-probes on network change |
| Pairing auth | WSS `auth.ok` payload | Includes `expires_at`, `grants`, `transport_hint` |
| Tailscale Serve (ADR 25) | `hermes-relay-tailscale enable|disable|status` CLI | Fronts loopback `:8767` with `tailscale serve --bg --https=<port>`; auto-retires on upstream PR #9295 |
| Inbound media (token) | `GET /media/{token}` | Bearer auth; 24h TTL |
| Inbound media (path) | `GET /media/by-path?path=<abs>` | Permissive by default; `RELAY_MEDIA_STRICT_SANDBOX=1` to restrict |
| Session management | `GET /sessions`, `DELETE /sessions/{prefix}`, `PATCH /sessions/{prefix}` | List/revoke/extend; RelayHttpClient |
| Voice transcribe | `POST /voice/transcribe` | multipart/form-data; bearer auth |
| Voice synthesize | `POST /voice/synthesize` | JSON → audio/mpeg; max 5000 chars |
| Voice config | `GET /voice/config` | Returns current tts/stt provider info |
| Plugin diagnostics | `hermes relay doctor --json` | Reports upstream route reachability, Relay loopback state, plugin layout, and legacy bootstrap state |
| Compat hook lifecycle | `hermes relay compat status/install/remove` | Optional legacy API compatibility hook; not required for the standard path |
| Notifications | `GET /notifications/recent?limit=N` | Loopback callers skip bearer |
| Relay health | `GET /health` on `:8767` | Used by `RelayHttpClient.probeHealth()` |
| Capabilities | `GET /v1/capabilities` plus targeted `HEAD` probes | Prefer capabilities when present; HEAD probes keep mixed-version fallback working |
| Desktop CLI (tui channel) | WSS `tui.attach` / `tui.rpc.request` / `tui.rpc.event` | Same channel + envelopes as the Ink TUI — the CLI just renders events as plain lines. Zero server changes. |
| Desktop CLI (terminal channel) | WSS `terminal.attach` / `terminal.input` / `terminal.output` / `terminal.resize` / `terminal.detached` | Existing channel (shared with Android). CLI `shell` subcommand attaches, injects `clear; exec hermes\n` 350ms after ack, pipes raw bytes. `Ctrl+A .` detaches (tmux preserved), `Ctrl+A k` kills. |
| Desktop CLI tool visibility | `tools.list` RPC on the shared tui channel | Returns `{toolsets: [{name, description, tool_count, enabled, tools:[]}]}`; surfaced by `hermes-relay tools` |
| Desktop CLI devices | HTTP `GET/DELETE/PATCH /sessions` on the relay's same port | Wrapped by `hermes-relay devices list |
| Desktop tool routing (Phase B) | WSS `desktop.command` (s→c) + `desktop.response` (c→s) + `desktop.status` (c→s heartbeat) | New channel. Hermes calls `desktop_read_file(path)` → Python handler POSTs to `/desktop/desktop_read_file` → relay forwards over `desktop.command` → Node client's `DesktopToolRouter` runs the handler locally → response bubbles back. Mirror of Android's `bridge.command` pattern. |
| Desktop tool check_fn | HTTP `GET /desktop/_ping?tool=<name>` | Returns 200 if a client is connected AND advertises this tool; 503 otherwise. Hermes uses this to fail the tool quickly when no desktop client is live, instead of waiting 30s for the dispatch timeout. |
| Desktop health | HTTP `GET /desktop/health` | Returns full status snapshot — connected/host/platform/version/pid/uptime/advertised_tools/last_error/recent_commands. Loopback-only. Backs the `desktop_health` agent tool, which intentionally does NOT round-trip through the client so it remains callable when other tools are wedged. |
## Upstream References
| Topic | Upstream File |
| -------------------------- | ----------------------------------------------------------------------------- |
| API endpoints | `gateway/platforms/api_server.py` — all registered HTTP routes |
| Platform adapter interface | `gateway/platforms/base.py` — `BasePlatformAdapter` abstract class |
| Adding a platform | `gateway/platforms/ADDING_A_PLATFORM.md` — 16-step checklist |
| Platform registration | `gateway/run.py` → `_create_adapter()`, `gateway/config.py` → `Platform` enum |
| Channel directory | `gateway/channel_directory.py` — how platforms/channels are enumerated |
| Send message routing | `tools/send_message_tool.py` → `platform_map` dict |
| SSE streaming (runs) | `gateway/platforms/api_server.py` → runs endpoint, `_on_tool_progress` |
## Related Projects
- [**hermes-agent**](https://github.com/NousResearch/hermes-agent) — the agent platform (gateway, WebAPI, plugin system)
- [**android-tools-mcp**](https://github.com/Codename-11/android-tools-mcp) — our fork of Android Studio MCP bridge (Compose previews, Gradle, docs)
- [**mobile-mcp**](https://github.com/mobile-next/mobile-mcp) — device control MCP server (ADB, tap/swipe, screenshots)
@AGENTS.md
+24 -8
View File
@@ -61,6 +61,15 @@ configuration between invocations and do not add `--no-daemon` to normal dev
commands; a different heap or Java home starts a separate daemon and discards
the warm-process benefit.
On Windows, all repository dev helpers serialize Android build and device work
through one machine-wide lane shared by every Hermes-Relay worktree. Use
`scripts/android-lane.ps1` for ad hoc Gradle, connected-test, and APK-install
commands, and keep Android Studio idle while another owner holds the lane. For
an exact commit that is already pushed, prefer the `Android On-Demand` workflow
for heavy verification so concurrent worktrees use isolated GitHub-hosted
runners. See [Android build execution](docs/android-build-lane.md) for cloud
presets, the optional full local gate, status, and recovery modes.
Use the narrowest command that proves the change:
1. `scripts/dev.bat compile` for a Kotlin compile check.
@@ -68,7 +77,10 @@ Use the narrowest command that proves the change:
3. `scripts/dev.bat install-fast` when the result must run on the connected
arm64 phone. This passes `-Phermes.devAbi=arm64-v8a`, avoiding the x86,
x86_64, and armeabi-v7a native libraries in the local APK.
4. `scripts/dev.bat prepush` before pushing Android work.
4. `Android On-Demand` after an exact commit is pushed for lint, broad checks,
assemblies, or release smoke.
5. `scripts/dev.bat prepush` only when full local verification is explicitly
wanted or cloud execution is unavailable.
`install-fast` is intentionally phone-specific. Use `install` for a universal
sideload debug APK or when the target ABI is not arm64. Release builds remain
@@ -258,12 +270,16 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
## Testing
- **Android pre-push gate:** `scripts\dev.bat prepush` on Windows or
`./scripts/dev.sh prepush` on macOS/Linux. This runs the Android repository
checks, Google Play debug lint, and the same focused unit-test shard used by
CI in one cached Gradle invocation. Run it before pushing Android PR updates
to catch common hosted failures without waiting for another full Actions
cycle; hosted CI remains the exhaustive all-variant gate.
- **Android cloud verification (preferred for pushed work):** dispatch the
registered `Required checks` workflow with an exact base/head SHA pair and
`android_preset` set to `focused`, `lint`, `assemble-debug`, `release-smoke`,
or `all-final`. It calls the reusable Android workflow from `dev`. Check for
an existing run before dispatching the same SHA/preset again. The four
`all-final` compute jobs use isolated runners and may execute concurrently.
- **Full local Android gate (optional):** `scripts\dev.bat prepush` on Windows
or `./scripts/dev.sh prepush` on macOS/Linux. This retains the repository
checks, full Android lint, and both focused flavor shards for an explicit local
run or cloud outage. On Windows it acquires the machine-wide lane.
- **Focused Android unit test:** `scripts/dev.bat test-one "<fully-qualified-class-or-pattern>"`
- **Android unit tests:** `scripts/dev.bat test` (runs the sideload debug JUnit + MockK + Compose suite)
- **Gateway contract lab:** [`docs/gateway-contract-testing.md`](docs/gateway-contract-testing.md)
@@ -272,7 +288,7 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
device lane is scheduled automatically.
- **Python tests:** `python -m unittest plugin.tests.test_<name>` from the repo root with the hermes-agent venv active. `pytest` works too but the pre-existing `conftest.py` imports a module that isn't always installed — `unittest` avoids that entirely.
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched.
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched. The registered `ci-required.yml` dispatcher calls `android-on-demand.yml` as the trusted manual compute lane for an exact pushed commit; it does not replace required PR checks.
Superseded Android runs on `dev` and PR refs are canceled automatically; `main`
runs are never canceled because each release-branch commit must complete its
independent validation.
+22
View File
@@ -1,5 +1,27 @@
# Hermes-Relay — Dev Log
## 2026-08-31 — Complete, readable Android release notes
Android release metadata now keeps one overall title and summary plus a complete
typed inventory of user-visible additions, improvements, and fixes. Stable
change ids prevent duplicate records, selected highlights lead the expanded
view, and compatibility boundaries remain visible without turning the compact
notice into technical release documentation. Toast counts and previews are
derived from the same non-highlighted changes the dialog and history render, so
View all reaches every counted item. Older bundled changelog entries retain
their existing rendering path.
The Android 1.14.0 record was migrated to the complete schema and reconciled
against its released Android changelog: four highlights, two additional
improvements, ten fixes, and three compatibility notes. The dialog, full
history, large-text toast, seven Android resource catalogs, legacy text
fallback, Play note, listing copy, release-prep instructions, and validation
tests were updated together.
Structured release-note tests, focused Kotlin tests, Android locale and
collection-API gates, rendered 360×640 dark-theme screenshots including 135%
text, sideload APK assembly, Android lint, and diff checks passed.
## 2026-08-27 — Fixed issue ownership and bounded PR intake
The automated issue first-response lane now assigns only `Codename-11` when the
+30 -27
View File
@@ -531,13 +531,14 @@ the new app version and a higher `appVersionCode`.
`retrace <mapping.txt> <obfuscated-trace.txt>`. Play reports can additionally
use the mapping bundled into the uploaded AAB through Play Console.
- `app/src/main/assets/changelog.json` — curated source for the in-app
**What's New** dialog and Android release history. Prepend the newest entry
with one explicit `highlight` (`title`, plain-language `summary`, and 1–3
user-benefit bullets), up to two quieter `improvements`, Android-only
`playNotes`, a `toastDigest` with counts and 0–2 short previews for noteworthy
items beyond the hero, and the existing technical `sections` used by older clients.
Do not derive the highlight mechanically from `CHANGELOG.md`; choosing the
release's main reason to care is an editorial release-prep decision.
**What's New** dialog and Android release history. Prepend one schema-3 entry
with a single descriptive release `title`, a plain-language `summary`, and a
complete `changes` inventory. Every user-visible change has a stable `id`, a
`kind` (`added`, `improved`, or `fixed`), a short title, a useful explanation,
and an optional `highlight: true`; select 1–4 highlights. Add `compatibility`
bullets only when users need an availability, migration, flavor, or Plugin
boundary, plus Android-only `playNotes`. The app derives toast counts and
previews from the same inventory and renders every change exactly once.
- `app/src/main/assets/whats_new.txt` — legacy in-app fallback generated from
the newest structured entry. Do not edit it independently.
- `app/src/googlePlay/play/release-notes/en-US/default.txt` — the Play
@@ -551,8 +552,8 @@ the new app version and a higher `appVersionCode`.
block and the Gradle Play Publisher note are generated from `playNotes`.
After editing the newest structured entry, run
`python scripts/check-android-release-notes.py --write`, then run it again
without `--write` to validate the 1–3 / 0–2 editorial limits, current Android
version, GitHub-release/changelog headings, derived files, and Play's
without `--write` to validate complete unique change records, 1–4 highlights,
the current Android version, GitHub-release/changelog headings, derived files, and Play's
**500-character** limit. Frame Play copy around the release's themes, not a
feature dump. Compare its **Foreground service
permissions** section with the merged `googlePlayRelease` manifest and
@@ -570,28 +571,30 @@ authoring contract; do not maintain a separate prompt file.
boundary that users must understand. Do not generate from commit titles or
a mixed-surface changelog block alone.
2. Before editing release files, show a temporary coverage ledger in the task
output. Map every selected source change to exactly one placement:
`hero`, `secondary`, or `full-only`. Include the change kind (`feature`,
`change`, or `fix`) and a short reason. The ledger is review evidence, not a
committed public artifact; no selected source item may disappear silently.
3. Choose exactly one `hero`: the strongest user-facing reason to care about
the release. Its summary is one plain-language outcome, and its 1–3 bullets
are distinct user benefits rather than implementation steps or filler.
4. Use `secondary` for other important user-visible features and fixes. The
`toastDigest` counts only these items, excluding the hero. Preview the
strongest 1–2 secondary items in short phrases. If there are no legitimate
secondary items, set both counts to `0` and `preview` to `[]`; the app hides
the footer. Never invent an item to satisfy the layout.
5. Use `full-only` for technically relevant details that belong in
`RELEASE_NOTES.md` or `CHANGELOG.md` but would make the collapsed update card
noisy. Preserve user-relevant trust and compatibility limits; omit branches,
worktrees, CI mechanics, debugging history, and private/operator context.
output. Map every selected Android source change to one stable change id and
one kind (`added`, `improved`, or `fixed`), and mark whether it is a
highlight. The ledger is review evidence, not a committed public artifact;
no selected user-visible change may disappear silently or be counted twice.
3. Write one release title that describes the release as a whole. Do not let a
narrow feature name, internal project label, or poetic codename replace the
title users see in the toast and history. Follow it with a one- or two-sentence
summary that gives the release's overall outcome without becoming a feature dump.
4. Select 1–4 highlights from the complete change inventory. A highlight is a
strong reason to care, not a second copy of the change: the app presents it
once in the highlight section and derives the remaining counts and previews
from non-highlighted changes.
5. Include every meaningful user-visible addition, improvement, and fix in
`changes`, using plain titles and enough explanation for someone to recognize
the affected behavior. Internal refactors, tests, CI mechanics, branch work,
and debugging history stay in `RELEASE_NOTES.md`, `CHANGELOG.md`, or engineering
records unless they materially change reliability, security, or compatibility.
6. Write each surface for its audience:
- `RELEASE_NOTES.md`: concise Summary plus Added/Changed/Fixed; keep the
deterministic Download and Install/Verify scaffolding intact.
- `CHANGELOG.md`: complete, crisp public history for the released surface.
- `changelog.json`: curated hero, optional improvements, digest, Play copy,
and compatibility `sections` for older clients.
- `changelog.json`: overall title/summary, complete typed changes, selected
highlights, compatibility boundaries, and Play copy. Counts and previews
are derived; never author a parallel digest.
- `playNotes`: Android-only themes within the rendered 500-character limit.
7. Before presenting the draft, check that wording begins with user outcomes,
avoids unexplained implementation terminology, uses exact public product
+13
View File
@@ -6,6 +6,19 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
---
## Consider hosted Android emulator execution
The local API 36 Gradle Managed Device lanes are intentionally on demand and
individually selected. The current Android On-Demand workflow covers hosted
source, unit, lint, and build verification only; it does not run emulators. If
local emulator capacity becomes a recurring constraint, evaluate a separately
approved hosted-emulator design with explicit cost, concurrency, artifact
retention, and trigger policy. Do not schedule the full form-factor matrix or
add a device farm until that policy is approved; keep live-server mutation tests
outside any automatic matrix.
---
## Upstream a public Dashboard plugin WebSocket admission seam
The same-origin Relay ingress follows current upstream's bundled Dashboard
+60 -2
View File
@@ -249,6 +249,58 @@ android {
it.systemProperty("roborazzi.test.record", "true")
it.maxHeapSize = "2g"
}
// On-demand only. Keep each form factor as an individually selected
// Gradle-managed device; there is deliberately no aggregate matrix
// task or scheduled emulator job. See docs/android-emulator-testing.md.
managedDevices {
localDevices {
create("compactPhoneApi36") {
device = "Pixel 2"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("standardPhoneApi36") {
device = "Pixel 6"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("largePhoneApi36") {
device = "Pixel 7 Pro"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("foldableApi36") {
device = "Pixel Fold"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("tabletApi36") {
device = "Pixel Tablet"
apiLevel = 36
systemImageSource = "aosp"
require64Bit = true
testedAbi = "x86_64"
}
create("futureApi37Ps16k") {
device = "Pixel 7 Pro"
apiLevel = 37
systemImageSource = "google_apis_playstore"
require64Bit = true
testedAbi = "x86_64"
pageAlignment =
com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES
}
}
}
}
}
@@ -390,6 +442,12 @@ dependencies {
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
testImplementation(libs.konsist)
androidTestImplementation(libs.compose.ui.test.junit4)
// Compose UI Test still declares Espresso 3.5.0 transitively. API 37
// removed the reflected InputManager.getInstance() seam; Espresso 3.7.0
// uses Context.getSystemService and is the current stable AndroidX line.
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test:runner:1.7.0")
androidTestImplementation("androidx.test.ext:junit:1.3.0")
// On-device vanilla-Gateway contract tests exercise the production
// Dashboard ticket + WebSocket stack over real loopback sockets.
androidTestImplementation(libs.okhttp.mockwebserver)
@@ -399,8 +457,8 @@ dependencies {
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
// Renders real composables on the JVM at an exact canvas — no device, no
// status bar, no clipping. See StoreScreenshotTest.
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.72.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.72.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.73.0")
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.73.0")
testImplementation(libs.compose.ui.test.junit4)
testImplementation(libs.compose.ui.test.manifest)
testImplementation("androidx.test.ext:junit:1.3.0")
@@ -6,8 +6,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.test.platform.app.InstrumentationRegistry
@@ -28,50 +27,6 @@ class AmbientVisualizationVisibilityTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun cleanMode_backgroundOff_hidesSphereAndKeepsComposer() {
composeTestRule.setContent {
AmbientTestProviders(enabled = false) {
CleanChatMode(
messages = emptyList(),
isStreaming = false,
sphereState = SphereState.Idle,
streamingIntensity = 0f,
toolCallBurst = 0f,
animationEnabled = true,
enabled = true,
onSend = {},
onExit = {},
)
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertDoesNotExist()
composeTestRule.onNodeWithContentDescription(targetString(R.string.agent_text_send_cd))
.assertExists()
}
@Test
fun cleanMode_backgroundOn_rendersSphere() {
composeTestRule.setContent {
AmbientTestProviders(enabled = true) {
CleanChatMode(
messages = emptyList(),
isStreaming = false,
sphereState = SphereState.Idle,
streamingIntensity = 0f,
toolCallBurst = 0f,
animationEnabled = false,
enabled = true,
onSend = {},
onExit = {},
)
}
}
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertExists()
}
@Test
fun voiceMode_backgroundOff_hidesSphereAndKeepsVoiceUi() {
composeTestRule.setContent {
@@ -0,0 +1,160 @@
package com.hermesandroid.relay.ui.screens
import android.os.Handler
import android.os.Looper
import android.view.accessibility.AccessibilityNodeInfo
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import androidx.test.platform.app.InstrumentationRegistry
import com.hermesandroid.relay.data.BotGatewayRoute
import com.hermesandroid.relay.data.BotGatewayRouteKey
import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.viewmodel.AndroidGatewayContractFixture
import com.hermesandroid.relay.viewmodel.ChatViewModel
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.JsonPrimitive
import okhttp3.OkHttpClient
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/** On-device proof for the route-owned first-composition collection boundary. */
class BotChatScreenBindingInstrumentedTest {
private lateinit var fixture: AndroidGatewayContractFixture
private lateinit var gatewayScope: CoroutineScope
private lateinit var dashboardClient: DashboardApiClient
private lateinit var gatewayClient: GatewayChatClient
private lateinit var viewModel: ChatViewModel
private lateinit var handler: ChatHandler
private var activityScenario: ActivityScenario<BotChatBindingTestActivity>? = null
@Before
fun setUp() {
fixture = AndroidGatewayContractFixture()
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
dashboardClient = DashboardApiClient(
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
okHttpClient = OkHttpClient(),
)
gatewayClient = GatewayChatClient(
initialDashboardClient = dashboardClient,
okHttpClient = OkHttpClient(),
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
scope = gatewayScope,
reconnectJitterUnit = { 0.0 },
)
viewModel = ChatViewModel()
handler = ChatHandler()
}
@After
fun tearDown() {
activityScenario?.close()
viewModel.updateGatewayClient(null)
gatewayClient.shutdown()
gatewayScope.cancel()
dashboardClient.shutdown()
fixture.shutdown()
}
@Test
fun fastInitialHistoryRendersBeforeNavigationAndSurvivesLifecycleResume() {
val route = BotGatewayRoute(
key = BotGatewayRouteKey("fixture-gateway", PROFILE_NAME),
connectionLabel = "Fixture gateway",
)
val bot = BotRosterEntry(
profile = Profile(
name = PROFILE_NAME,
model = "fixture-model",
description = "Fixture profile",
),
displayName = "Research",
route = route,
)
val scenario = ActivityScenario.launch(BotChatBindingTestActivity::class.java)
.also { activityScenario = it }
scenario.onActivity { activity ->
activity.setContent {
MaterialTheme {
BotChatScreen(
route = route,
bot = bot,
sessionId = STORED_SESSION_ID,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = viewModel,
onBack = {},
handlerFactory = { handler },
historyLoader = { _, _, _ ->
Result.success(
listOf(
MessageItem(
id = HISTORY_ID,
sessionId = STORED_SESSION_ID,
role = "assistant",
content = JsonPrimitive(HISTORY_TEXT),
timestamp = 1.0,
finishReason = "stop",
),
),
)
},
profileIconFlow = { _, _ -> MutableStateFlow(null) },
)
}
}
}
waitUntil { handler.messages.value.singleOrNull()?.content == HISTORY_TEXT }
waitUntil { renderedTextExists(HISTORY_TEXT) }
scenario.moveToState(Lifecycle.State.STARTED)
scenario.moveToState(Lifecycle.State.RESUMED)
waitUntil { renderedTextExists(HISTORY_TEXT) }
assertEquals(0, fixture.rpcCount("prompt.submit"))
}
private fun renderedTextExists(expected: String): Boolean {
val instrumentation = InstrumentationRegistry.getInstrumentation()
instrumentation.waitForIdleSync()
val root = instrumentation.uiAutomation.rootInActiveWindow ?: return false
return root.containsText(expected)
}
private fun AccessibilityNodeInfo.containsText(expected: String): Boolean {
if (text?.toString() == expected || contentDescription?.toString() == expected) return true
return (0 until childCount).any { index -> getChild(index)?.containsText(expected) == true }
}
private fun waitUntil(condition: () -> Boolean) {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (System.nanoTime() < deadline) {
if (condition()) return
Thread.sleep(25)
}
assertTrue("Condition was not satisfied within 5 seconds", condition())
}
private companion object {
const val PROFILE_NAME = "research"
const val STORED_SESSION_ID = "20260829_120000_bot_chat"
const val HISTORY_ID = "persisted-bot-history"
const val HISTORY_TEXT = "Durable Bot Chat history is ready."
}
}
@@ -4,6 +4,7 @@ import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.Modifier
@@ -17,6 +18,11 @@ import androidx.compose.ui.test.onNodeWithTag
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
import com.hermesandroid.relay.data.ChatTurnCheckpoint
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
@@ -27,6 +33,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
@@ -44,6 +51,7 @@ import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
@@ -74,10 +82,11 @@ class GatewayForegroundRecoveryInstrumentedTest {
@Volatile
private var persistedHistory: List<MessageItem> = emptyList()
private val historySignInRequired = MutableStateFlow(false)
@Before
fun setUp() {
fixture = AndroidGatewayContractFixture()
fixture = AndroidGatewayContractFixture().also { it.profileName = PROFILE_NAME }
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
val okHttp = OkHttpClient()
gatewayClient = GatewayChatClient(
@@ -97,6 +106,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
handler,
)
it.streamingEndpoint = "gateway"
it.setSessionProfileNameProvider { PROFILE_NAME }
it.setProfileMessageLoader { Result.success(persistedHistory) }
it.updateGatewayClient(gatewayClient)
it.setChatVisible(true)
@@ -105,6 +115,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
compose.setContent {
val messages by viewModel.messages.collectAsStateWithLifecycle()
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
MaterialTheme {
Column(Modifier.testTag("contract-transcript")) {
Text(
@@ -117,6 +128,14 @@ class GatewayForegroundRecoveryInstrumentedTest {
modifier = Modifier.testTag("message-${message.id}"),
)
}
if (signInRequired) {
Button(
onClick = {},
modifier = Modifier.testTag("dashboard-sign-in-recovery"),
) {
Text("SIGN IN")
}
}
}
}
}
@@ -252,9 +271,6 @@ class GatewayForegroundRecoveryInstrumentedTest {
"session.interrupt",
"prompt.submit",
)
val baseline = controlMethods.associateWith(fixture::rpcCount)
val baselineActiveList = fixture.rpcCount("session.active_list")
fixture.activeSessionStatus = "working"
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
val okHttp = OkHttpClient()
gatewayClient = GatewayChatClient(
@@ -269,6 +285,17 @@ class GatewayForegroundRecoveryInstrumentedTest {
)
viewModel.setChatTurnCheckpointStore(null)
viewModel.updateGatewayClient(gatewayClient)
assertTrue(runBlocking { gatewayClient.observeAwait() })
serverSocket = fixture.awaitServerSocket()
viewModel.switchProfileContext(
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
STORED_SESSION_ID,
)
viewModel.updateSessionActivityDirectory(listOf(PROFILE_NAME to STORED_SESSION_ID))
val baseline = controlMethods.associateWith(fixture::rpcCount)
val baselineActiveList = fixture.rpcCount("session.active_list")
fixture.activeSessionStatus = "working"
viewModel.setChatVisible(true)
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
@@ -293,6 +320,141 @@ class GatewayForegroundRecoveryInstrumentedTest {
)
}
@Test
fun normalCompletion_genericHistory401RetainsTranscriptAndRequiresProfileSignIn() {
bindDashboardHistoryFailure(
body = "Unauthorized",
profileName = PROFILE_NAME,
)
viewModel.sendMessage("Keep this local transcript")
fixture.awaitRpc("prompt.submit")
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
serverSocket.send(
fixture.event(
"message.delta",
buildJsonObject { put("text", LOCAL_COMPLETION) },
LIVE_SESSION_ID,
),
)
serverSocket.send(
fixture.event(
"message.complete",
buildJsonObject { put("text", LOCAL_COMPLETION) },
LIVE_SESSION_ID,
),
)
compose.waitUntil(15_000) {
historySignInRequired.value &&
!handler.isStreaming.value &&
handler.messages.value.any { it.content == LOCAL_COMPLETION }
}
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
assertFalse(viewModel.isLoadingHistory.value)
assertTrue(handler.messages.value.any { it.content == "Keep this local transcript" })
assertTrue(handler.messages.value.any { it.content == LOCAL_COMPLETION })
assertNull(viewModel.chatFailure.value)
assertExactProfileHistoryOnly(PROFILE_NAME)
}
@Test
fun recoveredCompletion_sessionExpiredHistoryRetainsSettledTranscript() {
bindDashboardHistoryFailure(
body = """{"reason":"session_expired"}""",
profileName = PROFILE_NAME,
)
val now = System.currentTimeMillis()
val contextKey = AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME)
viewModel.setChatTurnCheckpointStore(
MemoryCheckpointStore(
ChatTurnCheckpoint(
contextKey = contextKey,
profileKey = PROFILE_NAME,
sessionId = STORED_SESSION_ID,
liveSessionId = LIVE_SESSION_ID,
transport = "gateway",
user = ChatTurnUserCheckpoint("recovered-user", "Resume this turn", now - 2_000L),
assistant = ChatTurnAssistantCheckpoint(
id = "recovered-assistant",
content = "Recovered partial",
timestamp = now - 1_900L,
),
priorUserMessageCount = 0,
baselineAssistantCount = 0,
startedAt = now - 2_000L,
updatedAt = now,
),
),
)
fixture.recoveryRunning = true
handler.setSessionId(null)
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
fixture.awaitRpc("session.activate")
serverSocket.send(
fixture.event(
"message.delta",
buildJsonObject { put("text", RECOVERED_COMPLETION) },
LIVE_SESSION_ID,
),
)
serverSocket.send(
fixture.event(
"message.complete",
buildJsonObject { put("text", RECOVERED_COMPLETION) },
LIVE_SESSION_ID,
),
)
compose.waitUntil(15_000) {
historySignInRequired.value && !handler.isStreaming.value
}
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
assertFalse(viewModel.isLoadingHistory.value)
assertTrue(
"recovered completion was not retained: ${handler.messages.value}",
handler.messages.value.any { it.content.contains(RECOVERED_COMPLETION.trim()) },
)
assertFalse(handler.messages.value.any { it.isStreaming || it.isThinkingStreaming })
assertNull(viewModel.chatFailure.value)
assertExactProfileHistoryOnly(PROFILE_NAME)
}
private fun bindDashboardHistoryFailure(body: String, profileName: String) {
fixture.profileName = profileName
fixture.historyFailureBody = body
val dashboard = DashboardApiClient(
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
okHttpClient = OkHttpClient(),
)
viewModel.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
dashboard.getSessionMessages(sessionId, profile, mode)
}
viewModel.setDashboardSignInRequiredHandler {
historySignInRequired.value = true
}
}
private fun assertExactProfileHistoryOnly(profileName: String) {
val historyRequests = fixture.historyRequestPaths()
assertTrue("no Dashboard history request was observed", historyRequests.isNotEmpty())
assertTrue(
"history escaped the exact profile: $historyRequests",
historyRequests.all { it.contains("profile=$profileName") },
)
}
private companion object {
const val STORED_SESSION_ID = "20260821_120000_fixture"
const val LIVE_SESSION_ID = "fixture-live-1"
@@ -301,6 +463,23 @@ class GatewayForegroundRecoveryInstrumentedTest {
const val PARTIAL_ANSWER = "Partial foreground answer"
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
const val FOREIGN_ANSWER = "Wrong session content"
const val PROFILE_NAME = "research"
const val LOCAL_COMPLETION = "Completed before Dashboard auth expired."
const val RECOVERED_COMPLETION = " and then recovered to completion."
}
}
private class MemoryCheckpointStore(
private var checkpoint: ChatTurnCheckpoint?,
) : ChatTurnCheckpointStore {
override suspend fun read(): ChatTurnCheckpoint? = checkpoint
override suspend fun write(checkpoint: ChatTurnCheckpoint) {
this.checkpoint = checkpoint
}
override suspend fun clear() {
checkpoint = null
}
}
@@ -320,6 +499,12 @@ internal class AndroidGatewayContractFixture {
@Volatile
var activeSessionStatus: String? = null
@Volatile
var historyFailureBody: String? = null
@Volatile
var profileName: String = "default"
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
sockets.add(webSocket)
@@ -377,6 +562,11 @@ internal class AndroidGatewayContractFixture {
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
)
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
path.startsWith("/api/sessions/") && path.contains("/messages") &&
historyFailureBody != null -> MockResponse()
.setResponseCode(401)
.setHeader("Content-Type", "application/json")
.setBody(historyFailureBody.orEmpty())
else -> MockResponse().setResponseCode(404)
}
}
@@ -388,7 +578,7 @@ internal class AndroidGatewayContractFixture {
put("session_id", sessionId)
put("running", recoveryRunning)
put("status", if (recoveryRunning) "streaming" else "idle")
put("info", buildJsonObject { put("profile_name", "default") })
put("info", buildJsonObject { put("profile_name", profileName) })
}
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
@@ -406,7 +596,7 @@ internal class AndroidGatewayContractFixture {
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
fun awaitRpc(method: String): JsonObject {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
while (System.nanoTime() < deadline) {
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
Thread.sleep(20)
@@ -415,7 +605,7 @@ internal class AndroidGatewayContractFixture {
}
fun awaitRpcCount(method: String, count: Int) {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
while (System.nanoTime() < deadline) {
if (rpcCount(method) >= count) return
Thread.sleep(20)
@@ -425,6 +615,10 @@ internal class AndroidGatewayContractFixture {
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
fun historyRequestPaths(): List<String> = requestPaths.filter {
it.startsWith("/api/sessions/") && it.contains("/messages")
}
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
fun shutdown() {
+4
View File
@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name="com.hermesandroid.relay.ui.screens.BotChatBindingTestActivity"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name="com.hermesandroid.relay.ui.screens.VoiceSettingsDesignQaActivity"
android:exported="true"
@@ -0,0 +1,6 @@
package com.hermesandroid.relay.ui.screens
import androidx.activity.ComponentActivity
/** Empty debug-only host populated by the Bot Chat lifecycle instrumentation. */
class BotChatBindingTestActivity : ComponentActivity()
@@ -1,3 +1,3 @@
v1.14.0 - Connections that follow you
v1.14.0 - Connections, delegated work, Git, and voice
Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.
+106 -41
View File
@@ -1,55 +1,120 @@
{
"schema": 2,
"schema": 3,
"versions": [
{
"version": "1.14.0",
"title": "Connections that follow you",
"title": "Connections, delegated work, Git, and voice",
"date": "2026-08-30",
"highlight": {
"title": "Reliable routes",
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard or Relay authentication.",
"bullets": [
"Keep Chat and sessions on the trusted Dashboard while optional Relay routes recover independently.",
"Preview delegated agent work and use the optional native Git workspace.",
"Use more reliable Continuous voice, Voice Focus, Assistant, Threads, profiles, and Clarify controls."
]
},
"improvements": [
"Wake-word detection now packages a compatible native runtime for every supported ABI.",
"Protected Relay health checks no longer appear as broken routes."
],
"toastDigest": {
"additionalFeatureCount": 2,
"fixCount": 10,
"preview": [
"delegated-agent previews",
"safer voice and sessions"
]
},
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
"sections": [
"summary": "Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.",
"changes": [
{
"header": "Use the best available route",
"bullets": [
"Resolve Dashboard, Relay, and optional API health independently across LAN, Tailscale, and public HTTPS.",
"Keep same-origin Relay ingress on the exact Dashboard origin that owns authentication."
]
"id": "route-aware-connections",
"kind": "improved",
"title": "Connections recover independently",
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.",
"highlight": true
},
{
"header": "Follow active work",
"bullets": [
"Preview delegated-agent lifecycle, progress, tools, and available read-only child history from the parent chat.",
"Review Git status, diffs, branches, staging, commits, and remotes through the optional Relay plugin."
]
"id": "delegated-agent-previews",
"kind": "added",
"title": "Follow delegated-agent activity",
"summary": "See lifecycle, progress, tool previews, and available read-only child history from the parent chat.",
"highlight": true
},
{
"header": "Keep voice and conversations owned correctly",
"bullets": [
"Serialize microphone handoff and keep Voice Focus Stop and steering accessible across active phases.",
"Preserve fresh profile drafts, provisional Thread ownership, Clarify answers, passive observation, and Assistant privacy through reconnects."
]
"id": "native-git-workspace",
"kind": "added",
"title": "Work with repositories from Android",
"summary": "Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.",
"highlight": true
},
{
"id": "voice-focus-controls",
"kind": "improved",
"title": "Steer voice at any time",
"summary": "Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.",
"highlight": true
},
{
"id": "non-blocking-release-notice",
"kind": "improved",
"title": "Release notes stay out of your way",
"summary": "A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings."
},
{
"id": "single-chat-presentation",
"kind": "improved",
"title": "Chat uses one consistent presentation",
"summary": "The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available."
},
{
"id": "wake-word-runtime",
"kind": "fixed",
"title": "Wake-word detection starts reliably",
"summary": "Compatible native voice components are now packaged for every supported phone architecture."
},
{
"id": "sphere-motion",
"kind": "fixed",
"title": "The visible Sphere keeps moving smoothly",
"summary": "Foreground animation no longer falls back to a stepped ambient pulse."
},
{
"id": "continuous-microphone-handoff",
"kind": "fixed",
"title": "Continuous voice keeps the microphone",
"summary": "The next listening turn waits for barge-in recording to release cleanly."
},
{
"id": "fresh-profile-drafts",
"kind": "fixed",
"title": "New chats keep the selected profile",
"summary": "Fresh drafts no longer reopen an older session or carry a Thread route into another profile."
},
{
"id": "provisional-thread-removal",
"kind": "fixed",
"title": "Provisional Threads can be removed safely",
"summary": "Local removal and later session promotion no longer risk duplicate rows or server history."
},
{
"id": "clarify-custom-answers",
"kind": "fixed",
"title": "Clarify keeps custom answers reachable",
"summary": "Other answers, keyboard Send, and expired prompts now behave consistently."
},
{
"id": "passive-session-observation",
"kind": "fixed",
"title": "Browsing no longer interrupts another client",
"summary": "Passive Android observation does not claim a turn owned by Desktop, TUI, or another client."
},
{
"id": "assistant-recovery-privacy",
"kind": "fixed",
"title": "Assistant sessions recover more clearly",
"summary": "No-speech feedback, recreated session state, and keyguard privacy now remain intact."
},
{
"id": "relay-auth-boundaries",
"kind": "fixed",
"title": "Protected Relay routes report the right problem",
"summary": "Authentication challenges are no longer presented as outages, while unsafe routes still fail closed."
},
{
"id": "connection-session-readiness",
"kind": "fixed",
"title": "Connections and sessions become ready sooner",
"summary": "Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history."
}
]
],
"compatibility": [
"Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.",
"The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.",
"Granular Device Control and the system Voice Focus overlay remain available only in the sideload build."
],
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
"sections": []
},
{
"version": "1.13.2",
+29 -8
View File
@@ -1,10 +1,31 @@
v1.14.0 - Connections that follow you
v1.14.0 - Connections, delegated work, Git, and voice
Reliable routes
* Keep Chat and sessions on the trusted Dashboard while optional Relay routes recover independently.
* Preview delegated agent work and use the optional native Git workspace.
* Use more reliable Continuous voice, Voice Focus, Assistant, Threads, profiles, and Clarify controls.
Summary
* Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.
Also improved
* Wake-word detection now packages a compatible native runtime for every supported ABI.
* Protected Relay health checks no longer appear as broken routes.
Highlights
* Connections recover independently — Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.
* Follow delegated-agent activity — See lifecycle, progress, tool previews, and available read-only child history from the parent chat.
* Work with repositories from Android — Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.
* Steer voice at any time — Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.
Improved
* Release notes stay out of your way — A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings.
* Chat uses one consistent presentation — The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available.
Fixed
* Wake-word detection starts reliably — Compatible native voice components are now packaged for every supported phone architecture.
* The visible Sphere keeps moving smoothly — Foreground animation no longer falls back to a stepped ambient pulse.
* Continuous voice keeps the microphone — The next listening turn waits for barge-in recording to release cleanly.
* New chats keep the selected profile — Fresh drafts no longer reopen an older session or carry a Thread route into another profile.
* Provisional Threads can be removed safely — Local removal and later session promotion no longer risk duplicate rows or server history.
* Clarify keeps custom answers reachable — Other answers, keyboard Send, and expired prompts now behave consistently.
* Browsing no longer interrupts another client — Passive Android observation does not claim a turn owned by Desktop, TUI, or another client.
* Assistant sessions recover more clearly — No-speech feedback, recreated session state, and keyguard privacy now remain intact.
* Protected Relay routes report the right problem — Authentication challenges are no longer presented as outages, while unsafe routes still fail closed.
* Connections and sessions become ready sooner — Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history.
Compatibility
* Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.
* The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.
* Granular Device Control and the system Voice Focus overlay remain available only in the sideload build.
@@ -10,6 +10,16 @@ package com.hermesandroid.relay.data
*/
enum class AttachmentState { LOADING, LOADED, FAILED }
/**
* Gateway tool events do not yet expose an output kind before completion.
* Recognize the upstream built-in plus the profile-tool naming convention used
* for image generators without guessing from generic prompt arguments.
*/
internal fun isImageGenerationToolName(name: String): Boolean {
val normalized = name.trim().lowercase()
return normalized == "image_generate" || normalized.endsWith("_create_image")
}
/**
* How the UI should render a loaded attachment. Derived from the MIME type.
* - [IMAGE] inline image (decode bytes / load URI).
@@ -81,6 +81,24 @@ class SupervisedModeStore private constructor(
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
}
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
internal suspend fun disableAllAndRemoveCredential(
parentCredentialKey: Preferences.Key<String>,
) {
dataStore.edit { preferences ->
val decoded = decode(preferences[KEY_POLICIES])
if (decoded.corrupt || decoded.policies.isEmpty()) {
preferences.remove(KEY_POLICIES)
} else {
val disabled = decoded.policies.mapValues { (_, policy) ->
policy.copy(enabled = false).normalized()
}
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
}
preferences.remove(parentCredentialKey)
}
}
private fun decode(raw: String?): DecodeResult {
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
return try {
@@ -0,0 +1,461 @@
package com.hermesandroid.relay.data
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
/** Availability of the app-specific parent credential. */
enum class SupervisedParentAuthStatus {
Missing,
Configured,
Corrupt,
}
/** Input method selected for the app-specific parent credential. */
@Serializable
enum class SupervisedParentCredentialType {
Legacy,
Pin,
Password,
}
@Serializable
private enum class SupervisedRecoveryFormat {
LegacyCode,
WordPhrase,
}
/** Result of a parent-secret or recovery-phrase verification attempt. */
sealed interface SupervisedParentAuthResult {
data object Success : SupervisedParentAuthResult
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
data object Missing : SupervisedParentAuthResult
data object Corrupt : SupervisedParentAuthResult
}
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
data class SupervisedParentEnrollment(val recoveryPhrase: String)
/** Validation result for a new parent PIN or password. */
data class SupervisedParentSecretValidation(
val valid: Boolean,
val message: String? = null,
)
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
interface SupervisedParentAuthenticator {
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
suspend fun enroll(
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
suspend fun change(
currentSecret: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
suspend fun resetWithRecoveryPhrase(
recoveryPhrase: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment>
}
/**
* App-specific parent authentication for Supervised Mode.
*
* This store deliberately does not delegate to Android's device credential: a
* child can legitimately own the PIN or biometrics on their Android profile.
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
* secret and recovery phrase are never persisted.
*/
class SupervisedParentAuthStore private constructor(
private val dataStore: DataStore<Preferences>,
private val iterations: Int,
private val minimumAcceptedIterations: Int,
private val random: SecureRandom,
private val nowMillis: () -> Long,
) : SupervisedParentAuthenticator {
constructor(context: Context) : this(
dataStore = context.applicationContext.relayDataStore,
iterations = DEFAULT_PBKDF2_ITERATIONS,
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
random = SecureRandom(),
nowMillis = System::currentTimeMillis,
)
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
decode(preferences[KEY_RECORD]).status
}
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
decode(preferences[KEY_RECORD]).record?.credentialType
}
override suspend fun enroll(
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
}
runCatching { enrollLocked(newSecret, credentialType) }
}
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
verifyLocked(secret, AuthTarget.ParentSecret)
}
override suspend fun change(
currentSecret: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
else -> Result.failure(ParentAuthenticationException(verified))
}
}
override suspend fun resetWithRecoveryPhrase(
recoveryPhrase: CharArray,
newSecret: CharArray,
credentialType: SupervisedParentCredentialType,
): Result<SupervisedParentEnrollment> = processMutex.withLock {
val validation = validateNewSecret(newSecret, credentialType)
if (!validation.valid) {
return Result.failure(IllegalArgumentException(validation.message))
}
val record = decode(dataStore.data.first()[KEY_RECORD]).record
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
try {
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
else -> Result.failure(ParentAuthenticationException(verified))
}
} finally {
normalizedRecovery.fill('\u0000')
}
}
/**
* Authenticated escape hatch used by the parent controls.
*
* The app-global credential cannot be removed while leaving any supervised
* policy enabled. Every policy is disabled, but its configuration is retained,
* in the same transaction that removes the credential.
*/
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
runCatching {
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
Unit
}
}
private suspend fun enrollLocked(
secret: CharArray,
credentialType: SupervisedParentCredentialType,
): SupervisedParentEnrollment {
require(credentialType != SupervisedParentCredentialType.Legacy)
val recoveryChars = generateRecoveryPhrase().toCharArray()
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
var parentVerifier = ByteArray(0)
var recoveryVerifier = ByteArray(0)
try {
parentVerifier = derive(secret, parentSalt, iterations)
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
val record = PersistedParentAuth(
iterations = iterations,
parentSalt = encode(parentSalt),
parentVerifier = encode(parentVerifier),
recoverySalt = encode(recoverySalt),
recoveryVerifier = encode(recoveryVerifier),
credentialType = credentialType,
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
)
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
return SupervisedParentEnrollment(recoveryChars.concatToString())
} finally {
recoveryChars.fill('\u0000')
parentSalt.fill(0)
recoverySalt.fill(0)
parentVerifier.fill(0)
recoveryVerifier.fill(0)
}
}
private suspend fun verifyLocked(
candidate: CharArray,
target: AuthTarget,
): SupervisedParentAuthResult {
val decoded = decode(dataStore.data.first()[KEY_RECORD])
val record = decoded.record ?: return when (decoded.status) {
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
else -> SupervisedParentAuthResult.Corrupt
}
val now = nowMillis()
if (record.blockedUntilEpochMillis > now) {
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
}
val saltText = when (target) {
AuthTarget.ParentSecret -> record.parentSalt
AuthTarget.RecoveryCode -> record.recoverySalt
}
val verifierText = when (target) {
AuthTarget.ParentSecret -> record.parentVerifier
AuthTarget.RecoveryCode -> record.recoveryVerifier
}
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
val actual = try {
derive(candidate, salt, record.iterations)
} catch (error: Exception) {
Log.w(TAG, "Unable to derive supervised parent verifier", error)
return SupervisedParentAuthResult.Corrupt
} finally {
salt.fill(0)
}
val matches = try {
MessageDigest.isEqual(expected, actual)
} finally {
expected.fill(0)
actual.fill(0)
}
if (matches) {
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
}
return SupervisedParentAuthResult.Success
}
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
val delayMillis = backoffMillis(failures)
save(
record.copy(
failedAttempts = failures,
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
),
)
return if (delayMillis == 0L) {
SupervisedParentAuthResult.Invalid(
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
)
} else {
SupervisedParentAuthResult.Throttled(delayMillis)
}
}
private suspend fun save(record: PersistedParentAuth) {
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
}
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
withContext(Dispatchers.Default) {
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
try {
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
}
private fun decode(raw: String?): DecodedRecord {
if (raw.isNullOrBlank()) {
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
}
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
.getOrElse {
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
}
val valid = record.version == RECORD_VERSION &&
record.algorithm == KDF_ALGORITHM &&
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
record.blockedUntilEpochMillis >= 0
return if (valid) {
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
} else {
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
}
}
private fun generateRecoveryPhrase(): String {
val available = RECOVERY_WORDS.toMutableList()
val selected = buildList(RECOVERY_WORD_COUNT) {
repeat(RECOVERY_WORD_COUNT) {
add(available.removeAt(random.nextInt(available.size)))
}
}
return selected.joinToString("-")
}
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
private fun decodeBytes(value: String): ByteArray? =
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
private fun backoffMillis(failures: Int): Long = when (failures) {
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
FAILURES_BEFORE_BACKOFF -> 30_000L
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
else -> MAX_BACKOFF_MILLIS
}
@Serializable
private data class PersistedParentAuth(
val version: Int = RECORD_VERSION,
val algorithm: String = KDF_ALGORITHM,
val iterations: Int,
val parentSalt: String,
val parentVerifier: String,
val recoverySalt: String,
val recoveryVerifier: String,
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
val failedAttempts: Int = 0,
val blockedUntilEpochMillis: Long = 0L,
)
private data class DecodedRecord(
val status: SupervisedParentAuthStatus,
val record: PersistedParentAuth?,
)
private enum class AuthTarget { ParentSecret, RecoveryCode }
class ParentAuthenticationException(
val authResult: SupervisedParentAuthResult,
) : IllegalStateException("Parent authentication failed: $authResult")
companion object {
private const val TAG = "SupervisedParentAuth"
private const val RECORD_VERSION = 1
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
private const val MIN_ACCEPTED_ITERATIONS = 100_000
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
private const val SALT_BYTES = 16
private const val KEY_BITS = 256
private const val FAILURES_BEFORE_BACKOFF = 5
private const val MAX_TRACKED_FAILURES = 9
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
private const val RECOVERY_WORD_COUNT = 6
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
private val processMutex = Mutex()
fun validateNewSecret(
secret: CharArray,
credentialType: SupervisedParentCredentialType,
): SupervisedParentSecretValidation {
if (secret.size > 64) {
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
}
if (credentialType == SupervisedParentCredentialType.Pin) {
return if (secret.size == 6 && secret.all(Char::isDigit)) {
SupervisedParentSecretValidation(true)
} else {
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
}
}
return if (
credentialType == SupervisedParentCredentialType.Password &&
secret.size >= 8 && secret.any { !it.isWhitespace() }
) {
SupervisedParentSecretValidation(true)
} else {
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
}
}
private fun normalizeRecoveryPhrase(
value: CharArray,
format: SupervisedRecoveryFormat,
): CharArray = when (format) {
SupervisedRecoveryFormat.LegacyCode -> value
.filterNot { it == '-' || it.isWhitespace() }
.joinToString("")
.uppercase()
.toCharArray()
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
.trim()
.lowercase()
.split(Regex("[-\\s]+"))
.filter(String::isNotBlank)
.joinToString("-")
.toCharArray()
}
private val RECOVERY_WORDS = listOf(
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
)
internal fun forTesting(
dataStore: DataStore<Preferences>,
iterations: Int = MIN_ACCEPTED_ITERATIONS,
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
random: SecureRandom = SecureRandom(),
nowMillis: () -> Long = System::currentTimeMillis,
): SupervisedParentAuthStore = SupervisedParentAuthStore(
dataStore = dataStore,
iterations = iterations,
minimumAcceptedIterations = minimumAcceptedIterations,
random = random,
nowMillis = nowMillis,
)
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
}
}
@@ -13,6 +13,7 @@ import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.MoaReference
import com.hermesandroid.relay.data.RealtimeTurnTrace
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.data.VoiceIntentTrace
import com.hermesandroid.relay.network.shared.LocalDispatchResult
import com.hermesandroid.relay.network.upstream.models.MessageItem
@@ -1499,11 +1500,13 @@ class ChatHandler {
// Run the media marker parser on assistant content; strip matched
// lines and queue hits for post-assignment dispatch.
val messageMediaHits = mutableListOf<Pair<String, MediaMarkerHit>>()
val afterMedia = if (role == MessageRole.ASSISTANT && persistedImages.cleanedText.isNotEmpty()) {
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, pendingMediaHits)
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, messageMediaHits)
} else {
persistedImages.cleanedText
}
pendingMediaHits += messageMediaHits
// Cards are synchronous (no async fetch) so we attach them
// straight onto the reconstructed ChatMessage and strip their
@@ -1537,15 +1540,25 @@ class ChatHandler {
val prior = priorById[messageId]
// Outbound attachments: prefer an id-match (covers any future
// user-message id reconciliation), else fall back to the
// content-keyed queue. Inbound attachments are intentionally
// excluded — they come back via the marker re-dispatch.
// content-keyed queue. Inbound attachments normally come back via
// marker re-dispatch. One narrow exception retains a completed
// image_generate result when the immediate post-turn history read
// still lacks its MEDIA marker; otherwise the rendered image
// disappears during the persistence-lag window.
val carriedAttachments = run {
val persistedImagePaths = persistedImages.paths.toHashSet()
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
isImageGenerationToolName(tool.name) &&
tool.isComplete && tool.success != false
}
val byId = prior?.attachments.orEmpty().filter { attachment ->
attachment.relayToken == null ||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
(
role == MessageRole.USER &&
attachment.relayToken in persistedImagePaths
role == MessageRole.ASSISTANT &&
priorGeneratedImage &&
attachment.isImage &&
messageMediaHits.isEmpty()
)
}
when {
@@ -2436,14 +2436,11 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
java.util.IdentityHashMap<Throwable, Boolean>(),
)
while (current != null && seen.add(current)) {
if (
current is DashboardHttpException &&
current.statusCode == 401 &&
(
current.message.orEmpty().contains("no_cookie", ignoreCase = true) ||
current.message.orEmpty().contains("unauthenticated", ignoreCase = true)
)
) {
// Every 401 from an authenticated Dashboard route means the saved
// browser/native session can no longer authorize this request. Older
// gateways used `no_cookie`/`unauthenticated`; current builds may return
// reason codes such as `session_expired`, or no structured body at all.
if (current is DashboardHttpException && current.statusCode == 401) {
return true
}
current = current.cause
@@ -209,6 +209,7 @@ internal class HermesRuntimeBinder(
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
connection.loadProfileScopedMessages(profileName, sessionId, mode)
}
chat.setDashboardSignInRequiredHandler(connection::probeNow)
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
chat.profileSessionDeleter = connection::deleteSession
chat.profileSessionRenamer = connection::renameSession
@@ -144,6 +144,7 @@ import com.hermesandroid.relay.data.VoicePresentationMode
import com.hermesandroid.relay.data.capabilities
import com.hermesandroid.relay.data.displayLabel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -738,6 +739,10 @@ fun RelayApp() {
val pendingAddConnectionJobs = remember {
mutableMapOf<String, kotlinx.coroutines.Job>()
}
var pendingAddConnectionTargetId by rememberSaveable { mutableStateOf<String?>(null) }
val pendingAddConnectionAbortJobs = remember {
mutableMapOf<String, kotlinx.coroutines.Job>()
}
val prepareAddConnection: (String, Boolean) -> Unit = { id, retryRequested ->
val existingJob = pendingAddConnectionJobs[id]
if (shouldStartPairPreparation(existingJob?.isActive == true, retryRequested)) {
@@ -758,6 +763,25 @@ fun RelayApp() {
job.start()
}
}
val abortAddConnection: (String) -> kotlinx.coroutines.Job = { id ->
pendingAddConnectionAbortJobs[id] ?: connectionSwitchScope.launch {
try {
pendingAddConnectionJobs.remove(id)?.cancelAndJoin()
connectionViewModel.discardPlaceholderConnection(id)
} finally {
if (pendingAddConnectionTargetId == id) {
pendingAddConnectionTargetId = null
}
}
}.also { job ->
pendingAddConnectionAbortJobs[id] = job
job.invokeOnCompletion {
if (pendingAddConnectionAbortJobs[id] === job) {
pendingAddConnectionAbortJobs.remove(id)
}
}
}
}
// One-time init: the terminal channel ViewModel registers with the shared
// multiplexer and observes the relay connection state so it can attach/
@@ -1351,6 +1375,9 @@ fun RelayApp() {
currentRoute = currentRoute,
)
if (redirect) {
pendingAddConnectionTargetId?.let { targetId ->
abortAddConnection(targetId).join()
}
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
@@ -2113,10 +2140,20 @@ fun RelayApp() {
?: AgentDisplay.displayModelName(serverModelName)
?: stringResource(R.string.status_model_pending)
val footerModelLabel = compactFooterModelLabel(modelLabel)
val openConnections = {
navController.navigate(Screen.ConnectionsSettings.route) {
launchSingleTop = true
val openConnections: (() -> Unit)? = if (
isSupervisedRouteContentAllowed(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
currentRoute = Screen.ConnectionsSettings.route,
)
) {
{
navController.navigate(Screen.ConnectionsSettings.route) {
launchSingleTop = true
}
}
} else {
null
}
RelayStatusStrip(
leadingBadge = {
@@ -2930,7 +2967,12 @@ fun RelayApp() {
}
composable(Screen.AdvancedSettings.route) {
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
LaunchedEffect(Unit) { navController.popBackStack() }
LaunchedEffect(Unit) {
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
}
}
} else {
AdvancedSettingsScreen(
supervisedPolicy = supervisedPolicy,
@@ -2961,7 +3003,12 @@ fun RelayApp() {
}
composable(Screen.SupervisedControls.route) {
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
LaunchedEffect(Unit) { navController.popBackStack() }
LaunchedEffect(Unit) {
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
launchSingleTop = true
}
}
} else {
SupervisedControlsScreen(
connectionViewModel = connectionViewModel,
@@ -3203,16 +3250,34 @@ fun RelayApp() {
addConnectionEnabled = mayStartAddConnection(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
activeTargetId = pendingAddConnectionTargetId,
),
onAddConnection = {
val id = java.util.UUID.randomUUID().toString()
onAddConnection = addConnection@{
val liveConnectionId = connectionViewModel.activeConnectionId.value
val livePolicyState = supervisedPolicyState.value
?.takeIf { (ownerId, _) -> ownerId == liveConnectionId }
val livePolicy = when {
liveConnectionId == null -> SupervisedModePolicy()
livePolicyState != null -> livePolicyState.second
else -> return@addConnection
}
val liveRoute = navController.currentDestination?.route
val liveParentAccess = parentAccessUnlocked &&
!shouldRelockParentAccess(
supervisedEnabled = livePolicy.enabled,
parentAccessUnlocked = parentAccessUnlocked,
route = liveRoute,
)
runAddConnectionAction(
supervisedEnabled = supervisedPolicy.enabled,
parentAccessUnlocked = parentAccessForCurrentRoute,
navigateToPair = {
supervisedEnabled = livePolicy.enabled,
parentAccessUnlocked = liveParentAccess,
activeTargetId = pendingAddConnectionTargetId,
allocateTarget = { java.util.UUID.randomUUID().toString() },
recordTarget = { id -> pendingAddConnectionTargetId = id },
navigateToPair = { id ->
navController.navigate(Screen.Pair.route(connectionId = id))
},
prepareConnection = { prepareAddConnection(id, false) },
prepareConnection = { id -> prepareAddConnection(id, false) },
)
},
onBack = { navController.popBackStack() },
@@ -3356,9 +3421,15 @@ fun RelayApp() {
if (connectionIdArg != null && pairDraftId == connectionIdArg) {
connectionSwitchScope.launch {
connectionViewModel.commitConnectionDraft(connectionIdArg)
if (pendingAddConnectionTargetId == connectionIdArg) {
pendingAddConnectionTargetId = null
}
navController.popBackStack()
}
} else {
if (pendingAddConnectionTargetId == connectionIdArg) {
pendingAddConnectionTargetId = null
}
navController.popBackStack()
}
},
@@ -3378,6 +3449,9 @@ fun RelayApp() {
runCatching {
connectionViewModel.commitConnectionDraft(targetId)
}.onSuccess {
if (pendingAddConnectionTargetId == targetId) {
pendingAddConnectionTargetId = null
}
android.util.Log.i(
"GatewayPairFlow",
"Opening Dashboard sign-in for staged gateway",
@@ -3414,14 +3488,12 @@ fun RelayApp() {
// never got a pairedAt stamp.
if (connectionIdArg != null) {
connectionSwitchScope.launch {
// If Back wins the race with background
// preparation, wait until the placeholder
// exists before attempting to discard it.
pendingAddConnectionJobs.remove(connectionIdArg)?.join()
connectionViewModel.discardPlaceholderConnection(connectionIdArg)
abortAddConnection(connectionIdArg).join()
navController.popBackStack()
}
} else {
navController.popBackStack()
}
navController.popBackStack()
},
)
}
@@ -15,18 +15,24 @@ internal fun isSupervisedRouteAllowed(route: String?, parentAccessUnlocked: Bool
internal fun mayStartAddConnection(
supervisedEnabled: Boolean,
parentAccessUnlocked: Boolean,
): Boolean = !supervisedEnabled || parentAccessUnlocked
activeTargetId: String? = null,
): Boolean = activeTargetId == null && (!supervisedEnabled || parentAccessUnlocked)
internal inline fun runAddConnectionAction(
supervisedEnabled: Boolean,
parentAccessUnlocked: Boolean,
navigateToPair: () -> Unit,
prepareConnection: () -> Unit,
): Boolean {
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked)) return false
navigateToPair()
prepareConnection()
return true
activeTargetId: String?,
allocateTarget: () -> String,
recordTarget: (String) -> Unit,
navigateToPair: (String) -> Unit,
prepareConnection: (String) -> Unit,
): String? {
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked, activeTargetId)) return null
val targetId = allocateTarget()
recordTarget(targetId)
navigateToPair(targetId)
prepareConnection(targetId)
return targetId
}
/** Do not inspect or mutate a NavController until its first destination exists. */
@@ -132,12 +138,10 @@ internal fun sanitizeSupervisedChatRouteArgs(
}
}
/** A disabled policy may become active only after an enrolled credential succeeds. */
/** A disabled policy may become active only after the app-specific parent credential succeeds. */
internal fun mayEnableSupervisedMode(
policy: SupervisedModePolicy,
deviceSecure: Boolean,
deviceCredentialConfirmed: Boolean,
parentCredentialConfirmed: Boolean,
): Boolean = !policy.enabled &&
policy.isConfigured &&
deviceSecure &&
deviceCredentialConfirmed
parentCredentialConfirmed
@@ -57,6 +57,7 @@ import androidx.compose.ui.unit.IntSize
import androidx.annotation.RequiresApi
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import java.util.Locale
@@ -65,7 +66,6 @@ import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.sin
private const val IMAGE_GENERATION_TOOL = "image_generate"
private const val GRID_COLUMNS = 42
private const val GRID_ROWS = 24
private const val DEFAULT_ANIMATION_DURATION_MS = 4_800
@@ -134,11 +134,11 @@ internal fun resolveImageGenerationVisualStyle(
}
internal fun ToolCall.showsImageGenerationPlaceholder(): Boolean =
!isComplete && name.trim().lowercase() == IMAGE_GENERATION_TOOL
!isComplete && isImageGenerationToolName(name)
internal fun imageGenerationStartedAt(toolCalls: List<ToolCall>): Long? =
toolCalls.lastOrNull {
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
isImageGenerationToolName(it.name)
}?.startedAt
internal fun formatGenerationDuration(elapsedMillis: Long): String =
@@ -155,7 +155,7 @@ internal fun shouldShowImageGenerationPlaceholder(
hasMediaResult: Boolean,
): Boolean {
val imageCalls = toolCalls.filter {
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
isImageGenerationToolName(it.name)
}
if (imageCalls.any { !it.isComplete }) return true
return !hasMediaResult &&
@@ -83,6 +83,7 @@ import com.hermesandroid.relay.data.HermesCardAction
import com.hermesandroid.relay.data.MediaSettingsRepository
import com.hermesandroid.relay.data.MessageDeliveryStatus
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.data.parseChatQuotedPrompt
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
@@ -292,9 +293,7 @@ fun MessageBubble(
append(streamingStatusLabel ?: visibleMessageContent.take(100))
}
val hasImageGenerationCall = remember(message.toolCalls) {
message.toolCalls.any {
it.name.trim().lowercase() == "image_generate"
}
message.toolCalls.any { isImageGenerationToolName(it.name) }
}
val imageGenerationStartMillis = remember(message.toolCalls) {
imageGenerationStartedAt(message.toolCalls)
@@ -43,6 +43,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ToolCall
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
private val TOOL_ACTIVITY_PET_ROUTES = setOf("chat")
@@ -101,7 +102,8 @@ internal fun ToolCall.requiresStandaloneToolSurface(): Boolean {
!error.isNullOrBlank() ||
outputRisk != null ||
normalized in FILE_EDIT_TOOLS ||
normalized in ATTENTION_TOOLS
normalized in ATTENTION_TOOLS ||
isImageGenerationToolName(name)
}
internal data class ToolActivityCounts(
@@ -294,7 +294,55 @@ fun VersionNotesBlock(
) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
val highlight = entry.highlight
if (highlight == null) {
if (entry.changes.isNotEmpty()) {
if (showVersionLine) {
Text(
text = entry.versionLine(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
entry.title?.takeIf { it.isNotBlank() }?.let { title ->
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
}
}
entry.summary?.takeIf { it.isNotBlank() }?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
)
}
val highlights = entry.highlightedChanges()
if (highlights.isNotEmpty()) {
ReleaseSectionTitle(stringResource(R.string.changelog_highlights))
ReleaseChangeList(highlights)
}
listOf(
CHANGE_KIND_ADDED to R.string.changelog_added,
CHANGE_KIND_IMPROVED to R.string.changelog_improved,
CHANGE_KIND_FIXED to R.string.changelog_fixed,
).forEach { (kind, label) ->
val changes = entry.remainingChangesOfKind(kind)
if (changes.isNotEmpty()) {
ReleaseSectionTitle(stringResource(label))
ReleaseChangeList(changes)
}
}
if (entry.compatibility.isNotEmpty()) {
ReleaseSectionTitle(stringResource(R.string.changelog_compatibility))
VersionNotesBody(
listOf(WhatsNewGroup(header = null, bullets = entry.compatibility)),
)
}
} else if (highlight == null) {
if (showVersionLine) {
Text(
text = entry.subtitle(),
@@ -340,6 +388,47 @@ fun VersionNotesBlock(
}
}
@Composable
private fun ReleaseSectionTitle(title: String) {
Text(
text = title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(top = 6.dp),
)
}
@Composable
private fun ColumnScope.ReleaseChangeList(changes: List<ChangelogChange>) {
changes.forEach { change ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "•",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = change.title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
change.summary?.takeIf { it.isNotBlank() }?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
}
// ──────────────────────────────────────────────────────────────────────────
// Structured changelog model + loader (kotlinx.serialization).
// ──────────────────────────────────────────────────────────────────────────
@@ -363,16 +452,37 @@ data class ChangelogHighlight(
@Serializable
data class ChangelogToastDigest(
val additionalFeatureCount: Int = 0,
val improvementCount: Int = 0,
val fixCount: Int = 0,
val preview: List<String> = emptyList(),
)
const val CHANGE_KIND_ADDED = "added"
const val CHANGE_KIND_IMPROVED = "improved"
const val CHANGE_KIND_FIXED = "fixed"
/** One complete, user-visible change in a release. */
@Serializable
data class ChangelogChange(
val id: String,
val kind: String,
val title: String,
val summary: String? = null,
val highlight: Boolean = false,
) {
fun fallbackText(): String =
summary?.takeIf { it.isNotBlank() }?.let { "$title — $it" } ?: title
}
/** A single released version's user-facing notes. */
@Serializable
data class ChangelogVersion(
val version: String,
val title: String? = null,
val date: String? = null,
val summary: String? = null,
val changes: List<ChangelogChange> = emptyList(),
val compatibility: List<String> = emptyList(),
val highlight: ChangelogHighlight? = null,
val improvements: List<String> = emptyList(),
val toastDigest: ChangelogToastDigest? = null,
@@ -393,8 +503,48 @@ data class ChangelogVersion(
return "v$version$datePart"
}
fun highlightedChanges(): List<ChangelogChange> = changes.filter { it.highlight }
fun remainingChanges(): List<ChangelogChange> = changes.filterNot { it.highlight }
fun remainingChangesOfKind(kind: String): List<ChangelogChange> =
remainingChanges().filter { it.kind == kind }
/** Derive compact toast metadata from the same changes the expanded view renders. */
fun resolvedToastDigest(): ChangelogToastDigest? {
if (changes.isEmpty()) return toastDigest
val remaining = remainingChanges()
if (remaining.isEmpty()) return null
return ChangelogToastDigest(
additionalFeatureCount = remaining.count { it.kind == CHANGE_KIND_ADDED },
improvementCount = remaining.count { it.kind == CHANGE_KIND_IMPROVED },
fixCount = remaining.count { it.kind == CHANGE_KIND_FIXED },
preview = remaining.take(2).map { it.title },
)
}
fun toGroups(): List<WhatsNewGroup> =
highlight?.let { curated ->
if (changes.isNotEmpty()) {
buildList {
val highlights = highlightedChanges()
if (highlights.isNotEmpty()) {
add(WhatsNewGroup("Highlights", highlights.map { it.fallbackText() }))
}
listOf(
CHANGE_KIND_ADDED to "Added",
CHANGE_KIND_IMPROVED to "Improved",
CHANGE_KIND_FIXED to "Fixed",
).forEach { (kind, label) ->
val items = remainingChangesOfKind(kind)
if (items.isNotEmpty()) {
add(WhatsNewGroup(label, items.map { it.fallbackText() }))
}
}
if (compatibility.isNotEmpty()) {
add(WhatsNewGroup("Compatibility", compatibility))
}
}
} else highlight?.let { curated ->
buildList {
add(WhatsNewGroup(curated.title.takeIf { it.isNotBlank() }, curated.bullets))
if (improvements.isNotEmpty()) {
@@ -185,6 +185,10 @@ internal fun WhatsNewToastContent(
) {
val title = stringResource(R.string.whats_new_title)
val highlight = entry.highlight
val digest = entry.resolvedToastDigest()
val releaseTitle = entry.title?.takeIf(String::isNotBlank) ?: highlight?.title.orEmpty()
val releaseSummary = entry.summary?.takeIf(String::isNotBlank)
?: highlight?.summary?.takeIf(String::isNotBlank)
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
@@ -220,14 +224,14 @@ internal fun WhatsNewToastContent(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = highlight?.title ?: entry.title.orEmpty(),
text = releaseTitle,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
highlight?.summary?.takeIf(String::isNotBlank)?.let { summary ->
releaseSummary?.let { summary ->
Text(
text = summary,
style = MaterialTheme.typography.bodySmall,
@@ -251,9 +255,9 @@ internal fun WhatsNewToastContent(
)
}
}
entry.toastDigest?.takeIf {
it.additionalFeatureCount > 0 || it.fixCount > 0
}?.let { digest ->
digest?.takeIf {
it.additionalFeatureCount > 0 || it.improvementCount > 0 || it.fixCount > 0
}?.let { resolvedDigest ->
HorizontalDivider(
modifier = Modifier.padding(horizontal = 16.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.32f),
@@ -272,21 +276,30 @@ internal fun WhatsNewToastContent(
) {
Column(modifier = Modifier.weight(1f)) {
val counts = buildList {
if (digest.additionalFeatureCount > 0) {
if (resolvedDigest.additionalFeatureCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_additional_feature_count,
digest.additionalFeatureCount,
digest.additionalFeatureCount,
resolvedDigest.additionalFeatureCount,
resolvedDigest.additionalFeatureCount,
),
)
}
if (digest.fixCount > 0) {
if (resolvedDigest.improvementCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_improvement_count,
resolvedDigest.improvementCount,
resolvedDigest.improvementCount,
),
)
}
if (resolvedDigest.fixCount > 0) {
add(
pluralStringResource(
R.plurals.changelog_fix_count,
digest.fixCount,
digest.fixCount,
resolvedDigest.fixCount,
resolvedDigest.fixCount,
),
)
}
@@ -298,11 +311,11 @@ internal fun WhatsNewToastContent(
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
text = digest.preview.joinToString(", ") + "…",
text = resolvedDigest.preview.joinToString(", ") + "…",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -56,11 +56,21 @@ import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.ui.components.MessageBubble
import com.hermesandroid.relay.ui.theme.RelayRefresh
import com.hermesandroid.relay.viewmodel.ChatViewModel
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import java.io.File
import kotlinx.coroutines.flow.Flow
internal typealias BotChatHistoryLoader = suspend (
profileName: String,
sessionId: String,
mode: SessionMessageLoadMode,
) -> Result<List<MessageItem>>
internal typealias BotChatProfileIconFlow = (connectionId: String, profileName: String) -> Flow<String?>
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -74,14 +84,52 @@ fun BotChatScreen(
connectionViewModel: ConnectionViewModel,
onBack: () -> Unit,
) {
val handler = remember(route.key) { ChatHandler() }
BotChatScreen(
route = route,
bot = bot,
sessionId = sessionId,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = chatViewModel,
onBack = onBack,
handlerFactory = ::ChatHandler,
historyLoader = { profileName, storedSessionId, mode ->
dashboardClient.getSessionMessages(
sessionId = storedSessionId,
profile = profileName,
mode = mode,
)
},
profileIconFlow = connectionViewModel::profileIconFlow,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun BotChatScreen(
route: BotGatewayRoute,
bot: BotRosterEntry,
sessionId: String,
gatewayClient: GatewayChatClient,
dashboardClient: DashboardApiClient,
chatViewModel: ChatViewModel,
onBack: () -> Unit,
handlerFactory: () -> ChatHandler,
historyLoader: BotChatHistoryLoader,
profileIconFlow: BotChatProfileIconFlow,
) {
val handler = remember(route.key) { handlerFactory() }
val context = LocalContext.current
val messages by chatViewModel.messages.collectAsState()
val isStreaming by chatViewModel.isStreaming.collectAsState()
// This route owns the handler but binds it to the ViewModel only after the
// first composition. Collecting delegated ViewModel getters here can pin
// Compose to their empty pre-bind fallback when history settles before the
// next frame. Observe the route-owned source directly so StateFlow replay
// covers fast history, live streaming, completion, and errors.
val messages by handler.messages.collectAsState()
val isStreaming by handler.isStreaming.collectAsState()
val isLoading by chatViewModel.isLoadingHistory.collectAsState()
val error by chatViewModel.error.collectAsState()
val iconPath by connectionViewModel
.profileIconFlow(route.connectionId, route.profileName)
val error by handler.error.collectAsState()
val iconPath by profileIconFlow(route.connectionId, route.profileName)
.collectAsState(initial = null)
val listState = rememberLazyListState()
var composer by remember(route.key, sessionId) { mutableStateOf("") }
@@ -101,11 +149,7 @@ fun BotChatScreen(
selected?.name == route.profileName
}
chatViewModel.setProfileMessageLoaderWithMode { _, storedSessionId, mode ->
dashboardClient.getSessionMessages(
sessionId = storedSessionId,
profile = route.profileName,
mode = mode,
)
historyLoader(route.profileName, storedSessionId, mode)
}
chatViewModel.updateApiClient(null)
chatViewModel.updateGatewayClient(gatewayClient)
@@ -265,6 +265,7 @@ import com.hermesandroid.relay.ui.components.ToolTranscriptItem
import com.hermesandroid.relay.ui.components.groupTranscriptTools
import com.hermesandroid.relay.ui.components.isVisibleForToolDisplay
import com.hermesandroid.relay.ui.components.showsImageGenerationPlaceholder
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.VoiceModeOverlay
import com.hermesandroid.relay.ui.LocalSnackbarHost
import com.hermesandroid.relay.ui.showHumanError
@@ -1228,7 +1229,7 @@ fun ChatScreen(
buildMap {
messages.forEach { message ->
val generationCount = message.toolCalls.count {
it.name.trim().equals("image_generate", ignoreCase = true)
isImageGenerationToolName(it.name)
}
if (generationCount > 0) {
put(message.uiKey, nextOrdinal + generationCount - 1)
@@ -0,0 +1,863 @@
package com.hermesandroid.relay.ui.screens
import android.content.ClipData
import android.content.Intent
import android.content.ClipboardManager
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Backspace
import androidx.compose.material.icons.filled.Dialpad
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.hermesandroid.relay.data.SupervisedParentAuthResult
import com.hermesandroid.relay.data.SupervisedParentAuthStore
import com.hermesandroid.relay.data.SupervisedParentAuthenticator
import com.hermesandroid.relay.data.SupervisedParentCredentialType
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import kotlinx.coroutines.launch
@Composable
internal fun SupervisedParentVerifyDialog(
store: SupervisedParentAuthenticator,
onDismiss: () -> Unit,
onVerified: () -> Unit,
onUseRecoveryCode: () -> Unit,
) {
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
var selectedLegacyType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
?: selectedLegacyType
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun verify(candidateText: String) {
if (busy) return
busy = true
scope.launch {
val candidate = candidateText.toCharArray()
val result = try {
store.verify(candidate)
} finally {
candidate.fill('\u0000')
}
busy = false
when (result) {
SupervisedParentAuthResult.Success -> onVerified()
else -> error = result.toUserMessage()
}
}
}
ParentAuthDialogSurface(
step = null,
onBack = if (storedType == SupervisedParentCredentialType.Legacy && inputType != null) {
{ selectedLegacyType = null; error = null }
} else {
onDismiss
},
) {
when (inputType) {
SupervisedParentCredentialType.Pin -> PinEntryScreen(
title = "Parent PIN",
subtitle = "Enter your 6-digit PIN.",
busy = busy,
error = error,
onComplete = ::verify,
onUseRecovery = onUseRecoveryCode,
)
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
busy = busy,
error = error,
onSubmit = ::verify,
onUseRecovery = onUseRecoveryCode,
)
else -> CredentialChoiceScreen(
title = "How do you enter your parent credential?",
subtitle = "This existing setup predates the PIN/password choice.",
onSelected = { selectedLegacyType = it },
)
}
}
}
@Composable
internal fun SupervisedParentSetupDialog(
store: SupervisedParentAuthenticator,
currentSecretRequired: Boolean,
onDismiss: () -> Unit,
onEnrolled: (SupervisedParentEnrollment) -> Unit,
) {
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
var stage by remember(currentSecretRequired) {
mutableStateOf(if (currentSecretRequired) SetupStage.VerifyCurrent else SetupStage.Choose)
}
var legacyInputType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var currentSecret by remember { mutableStateOf("") }
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun enroll(newSecretText: String) {
val type = credentialType ?: return
busy = true
scope.launch {
val current = currentSecret.toCharArray()
val replacement = newSecretText.toCharArray()
val result = try {
if (currentSecretRequired) store.change(current, replacement, type)
else store.enroll(replacement, type)
} finally {
current.fill('\u0000')
replacement.fill('\u0000')
}
busy = false
result.fold(onSuccess = onEnrolled, onFailure = { error = it.toUserMessage() })
}
}
fun verifyCurrent(candidateText: String) {
busy = true
scope.launch {
val candidate = candidateText.toCharArray()
val result = try { store.verify(candidate) } finally { candidate.fill('\u0000') }
busy = false
if (result == SupervisedParentAuthResult.Success) {
currentSecret = candidateText
error = null
stage = SetupStage.Choose
} else {
error = result.toUserMessage()
}
}
}
val backAction: () -> Unit = when (stage) {
SetupStage.VerifyCurrent, SetupStage.Choose -> onDismiss
SetupStage.Pin, SetupStage.Password -> {
{ stage = SetupStage.Choose; credentialType = null; error = null }
}
}
val step = when (stage) {
SetupStage.VerifyCurrent -> 1 to 3
SetupStage.Choose -> if (currentSecretRequired) 2 to 3 else 1 to 2
SetupStage.Pin, SetupStage.Password -> if (currentSecretRequired) 3 to 3 else 2 to 2
}
ParentAuthDialogSurface(step = step, onBack = backAction) {
when (stage) {
SetupStage.VerifyCurrent -> {
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
?: legacyInputType
when (inputType) {
SupervisedParentCredentialType.Pin -> PinEntryScreen(
title = "Current parent PIN",
subtitle = "Confirm before changing parent access.",
busy = busy,
error = error,
onComplete = ::verifyCurrent,
)
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
title = "Current parent password",
busy = busy,
error = error,
onSubmit = ::verifyCurrent,
)
else -> CredentialChoiceScreen(
title = "How do you enter the current credential?",
subtitle = "Choose the input that matches the existing setup.",
onSelected = { legacyInputType = it },
)
}
}
SetupStage.Choose -> CredentialChoiceScreen(
title = if (currentSecretRequired) "Choose new parent access" else "Choose parent access",
subtitle = "Pick one way to unlock parent settings. You can change it later.",
onSelected = {
credentialType = it
stage = if (it == SupervisedParentCredentialType.Pin) SetupStage.Pin else SetupStage.Password
},
)
SetupStage.Pin -> PinSetupScreen(
busy = busy,
error = error,
onComplete = ::enroll,
)
SetupStage.Password -> PasswordSetupScreen(
busy = busy,
error = error,
onComplete = ::enroll,
)
}
}
}
@Composable
internal fun SupervisedParentRecoveryDialog(
store: SupervisedParentAuthenticator,
onDismiss: () -> Unit,
onReset: (SupervisedParentEnrollment) -> Unit,
) {
var stage by remember { mutableStateOf(RecoveryStage.Phrase) }
var recoveryPhrase by remember { mutableStateOf("") }
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun reset(newSecretText: String) {
val type = credentialType ?: return
busy = true
scope.launch {
val recovery = recoveryPhrase.toCharArray()
val replacement = newSecretText.toCharArray()
val result = try {
store.resetWithRecoveryPhrase(recovery, replacement, type)
} finally {
recovery.fill('\u0000')
replacement.fill('\u0000')
}
busy = false
result.fold(onSuccess = onReset, onFailure = { error = it.toUserMessage() })
}
}
val step = when (stage) {
RecoveryStage.Phrase -> 1 to 3
RecoveryStage.Choose -> 2 to 3
RecoveryStage.Pin, RecoveryStage.Password -> 3 to 3
}
ParentAuthDialogSurface(
step = step,
onBack = when (stage) {
RecoveryStage.Phrase -> onDismiss
RecoveryStage.Choose -> ({ stage = RecoveryStage.Phrase })
RecoveryStage.Pin, RecoveryStage.Password -> ({ stage = RecoveryStage.Choose })
},
) {
when (stage) {
RecoveryStage.Phrase -> RecoveryPhraseInputScreen(
value = recoveryPhrase,
error = error,
onValueChange = { recoveryPhrase = it; error = null },
onContinue = { stage = RecoveryStage.Choose },
)
RecoveryStage.Choose -> CredentialChoiceScreen(
title = "Choose new parent access",
subtitle = "Your recovery phrase will be replaced after reset.",
onSelected = {
credentialType = it
stage = if (it == SupervisedParentCredentialType.Pin) RecoveryStage.Pin
else RecoveryStage.Password
},
)
RecoveryStage.Pin -> PinSetupScreen(busy = busy, error = error, onComplete = ::reset)
RecoveryStage.Password -> PasswordSetupScreen(busy = busy, error = error, onComplete = ::reset)
}
}
}
@Composable
internal fun SupervisedParentRecoveryCodeDialog(
enrollment: SupervisedParentEnrollment,
onDone: () -> Unit,
) {
val context = LocalContext.current
val clipboard = remember(context) {
context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager
}
ParentAuthDialogSurface(step = 3 to 3, onBack = null) {
SupervisedParentRecoveryCodeContent(
enrollment = enrollment,
onShare = {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, enrollment.recoveryPhrase)
}
context.startActivity(Intent.createChooser(intent, "Share recovery phrase"))
},
onCopy = {
clipboard.setPrimaryClip(
ClipData.newPlainText("Parent recovery phrase", enrollment.recoveryPhrase),
)
},
onDone = onDone,
)
}
}
@Composable
private fun ParentAuthDialogSurface(
step: Pair<Int, Int>?,
onBack: (() -> Unit)?,
content: @Composable () -> Unit,
) {
Dialog(
onDismissRequest = { onBack?.invoke() },
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
ParentAuthScreenSurface(step = step, onBack = onBack, content = content)
}
}
@Composable
internal fun ParentAuthScreenSurface(
step: Pair<Int, Int>?,
onBack: (() -> Unit)?,
content: @Composable () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
.imePadding()
.padding(horizontal = 24.dp),
) {
Row(
modifier = Modifier.fillMaxWidth().height(64.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (onBack != null) {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
} else {
Spacer(Modifier.size(48.dp))
}
step?.let { (current, total) ->
Row(
modifier = Modifier.weight(1f),
horizontalArrangement = Arrangement.Center,
) {
repeat(total) { index ->
Box(
Modifier
.padding(horizontal = 3.dp)
.size(width = 46.dp, height = 4.dp)
.clip(CircleShape)
.background(
if (index < current) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.outlineVariant,
),
)
}
}
Text(
"$current of $total",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} ?: Spacer(Modifier.weight(1f))
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopCenter,
) {
content()
}
}
}
}
@Composable
internal fun CredentialChoiceScreen(
title: String,
subtitle: String,
onSelected: (SupervisedParentCredentialType) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = 28.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, subtitle)
Spacer(Modifier.height(28.dp))
CredentialChoiceRow(
icon = { Icon(Icons.Filled.Dialpad, contentDescription = null) },
title = "Use a PIN",
subtitle = "Fast on this phone · 6 digits",
onClick = { onSelected(SupervisedParentCredentialType.Pin) },
)
Spacer(Modifier.height(12.dp))
CredentialChoiceRow(
icon = { Icon(Icons.Filled.Lock, contentDescription = null) },
title = "Use a password",
subtitle = "Works with password managers · 8+ characters",
onClick = { onSelected(SupervisedParentCredentialType.Password) },
)
Spacer(Modifier.height(16.dp))
Text(
"PIN and password are separate choices.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun CredentialChoiceRow(
icon: @Composable () -> Unit,
title: String,
subtitle: String,
onClick: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
Row(
modifier = Modifier.padding(horizontal = 18.dp, vertical = 18.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
modifier = Modifier.size(48.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
) {
Box(contentAlignment = Alignment.Center) { icon() }
}
Column(Modifier.weight(1f).padding(horizontal = 16.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("›", fontSize = 30.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
internal fun PinEntryScreen(
title: String,
subtitle: String,
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
onUseRecovery: (() -> Unit)? = null,
) {
var pin by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, subtitle)
Spacer(Modifier.height(28.dp))
PinDots(pin.length)
Spacer(Modifier.height(26.dp))
NumericKeypad(
enabled = !busy,
onDigit = { digit ->
if (pin.length < 6) {
val next = pin + digit
pin = next
if (next.length == 6) onComplete(next)
}
},
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
)
AuthError(error)
onUseRecovery?.let {
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
}
}
}
@Composable
internal fun PinSetupScreen(
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
) {
var firstPin by remember { mutableStateOf<String?>(null) }
var pin by remember(firstPin) { mutableStateOf("") }
var localError by remember { mutableStateOf<String?>(null) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(
if (firstPin == null) "Create a parent PIN" else "Confirm parent PIN",
if (firstPin == null) "Choose a 6-digit PIN." else "Enter the same 6 digits again.",
)
Spacer(Modifier.height(28.dp))
PinDots(pin.length)
Spacer(Modifier.height(26.dp))
NumericKeypad(
enabled = !busy,
onDigit = { digit ->
if (pin.length < 6) {
val next = pin + digit
pin = next
if (next.length == 6) {
if (firstPin == null) {
firstPin = next
} else if (firstPin == next) {
onComplete(next)
} else {
localError = "The PINs do not match. Try again."
firstPin = null
}
}
}
},
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
)
AuthError(localError ?: error)
}
}
@Composable
private fun NumericKeypad(
enabled: Boolean,
onDigit: (String) -> Unit,
onBackspace: () -> Unit,
) {
val rows = listOf(listOf("1", "2", "3"), listOf("4", "5", "6"), listOf("7", "8", "9"))
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
rows.forEach { row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
row.forEach { digit -> KeypadButton(digit, enabled) { onDigit(digit) } }
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Spacer(Modifier.size(width = 92.dp, height = 58.dp))
KeypadButton("0", enabled) { onDigit("0") }
Surface(
modifier = Modifier.size(width = 92.dp, height = 58.dp).clickable(enabled = enabled, onClick = onBackspace),
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
) {
Box(contentAlignment = Alignment.Center) {
Icon(Icons.AutoMirrored.Filled.Backspace, contentDescription = "Delete digit")
}
}
}
}
}
@Composable
private fun KeypadButton(label: String, enabled: Boolean, onClick: () -> Unit) {
Button(
onClick = onClick,
enabled = enabled,
modifier = Modifier.size(width = 92.dp, height = 58.dp),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurface,
),
) {
Text(label, style = MaterialTheme.typography.headlineSmall)
}
}
@Composable
private fun PinDots(count: Int) {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
repeat(6) { index ->
Box(
Modifier
.size(22.dp)
.clip(CircleShape)
.then(
if (index < count) Modifier.background(MaterialTheme.colorScheme.primary)
else Modifier.border(2.dp, MaterialTheme.colorScheme.outline, CircleShape),
),
)
}
}
}
@Composable
internal fun PasswordSetupScreen(
busy: Boolean,
error: String?,
onComplete: (String) -> Unit,
) {
var password by remember { mutableStateOf("") }
var confirmation by remember { mutableStateOf("") }
var reveal by remember { mutableStateOf(false) }
var localError by remember { mutableStateOf<String?>(null) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading("Create a parent password", "Use 8 or more characters.")
Spacer(Modifier.height(28.dp))
PasswordField("Password", password, { password = it; localError = null }, reveal, { reveal = !reveal })
Spacer(Modifier.height(12.dp))
PasswordField("Confirm password", confirmation, { confirmation = it; localError = null }, reveal, { reveal = !reveal }, ImeAction.Done)
AuthError(localError ?: error)
Spacer(Modifier.height(20.dp))
Button(
enabled = !busy && password.isNotEmpty() && confirmation.isNotEmpty(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = {
when {
password != confirmation -> localError = "The passwords do not match."
!SupervisedParentAuthStore.validateNewSecret(
password.toCharArray(),
SupervisedParentCredentialType.Password,
).valid -> localError = "Use a password with at least 8 characters."
else -> onComplete(password)
}
},
) { Text(if (busy) "Saving…" else "Continue") }
}
}
@Composable
internal fun PasswordVerifyScreen(
title: String = "Parent password",
busy: Boolean,
error: String?,
onSubmit: (String) -> Unit,
onUseRecovery: (() -> Unit)? = null,
) {
var password by remember { mutableStateOf("") }
var reveal by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(title, "Enter your password.")
Spacer(Modifier.height(28.dp))
PasswordField("Password", password, { password = it }, reveal, { reveal = !reveal }, ImeAction.Done)
AuthError(error)
Spacer(Modifier.height(20.dp))
Button(
enabled = !busy && password.isNotEmpty(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = { onSubmit(password) },
) { Text(if (busy) "Checking…" else "Unlock") }
onUseRecovery?.let {
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
}
}
}
@Composable
private fun PasswordField(
label: String,
value: String,
onValueChange: (String) -> Unit,
reveal: Boolean,
onReveal: () -> Unit,
imeAction: ImeAction = ImeAction.Next,
) {
OutlinedTextField(
value = value,
onValueChange = { if (it.length <= 64) onValueChange(it) },
modifier = Modifier.fillMaxWidth(),
label = { Text(label) },
visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),
trailingIcon = {
IconButton(onClick = onReveal) {
Icon(
if (reveal) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = if (reveal) "Hide password" else "Show password",
)
}
},
singleLine = true,
)
}
@Composable
private fun RecoveryPhraseInputScreen(
value: String,
error: String?,
onValueChange: (String) -> Unit,
onContinue: () -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading("Enter recovery phrase", "Paste or type the six words.")
Spacer(Modifier.height(28.dp))
OutlinedTextField(
value = value,
onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(),
label = { Text("Recovery phrase") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done),
minLines = 2,
)
AuthError(error)
Spacer(Modifier.height(20.dp))
Button(
enabled = value.isNotBlank(),
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onContinue,
) { Text("Continue") }
}
}
@Composable
internal fun SupervisedParentRecoveryCodeContent(
enrollment: SupervisedParentEnrollment,
onShare: () -> Unit = {},
onCopy: () -> Unit = {},
onDone: () -> Unit = {},
) {
val words = enrollment.recoveryPhrase.split('-')
val displayPhrase = if (words.size == 6) {
words.take(3).joinToString("-") + "\n" + words.drop(3).joinToString("-")
} else {
enrollment.recoveryPhrase
}
Column(
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AuthHeading(
"Save your recovery phrase",
"This is the only way to reset parent access if you forget it.",
)
Spacer(Modifier.height(28.dp))
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
SelectionContainer {
Text(
displayPhrase,
modifier = Modifier.padding(20.dp),
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.titleMedium.copy(lineHeight = 28.sp),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
)
}
}
Spacer(Modifier.height(18.dp))
Text(
"Send it somewhere parent-only, then delete the message or saved copy from this phone.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(24.dp))
Button(
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onShare,
) {
Icon(Icons.Filled.Share, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text("Share")
}
Spacer(Modifier.height(10.dp))
OutlinedButton(
modifier = Modifier.fillMaxWidth().height(52.dp),
onClick = onCopy,
) { Text("Copy phrase") }
TextButton(onClick = onDone) { Text("Done") }
}
}
@Composable
private fun AuthHeading(title: String, subtitle: String) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(8.dp))
Text(
subtitle,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun AuthError(error: String?) {
error?.let {
Spacer(Modifier.height(14.dp))
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
}
private fun SupervisedParentAuthResult.toUserMessage(): String = when (this) {
SupervisedParentAuthResult.Success -> ""
is SupervisedParentAuthResult.Invalid -> if (attemptsBeforeDelay > 0) {
"Incorrect parent credential. $attemptsBeforeDelay attempts remain before a delay."
} else {
"Incorrect parent credential."
}
is SupervisedParentAuthResult.Throttled -> {
val seconds = ((retryAfterMillis + 999L) / 1_000L).coerceAtLeast(1)
"Too many attempts. Try again in $seconds seconds."
}
SupervisedParentAuthResult.Missing -> "Parent access has not been set up."
SupervisedParentAuthResult.Corrupt -> "Parent access data is unavailable. Supervised Mode remains locked."
}
private fun Throwable.toUserMessage(): String = when (this) {
is IllegalArgumentException -> message ?: "The new parent credential is not valid."
is SupervisedParentAuthStore.ParentAuthenticationException -> authResult.toUserMessage()
else -> "Parent access could not be updated. Try again."
}
private enum class SetupStage { VerifyCurrent, Choose, Pin, Password }
private enum class RecoveryStage { Phrase, Choose, Pin, Password }
@@ -1,8 +1,5 @@
package com.hermesandroid.relay.ui.screens
import android.app.Activity
import android.app.KeyguardManager
import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
@@ -52,7 +49,9 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -65,6 +64,9 @@ import com.hermesandroid.relay.data.AgentDisplay
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
import com.hermesandroid.relay.data.SupervisedModePolicy
import com.hermesandroid.relay.data.SupervisedParentAuthStatus
import com.hermesandroid.relay.data.SupervisedParentAuthStore
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.data.SupervisedSessionActions
import com.hermesandroid.relay.data.SupervisedVisibilityPreset
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
@@ -77,6 +79,7 @@ import com.hermesandroid.relay.ui.theme.LocalBrand
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
import com.hermesandroid.relay.ui.theme.gradientBorder
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
import kotlinx.coroutines.launch
/**
* The settings surface available while supervised mode is locked.
@@ -100,28 +103,29 @@ fun SupervisedSettingsScreen(
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
val profileAlias by connectionViewModel.profileDisplayAlias.collectAsState()
val isDarkTheme = LocalBrand.current.isDark
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
initialValue = null,
key1 = parentAuthStore,
) {
parentAuthStore.statusFlow.collect { value = it }
}
var authError by remember { mutableStateOf<String?>(null) }
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
var showAbout by remember { mutableStateOf(false) }
val credentialLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
authError = null
onParentAccessGranted()
}
}
fun requestParentAccess() {
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
val intent = keyguard?.createConfirmDeviceCredentialIntent(
"Parent access",
"Unlock full Hermes settings and supervised-mode controls. Device credentials verify an enrolled device user, not a distinct parent identity.",
)
if (intent == null) {
authError = "Set a device screen lock before using parent access."
} else {
credentialLauncher.launch(intent)
when (parentAuthStatus) {
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
SupervisedParentAuthStatus.Missing -> {
authError = "This legacy supervised policy has no app-specific parent credential and stays locked. " +
"Reset this app's local data, reconnect, and configure parent access before enabling Supervised Mode again."
}
SupervisedParentAuthStatus.Corrupt -> {
authError = "Parent access data is unavailable. Supervised Mode remains locked."
}
null -> authError = "Parent access is still loading."
}
}
@@ -186,7 +190,7 @@ fun SupervisedSettingsScreen(
SupervisedNavigationRow(
icon = Icons.Filled.Lock,
title = "Parent access",
subtitle = "Unlock full settings with the device screen lock",
subtitle = "Unlock full settings with the app parent PIN or password",
onClick = ::requestParentAccess,
isDarkTheme = isDarkTheme,
)
@@ -217,6 +221,38 @@ fun SupervisedSettingsScreen(
},
)
}
when (parentAuthDialog) {
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onVerified = {
parentAuthDialog = null
authError = null
onParentAccessGranted()
},
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
)
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onReset = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
else -> Unit
}
pendingEnrollment?.let { enrollment ->
SupervisedParentRecoveryCodeDialog(
enrollment = enrollment,
onDone = {
pendingEnrollment = null
authError = null
onParentAccessGranted()
},
)
}
}
/** Restricted appearance editor backed by the supervised policy, not global theme settings. */
@@ -293,42 +329,41 @@ fun SupervisedControlsScreen(
onReturnToSupervisedView: () -> Unit,
) {
val context = LocalContext.current
val keyguardManager = remember(context) {
context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
initialValue = null,
key1 = parentAuthStore,
) {
parentAuthStore.statusFlow.collect { value = it }
}
val deviceSecure = keyguardManager?.isDeviceSecure == true
val isDarkTheme = LocalBrand.current.isDark
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
var showProfilePicker by remember { mutableStateOf(false) }
var sessionActionsExpanded by remember { mutableStateOf(false) }
var enableAuthError by remember { mutableStateOf<String?>(null) }
var enableRequested by remember { mutableStateOf(false) }
val enableCredentialLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) { result ->
val shouldEnable = enableRequested && mayEnableSupervisedMode(
policy = policy,
deviceSecure = deviceSecure,
deviceCredentialConfirmed = result.resultCode == Activity.RESULT_OK,
)
enableRequested = false
if (shouldEnable) {
enableAuthError = null
onPolicyChange(policy.copy(enabled = true))
}
}
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
var enableAfterEnrollment by remember { mutableStateOf(false) }
var showRemoveCredentialConfirm by remember { mutableStateOf(false) }
var removeCredentialBusy by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
fun requestFirstEnable() {
val intent = keyguardManager?.createConfirmDeviceCredentialIntent(
"Enable supervised mode",
"Confirm with an enrolled device credential. This does not verify a distinct parent identity.",
)
if (!deviceSecure || intent == null) {
enableAuthError = "Set a secure device screen lock before enabling supervised mode."
if (!policy.isConfigured) {
enableAuthError = "Choose an agent profile before enabling Supervised Mode."
return
}
enableRequested = true
enableCredentialLauncher.launch(intent)
when (parentAuthStatus) {
SupervisedParentAuthStatus.Missing -> {
enableAfterEnrollment = true
parentAuthDialog = ParentAuthDialog.Setup
}
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
SupervisedParentAuthStatus.Corrupt -> {
enableAuthError = "Parent access data is unavailable. Reset local app data before enabling Supervised Mode."
}
null -> enableAuthError = "Parent access is still loading."
}
}
Scaffold(
@@ -360,14 +395,18 @@ fun SupervisedControlsScreen(
subtitle = when {
policy.pinnedProfileName.isNullOrBlank() ->
"Choose an agent profile before enabling"
!deviceSecure ->
"Set a device screen lock before enabling"
parentAuthStatus == SupervisedParentAuthStatus.Missing ->
"Set an app-specific parent PIN or password"
else ->
"Show only the approved Android chat surfaces"
},
checked = policy.enabled,
enabled = policy.enabled ||
(!policy.pinnedProfileName.isNullOrBlank() && deviceSecure),
(!policy.pinnedProfileName.isNullOrBlank() &&
parentAuthStatus in setOf(
SupervisedParentAuthStatus.Missing,
SupervisedParentAuthStatus.Configured,
)),
onCheckedChange = { enabled ->
if (enabled) requestFirstEnable()
else onPolicyChange(policy.copy(enabled = false))
@@ -404,7 +443,7 @@ fun SupervisedControlsScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
"Android device credentials authenticate an enrolled device user; they do not establish a separate parent identity. Use a parent-only device credential or managed-device policy where that distinction matters.",
"Parent access uses an app-specific PIN or password, separate from the supervised user's Android screen lock and biometrics.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -713,14 +752,42 @@ fun SupervisedControlsScreen(
tint = MaterialTheme.colorScheme.primary,
)
Column(Modifier.padding(start = 12.dp)) {
Text("Device authentication", style = MaterialTheme.typography.titleSmall)
Text("App parent credential", style = MaterialTheme.typography.titleSmall)
Text(
"Full features require the device screen lock. This verifies an enrolled device user, not a distinct parent identity.",
when (parentAuthStatus) {
SupervisedParentAuthStatus.Configured -> "A parent PIN or password is configured for this app."
SupervisedParentAuthStatus.Missing -> "Set a parent PIN or password before enabling Supervised Mode."
SupervisedParentAuthStatus.Corrupt -> "Parent access data is unavailable and fails closed."
null -> "Loading parent access…"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
when (parentAuthStatus) {
SupervisedParentAuthStatus.Missing -> OutlinedButton(
onClick = {
enableAfterEnrollment = false
parentAuthDialog = ParentAuthDialog.Setup
},
) { Text("Set parent PIN or password") }
SupervisedParentAuthStatus.Configured -> {
OutlinedButton(onClick = { parentAuthDialog = ParentAuthDialog.Change }) {
Text("Change parent PIN or password")
}
TextButton(onClick = { parentAuthDialog = ParentAuthDialog.Recovery }) {
Text("Reset with recovery phrase")
}
TextButton(onClick = { showRemoveCredentialConfirm = true }) {
Text(
"Remove parent credential",
color = MaterialTheme.colorScheme.error,
)
}
}
else -> Unit
}
HorizontalDivider()
SupervisedSwitchRow(
title = "Relock when the app leaves the screen",
@@ -794,6 +861,118 @@ fun SupervisedControlsScreen(
},
)
}
if (showRemoveCredentialConfirm) {
RemoveParentCredentialDialog(
busy = removeCredentialBusy,
onDismiss = { showRemoveCredentialConfirm = false },
onConfirm = {
removeCredentialBusy = true
scope.launch {
val result = parentAuthStore.clearCredentialAndDisablePolicies()
removeCredentialBusy = false
result.fold(
onSuccess = {
showRemoveCredentialConfirm = false
enableAuthError = null
onBack()
},
onFailure = {
enableAuthError = "Parent access could not be removed. Try again."
},
)
}
},
)
}
when (parentAuthDialog) {
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onVerified = {
parentAuthDialog = null
enableAuthError = null
if (mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
onPolicyChange(policy.copy(enabled = true))
}
},
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
)
ParentAuthDialog.Setup -> SupervisedParentSetupDialog(
store = parentAuthStore,
currentSecretRequired = false,
onDismiss = {
parentAuthDialog = null
enableAfterEnrollment = false
},
onEnrolled = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
ParentAuthDialog.Change -> SupervisedParentSetupDialog(
store = parentAuthStore,
currentSecretRequired = true,
onDismiss = { parentAuthDialog = null },
onEnrolled = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
store = parentAuthStore,
onDismiss = { parentAuthDialog = null },
onReset = { enrollment ->
parentAuthDialog = null
pendingEnrollment = enrollment
},
)
null -> Unit
}
pendingEnrollment?.let { enrollment ->
SupervisedParentRecoveryCodeDialog(
enrollment = enrollment,
onDone = {
pendingEnrollment = null
enableAuthError = null
if (enableAfterEnrollment && mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
onPolicyChange(policy.copy(enabled = true))
}
enableAfterEnrollment = false
},
)
}
}
@Composable
internal fun RemoveParentCredentialDialog(
busy: Boolean,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
title = { Text("Remove parent credential?") },
text = {
Text(
"This disables Supervised Mode on every connection and removes the app-wide " +
"PIN or password and recovery phrase. Your supervised settings and toggles are kept. " +
"Hermes sessions and server history are not deleted.",
)
},
confirmButton = {
TextButton(enabled = !busy, onClick = onConfirm) {
Text(
if (busy) "Removing…" else "Remove",
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(enabled = !busy, onClick = onDismiss) { Text("Cancel") }
},
)
}
@Composable
@@ -984,6 +1163,13 @@ private fun sessionActionsSummary(actions: SupervisedSessionActions): String = w
else -> "${actions.enabledCount} of ${SupervisedSessionActions.TOTAL} allowed"
}
private enum class ParentAuthDialog {
Verify,
Setup,
Change,
Recovery,
}
@Composable
private fun SessionActionSwitch(
title: String,
@@ -126,6 +126,7 @@ import com.hermesandroid.relay.notifications.InteractionRequestNotifier
import com.hermesandroid.relay.reliability.ReliabilityCenter
import com.hermesandroid.relay.reliability.SessionResetEvidence
import com.hermesandroid.relay.ui.components.ServerImageResult
import com.hermesandroid.relay.data.isImageGenerationToolName
import com.hermesandroid.relay.ui.components.SlashCommand
import com.hermesandroid.relay.voice.RealtimeTurnSyncBuilder
import com.hermesandroid.relay.voice.VoiceIntentSyncBuilder
@@ -3183,6 +3184,7 @@ class ChatViewModel : ViewModel() {
) {
val handler = chatHandler ?: return
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) return
val contextKey = activeProfileContextKey
gatewayHistoryReconcileJob?.cancel()
gatewayHistoryReconcileJob = viewModelScope.launch {
val expected = expectedAssistantText?.trim()?.takeIf { it.isNotEmpty() }
@@ -3215,7 +3217,28 @@ class ChatViewModel : ViewModel() {
}
val transcriptSnapshot = handler.messages.value
val serverMessages = loadGatewaySessionHistory(storedSessionId)
val serverMessages = try {
loadGatewaySessionHistory(
sessionId = storedSessionId,
requireProfileScope = true,
)
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
// A live completion is already visible and settled locally.
// History auth loss must retain that transcript and promote
// the existing sign-in recovery instead of escaping this
// Main-scope coroutine and crashing the app.
if (
chatHandler === handler &&
activeProfileContextKey == contextKey &&
handler.currentSessionId.value == storedSessionId
) {
publishHistoryLoadFailure(storedSessionId, e)
}
gatewayHistoryReconcileJob = null
return@launch
}
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) {
return@launch
}
@@ -3848,6 +3871,12 @@ class ChatViewModel : ViewModel() {
profileSessionPageLister = lister
}
private var dashboardSignInRequiredHandler: (() -> Unit)? = null
fun setDashboardSignInRequiredHandler(handler: () -> Unit) {
dashboardSignInRequiredHandler = handler
}
/**
* Deletes a session scoped to the active profile on gateway connections
* (dashboard `DELETE /api/sessions/{id}?profile=`). The write twin of
@@ -4236,7 +4265,19 @@ class ChatViewModel : ViewModel() {
}
private fun publishHistoryLoadFailure(sessionId: String, error: Throwable) {
if (error.isDashboardSignInRequiredFailure()) return
if (error.isDashboardSignInRequiredFailure()) {
dashboardSignInRequiredHandler?.invoke()
DiagnosticsLog.record(
category = DiagnosticCategory.Auth,
severity = DiagnosticSeverity.Warning,
title = "Dashboard sign-in required for chat history",
detail = "stored_session=$sessionId; dashboard_auth=required",
operation = "load chat history",
endpointRole = "gateway",
suggestion = "Sign in to Dashboard on the active route, then retry this conversation.",
)
return
}
val rawError = error.message?.takeIf { it.isNotBlank() }
?: "The active profile's conversation history could not be reached."
_chatFailure.value = ChatFailureNotice(
@@ -5382,6 +5423,7 @@ class ChatViewModel : ViewModel() {
// recovery state. Preserve cached history and
// mark the directory unavailable without also
// emitting a generic turn/error toast.
dashboardSignInRequiredHandler?.invoke()
} else if (scoped != null) {
// The shared API list belongs to the launch/default
// database. Preserve the current profile's rows and
@@ -5404,7 +5446,9 @@ class ChatViewModel : ViewModel() {
)
retryUnavailable = true
retryReadiness = retryReadiness || !e.isSessionReadTimeout()
if (!e.isDashboardSignInRequiredFailure()) {
if (e.isDashboardSignInRequiredFailure()) {
dashboardSignInRequiredHandler?.invoke()
} else {
emitError(
e,
context = if (profileSessionLister != null) {
@@ -7823,13 +7867,39 @@ class ChatViewModel : ViewModel() {
if (!queuedSuccessorPending.get()) {
val expectedSessionId = checkpoint.sessionId
viewModelScope.launch {
val history = loadSessionHistory(expectedSessionId)
if (handler.currentSessionId.value == expectedSessionId && history.isNotEmpty()) {
handler.loadMessageHistory(history)
refreshSessions()
scheduleTitleReconcile(expectedSessionId)
try {
val history = loadSessionHistory(expectedSessionId)
if (
handler.currentSessionId.value == expectedSessionId &&
history.isNotEmpty()
) {
handler.loadMessageHistory(history)
clearMatchingHistoryLoadFailure(expectedSessionId)
}
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
// Recovery completion has already settled the
// local turn. Keep it visible and route an
// expired Dashboard session to sign-in.
if (
chatHandler === handler &&
activeProfileContextKey == checkpoint.contextKey &&
handler.currentSessionId.value == expectedSessionId
) {
publishHistoryLoadFailure(expectedSessionId, e)
}
} finally {
if (
chatHandler === handler &&
activeProfileContextKey == checkpoint.contextKey &&
handler.currentSessionId.value == expectedSessionId
) {
refreshSessions()
scheduleTitleReconcile(expectedSessionId)
}
drainQueue()
}
drainQueue()
}
}
}
@@ -9566,7 +9636,7 @@ class ChatViewModel : ViewModel() {
ensurePostInterimMessage()
streamDeltas.flushNow()
val alreadyObserved =
toolName == "image_generate" &&
isImageGenerationToolName(toolName) &&
observedImageToolStates.putIfAbsent(toolCallId, "running") != null
if (!alreadyObserved) {
handler.onToolCallStart(currentMessageId, toolCallId, toolName, argsPreview)
@@ -9693,6 +9763,7 @@ class ChatViewModel : ViewModel() {
// tool.complete. The structured reload recovers those calls without ever
// parsing assistant prose and retains the profile-aware history boundary.
val sid = handler.currentSessionId.value
val historyContextKey = activeProfileContextKey
// A turn that ended in an error (gateway ❌ lifecycle → "Error" badge)
// has NO assistant message persisted server-side, so reconciling the
// server transcript would WIPE the just-shown error bubble (the user
@@ -9711,34 +9782,54 @@ class ChatViewModel : ViewModel() {
)
}
viewModelScope.launch {
if (!turnErrored && !gatewayHistoryReconcileRequired) {
// Profile-aware read: a gateway turn on a non-default profile
// persists into THAT profile's own state.db, so the bare
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
// → a silent wipe of the just-finished turn. loadSessionHistory
// prefers the `?profile=` dashboard loader on gateway connections.
val serverMessages = loadSessionHistory(sid)
val missingPersistedToolActivity =
completedTransport == "gateway" &&
handler.hasMissingPersistedToolActivity(serverMessages)
if (shouldReloadHistoryAfterSuccessfulTurn(
actualTransport = completedTransport,
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
missingPersistedToolActivity = missingPersistedToolActivity,
)
) {
handler.loadMessageHistory(serverMessages)
try {
if (!turnErrored && !gatewayHistoryReconcileRequired) {
// Profile-aware read: a gateway turn on a non-default profile
// persists into THAT profile's own state.db, so the bare
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
// → a silent wipe of the just-finished turn. loadSessionHistory
// prefers the `?profile=` dashboard loader on gateway connections.
val serverMessages = loadSessionHistory(sid)
val missingPersistedToolActivity =
completedTransport == "gateway" &&
handler.hasMissingPersistedToolActivity(serverMessages)
if (shouldReloadHistoryAfterSuccessfulTurn(
actualTransport = completedTransport,
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
missingPersistedToolActivity = missingPersistedToolActivity,
)
) {
handler.loadMessageHistory(serverMessages)
clearMatchingHistoryLoadFailure(sid)
}
}
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
if (
chatHandler === handler &&
activeProfileContextKey == historyContextKey &&
handler.currentSessionId.value == sid
) {
publishHistoryLoadFailure(sid, e)
}
} finally {
// Re-sync the drawer now that the turn is persisted server-side.
// The only other auto-refresh fires ~160ms after session creation
// (RelayApp) — mid-stream, BEFORE the new session's first message
// is persisted, so a brand-new chat would otherwise stay missing
// from the drawer (carried only by the optimistic row) until a
// manual reload. By message.complete the dashboard list includes it.
if (
chatHandler === handler &&
activeProfileContextKey == historyContextKey &&
handler.currentSessionId.value == sid
) {
refreshSessions()
scheduleTitleReconcile(sid)
}
drainQueue()
}
// Re-sync the drawer now that the turn is persisted server-side.
// The only other auto-refresh fires ~160ms after session creation
// (RelayApp) — mid-stream, BEFORE the new session's first message
// is persisted, so a brand-new chat would otherwise stay missing
// from the drawer (carried only by the optimistic row) until a
// manual reload. By message.complete the dashboard list includes it.
refreshSessions()
scheduleTitleReconcile(sid)
drainQueue()
}
Unit
} else {
+10 -1
View File
@@ -584,6 +584,11 @@
<string name="changelog_state_collapsed">Recolhido</string>
<string name="changelog_installed">Instalado</string>
<string name="changelog_also_improved">Também melhorado</string>
<string name="changelog_highlights">Destaques</string>
<string name="changelog_added">Adicionado</string>
<string name="changelog_improved">Melhorado</string>
<string name="changelog_fixed">Corrigido</string>
<string name="changelog_compatibility">Compatibilidade</string>
<string name="changelog_toast_also">Também: %1$s</string>
<string name="changelog_view_all">Ver tudo</string>
<plurals name="changelog_additional_feature_count">
@@ -594,6 +599,10 @@
<item quantity="one">%1$d correção</item>
<item quantity="other">%1$d correções</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d melhoria</item>
<item quantity="other">%1$d melhorias</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnóstico</string>
<string name="diag_back">Voltar</string>
@@ -3239,7 +3248,7 @@
<string name="whats_new_full_history">Ver histórico completo</string>
<string name="whats_new_no_notes">Nenhuma nota de versão disponível</string>
<string name="whats_new_title">Novidades</string>
<string name="whats_new_subtitle">Destaques da versão mais recente</string>
<string name="whats_new_subtitle">Destaques e detalhes completos da versão</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Acesso temporário à tela expirou</string>
<string name="bridge_notification_auto_disabled_body">Inspeção e controle da tela foram desativados após ociosidade. As outras permissões não mudaram.</string>
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">已收起</string>
<string name="changelog_installed">已安装</string>
<string name="changelog_also_improved">其他改进</string>
<string name="changelog_highlights">亮点</string>
<string name="changelog_added">新增</string>
<string name="changelog_improved">改进</string>
<string name="changelog_fixed">修复</string>
<string name="changelog_compatibility">兼容性</string>
<string name="changelog_toast_also">另外:%1$s</string>
<string name="changelog_view_all">查看全部</string>
<plurals name="changelog_additional_feature_count">
@@ -629,6 +634,9 @@
<plurals name="changelog_fix_count">
<item quantity="other">%1$d 项修复</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="other">%1$d 项改进</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">诊断</string>
@@ -3339,7 +3347,7 @@
<string name="whats_new_full_history">查看完整历史记录</string>
<string name="whats_new_no_notes">无可用的发布说明</string>
<string name="whats_new_title">更新内容</string>
<string name="whats_new_subtitle">最新版本亮点</string>
<string name="whats_new_subtitle">亮点和完整版本详情</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">限时屏幕访问已到期</string>
<string name="bridge_notification_auto_disabled_body">空闲后,屏幕检查和控制已关闭。其他授权保持不变。</string>
+10 -1
View File
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">Eingeklappt</string>
<string name="changelog_installed">Installiert</string>
<string name="changelog_also_improved">Außerdem verbessert</string>
<string name="changelog_highlights">Highlights</string>
<string name="changelog_added">Hinzugefügt</string>
<string name="changelog_improved">Verbessert</string>
<string name="changelog_fixed">Behoben</string>
<string name="changelog_compatibility">Kompatibilität</string>
<string name="changelog_toast_also">Außerdem: %1$s</string>
<string name="changelog_view_all">Alle anzeigen</string>
<plurals name="changelog_additional_feature_count">
@@ -631,6 +636,10 @@
<item quantity="one">%1$d Fehlerbehebung</item>
<item quantity="other">%1$d Fehlerbehebungen</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d Verbesserung</item>
<item quantity="other">%1$d Verbesserungen</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnose</string>
@@ -3407,7 +3416,7 @@
<string name="whats_new_full_history">Vollständigen Verlauf anzeigen</string>
<string name="whats_new_no_notes">Keine Versionshinweise verfügbar</string>
<string name="whats_new_title">Neuigkeiten</string>
<string name="whats_new_subtitle">Highlights der neuesten Version</string>
<string name="whats_new_subtitle">Highlights und vollständige Versionsdetails</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Zeitgesteuerter Bildschirmzugriff abgelaufen</string>
<string name="bridge_notification_auto_disabled_body">Bildschirmprüfung und -steuerung sind nach Inaktivität aus. Andere Berechtigungen bleiben unverändert.</string>
+10 -1
View File
@@ -556,6 +556,11 @@
<string name="changelog_state_collapsed">Contraído</string>
<string name="changelog_installed">Instalada</string>
<string name="changelog_also_improved">También mejorado</string>
<string name="changelog_highlights">Destacados</string>
<string name="changelog_added">Añadido</string>
<string name="changelog_improved">Mejorado</string>
<string name="changelog_fixed">Corregido</string>
<string name="changelog_compatibility">Compatibilidad</string>
<string name="changelog_toast_also">También: %1$s</string>
<string name="changelog_view_all">Ver todo</string>
<plurals name="changelog_additional_feature_count">
@@ -566,6 +571,10 @@
<item quantity="one">%1$d corrección</item>
<item quantity="other">%1$d correcciones</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d mejora</item>
<item quantity="other">%1$d mejoras</item>
</plurals>
<string name="diag_title">Diagnóstico</string>
<string name="diag_back">Atrás</string>
<string name="diag_status">Estado</string>
@@ -3071,7 +3080,7 @@
<string name="whats_new_full_history">Ver historial completo</string>
<string name="whats_new_no_notes">No hay notas de versión disponibles</string>
<string name="whats_new_title">¿Qué hay de nuevo?</string>
<string name="whats_new_subtitle">Novedades de la última versión</string>
<string name="whats_new_subtitle">Destacados y detalles completos de la versión</string>
<string name="bridge_notification_auto_disabled_title">Acceso de pantalla temporizado vencido</string>
<string name="bridge_notification_auto_disabled_body">La inspección y el control de pantalla están desactivados tras la inactividad. Los demás permisos no cambian.</string>
<string name="bridge_notification_control_title">El agente Hermes tiene control del dispositivo.</string>
+9 -1
View File
@@ -621,6 +621,11 @@
<string name="changelog_state_collapsed">折りたたみ済み</string>
<string name="changelog_installed">インストール済み</string>
<string name="changelog_also_improved">その他の改善</string>
<string name="changelog_highlights">ハイライト</string>
<string name="changelog_added">追加</string>
<string name="changelog_improved">改善</string>
<string name="changelog_fixed">修正</string>
<string name="changelog_compatibility">互換性</string>
<string name="changelog_toast_also">その他: %1$s</string>
<string name="changelog_view_all">すべて表示</string>
<plurals name="changelog_additional_feature_count">
@@ -629,6 +634,9 @@
<plurals name="changelog_fix_count">
<item quantity="other">%1$d 件の修正</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="other">%1$d 件の改善</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">診断</string>
@@ -3415,7 +3423,7 @@
<string name="whats_new_full_history">全履歴を表示</string>
<string name="whats_new_no_notes">リリースノートはありません</string>
<string name="whats_new_title">新機能</string>
<string name="whats_new_subtitle">最新リリースのハイライト</string>
<string name="whats_new_subtitle">ハイライトと完全なリリース詳細</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">時間制限付き画面アクセスの期限切れ</string>
<string name="bridge_notification_auto_disabled_body">操作がなかったため、画面の検査と操作をオフにしました。他の許可は変更されません。</string>
+12 -1
View File
@@ -599,6 +599,11 @@
<string name="changelog_state_collapsed">Свернуто</string>
<string name="changelog_installed">Установлено</string>
<string name="changelog_also_improved">Также улучшено</string>
<string name="changelog_highlights">Основное</string>
<string name="changelog_added">Добавлено</string>
<string name="changelog_improved">Улучшено</string>
<string name="changelog_fixed">Исправлено</string>
<string name="changelog_compatibility">Совместимость</string>
<string name="changelog_toast_also">Также: %1$s</string>
<string name="changelog_view_all">Показать все</string>
<plurals name="changelog_additional_feature_count">
@@ -613,6 +618,12 @@
<item quantity="many">%1$d исправлений</item>
<item quantity="other">%1$d исправления</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d улучшение</item>
<item quantity="few">%1$d улучшения</item>
<item quantity="many">%1$d улучшений</item>
<item quantity="other">%1$d улучшения</item>
</plurals>
<string name="diag_title">Диагностика</string>
<string name="diag_back">Назад</string>
<string name="diag_status">Статус</string>
@@ -3275,7 +3286,7 @@
<string name="whats_new_full_history">Просмотреть полную историю</string>
<string name="whats_new_no_notes">Примечания к выпуску недоступны</string>
<string name="whats_new_title">Что нового</string>
<string name="whats_new_subtitle">Последние обновления</string>
<string name="whats_new_subtitle">Основное и полный список изменений</string>
<string name="bridge_notification_auto_disabled_title">Временный доступ к экрану истек</string>
<string name="bridge_notification_auto_disabled_body">Просмотр и управление экраном отключены после бездействия. Другие разрешения не изменены.</string>
<string name="bridge_notification_control_title">Агент Гермес имеет управление устройством</string>
+10 -1
View File
@@ -666,6 +666,11 @@
<string name="changelog_state_collapsed">Collapsed</string>
<string name="changelog_installed">Installed</string>
<string name="changelog_also_improved">Also improved</string>
<string name="changelog_highlights">Highlights</string>
<string name="changelog_added">Added</string>
<string name="changelog_improved">Improved</string>
<string name="changelog_fixed">Fixed</string>
<string name="changelog_compatibility">Compatibility</string>
<string name="changelog_toast_also">Also: %1$s</string>
<string name="changelog_view_all">View all</string>
<plurals name="changelog_additional_feature_count">
@@ -676,6 +681,10 @@
<item quantity="one">%1$d fix</item>
<item quantity="other">%1$d fixes</item>
</plurals>
<plurals name="changelog_improvement_count">
<item quantity="one">%1$d improvement</item>
<item quantity="other">%1$d improvements</item>
</plurals>
<!-- DiagnosticsScreen -->
<string name="diag_title">Diagnostics</string>
@@ -3781,7 +3790,7 @@
<string name="whats_new_full_history">View full history</string>
<string name="whats_new_no_notes">No release notes available</string>
<string name="whats_new_title">What\u0027s new</string>
<string name="whats_new_subtitle">Latest release highlights</string>
<string name="whats_new_subtitle">Highlights and complete release details</string>
<!-- Localization guardrail additions for current dev surfaces -->
<string name="bridge_notification_auto_disabled_title">Timed screen access expired</string>
<string name="bridge_notification_auto_disabled_body">Screen inspection and control are off after being idle. Other grants are unchanged.</string>
@@ -0,0 +1,260 @@
package com.hermesandroid.relay.data
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import java.util.concurrent.atomic.AtomicLong
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class SupervisedParentAuthStoreTest {
@Test
fun `new credential policy accepts strong pins and passwords`() {
assertFalse(SupervisedParentAuthStore.validateNewSecret("12345".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertTrue(SupervisedParentAuthStore.validateNewSecret("123456".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("1234567".toCharArray(), SupervisedParentCredentialType.Pin).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("short".toCharArray(), SupervisedParentCredentialType.Password).valid)
assertTrue(SupervisedParentAuthStore.validateNewSecret("long passphrase".toCharArray(), SupervisedParentCredentialType.Password).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret(" ".repeat(8).toCharArray(), SupervisedParentCredentialType.Password).valid)
assertFalse(SupervisedParentAuthStore.validateNewSecret("x".repeat(65).toCharArray(), SupervisedParentCredentialType.Password).valid)
}
@Test
fun `enrollment stores only salted PBKDF2 verifiers and returns six word recovery phrase`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
val enrollment = store.enroll(
"correct horse".toCharArray(),
SupervisedParentCredentialType.Password,
).getOrThrow()
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
assertEquals(6, enrollment.recoveryPhrase.split('-').size)
assertEquals(6, enrollment.recoveryPhrase.split('-').distinct().size)
assertTrue(raw.contains("PBKDF2WithHmacSHA256"))
assertTrue(raw.contains("\"iterations\":1"))
assertFalse(raw.contains("correct horse"))
assertFalse(raw.contains(enrollment.recoveryPhrase))
assertTrue(raw.contains("\"credentialType\":\"Password\""))
assertTrue(raw.contains("\"recoveryFormat\":\"WordPhrase\""))
val salts = Regex("\"(?:parentSalt|recoverySalt)\":\"([^\"]+)\"")
.findAll(raw).map { it.groupValues[1] }.toList()
assertEquals(2, salts.size)
assertNotEquals(salts[0], salts[1])
}
@Test
fun `production enrollment records 310000 rounds`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = SupervisedParentAuthStore.forTesting(
dataStore = dataStore,
iterations = 310_000,
)
store.enroll("production-strength".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(
dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting]
.orEmpty().contains("\"iterations\":310000"),
)
}
@Test
fun `verification is fail closed when missing or corrupt`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
assertEquals(SupervisedParentAuthStatus.Missing, store.statusFlow.first())
assertEquals(SupervisedParentAuthResult.Missing, store.verify("anything".toCharArray()))
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "not-json" }
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
assertEquals(SupervisedParentAuthResult.Corrupt, store.verify("anything".toCharArray()))
}
@Test
fun `unsupported or weakened records fail closed`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
dataStore.edit {
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"version\":1", "\"version\":2")
}
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
dataStore.edit {
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"iterations\":1", "\"iterations\":0")
}
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
}
@Test
fun `records created before credential type selection remain verifiable`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val current = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
val legacy = current
.replace(Regex(",\"credentialType\":\"Password\""), "")
.replace(Regex(",\"recoveryFormat\":\"WordPhrase\""), "")
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = legacy }
assertEquals(SupervisedParentCredentialType.Legacy, store.credentialTypeFlow.first())
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
}
@Test
fun `enroll cannot replace an existing or corrupt credential`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val store = fastStore(dataStore)
store.enroll("first password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
assertEquals(SupervisedParentAuthResult.Success, store.verify("first password".toCharArray()))
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "corrupt" }
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
}
@Test
fun `authenticated clear removes credential and disables policies without losing settings`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val authStore = fastStore(dataStore)
val policyStore = SupervisedModeStore.forTesting(dataStore)
authStore.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
policyStore.setPolicy(
"connection-a",
SupervisedModePolicy(
enabled = true,
pinnedProfileName = "willow",
capabilities = SupervisedCapabilities(attachments = false, voice = true),
),
)
policyStore.setPolicy(
"connection-b",
SupervisedModePolicy(
enabled = true,
pinnedProfileName = "coder",
visibility = SupervisedVisibility(showTimestamps = true),
),
)
val beforeA = policyStore.policyFlow("connection-a").first()
val beforeB = policyStore.policyFlow("connection-b").first()
authStore.clearCredentialAndDisablePolicies().getOrThrow()
assertEquals(SupervisedParentAuthStatus.Missing, authStore.statusFlow.first())
assertEquals(beforeA.copy(enabled = false), policyStore.policyFlow("connection-a").first())
assertEquals(beforeB.copy(enabled = false), policyStore.policyFlow("connection-b").first())
}
@Test
fun `failed attempts persist across store recreation and backoff expires by clock`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val clock = AtomicLong(1_000L)
var store = fastStore(dataStore, clock)
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
repeat(4) {
assertTrue(store.verify("wrong password".toCharArray()) is SupervisedParentAuthResult.Invalid)
}
val fifth = store.verify("wrong password".toCharArray())
assertEquals(SupervisedParentAuthResult.Throttled(30_000L), fifth)
store = fastStore(dataStore, clock)
assertEquals(
SupervisedParentAuthResult.Throttled(30_000L),
store.verify("parent password".toCharArray()),
)
clock.addAndGet(30_001L)
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
}
@Test
fun `concurrent store instances preserve the capped failure sequence`() = runTest {
val dataStore = InMemoryParentAuthDataStore()
val stores = List(5) { fastStore(dataStore) }
stores.first().enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val results = stores.map { store -> async { store.verify("wrong password".toCharArray()) } }.awaitAll()
assertEquals(4, results.count { it is SupervisedParentAuthResult.Invalid })
assertEquals(1, results.count { it == SupervisedParentAuthResult.Throttled(30_000L) })
}
@Test
fun `change requires the current credential and rotates recovery`() = runTest {
val store = fastStore(InMemoryParentAuthDataStore())
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
assertTrue(store.change("wrong".toCharArray(), "new password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
assertEquals(SupervisedParentAuthResult.Success, store.verify("old password".toCharArray()))
val replacement = store.change(
"old password".toCharArray(),
"654321".toCharArray(),
SupervisedParentCredentialType.Pin,
).getOrThrow()
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
assertTrue(store.verify("old password".toCharArray()) is SupervisedParentAuthResult.Invalid)
assertEquals(SupervisedParentAuthResult.Success, store.verify("654321".toCharArray()))
assertEquals(SupervisedParentCredentialType.Pin, store.credentialTypeFlow.first())
}
@Test
fun `recovery is normalized one time and rotates both secrets`() = runTest {
val store = fastStore(InMemoryParentAuthDataStore())
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
val lowerSpaced = original.recoveryPhrase.uppercase().replace("-", " ").toCharArray()
val replacement = store.resetWithRecoveryPhrase(
lowerSpaced,
"new password".toCharArray(),
SupervisedParentCredentialType.Password,
).getOrThrow()
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
assertEquals(SupervisedParentAuthResult.Success, store.verify("new password".toCharArray()))
assertTrue(
store.resetWithRecoveryPhrase(
original.recoveryPhrase.toCharArray(),
"another password".toCharArray(),
SupervisedParentCredentialType.Password,
)
.isFailure,
)
}
private fun fastStore(
dataStore: DataStore<Preferences>,
clock: AtomicLong = AtomicLong(1_000L),
): SupervisedParentAuthStore = SupervisedParentAuthStore.forTesting(
dataStore = dataStore,
iterations = 1,
minimumAcceptedIterations = 1,
nowMillis = clock::get,
)
}
private class InMemoryParentAuthDataStore : DataStore<Preferences> {
private val state = MutableStateFlow(emptyPreferences())
override val data: Flow<Preferences> = state
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
val updated = transform(state.value)
state.value = updated
return updated
}
}
@@ -1530,6 +1530,86 @@ class ChatHandlerTest {
assertTrue(handler.messages.value.single().attachments.isEmpty())
}
@Test
fun loadMessageHistory_preservesCompletedGeneratedImageUntilMarkerPersists() {
handler.addPlaceholderMessage(
ChatMessage(
id = "assistant-live-image",
role = MessageRole.ASSISTANT,
content = "Here is the generated image.",
timestamp = 1L,
attachments = listOf(
Attachment(
contentType = "image/png",
content = "",
fileName = "generated.png",
relayToken = "/tmp/generated.png",
state = AttachmentState.LOADED,
),
),
toolCalls = listOf(
ToolCall(
id = "image-call",
name = "willow_create_image",
args = null,
result = "success",
success = true,
isComplete = true,
),
),
),
)
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-server-image",
role = "assistant",
content = JsonPrimitive("Here is the generated image."),
),
),
)
val message = handler.messages.value.single()
assertEquals("assistant-server-image", message.id)
assertEquals("assistant-live-image", message.uiKey)
assertEquals(1, message.attachments.size)
assertEquals("generated.png", message.attachments.single().fileName)
}
@Test
fun loadMessageHistory_doesNotCarryUnownedAssistantInboundImage() {
handler.addPlaceholderMessage(
ChatMessage(
id = "assistant-live-generic",
role = MessageRole.ASSISTANT,
content = "A generic fetched image.",
timestamp = 1L,
attachments = listOf(
Attachment(
contentType = "image/png",
content = "",
fileName = "generic.png",
relayToken = "generic-token",
state = AttachmentState.LOADED,
),
),
),
)
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-server-generic",
role = "assistant",
content = JsonPrimitive("A generic fetched image."),
),
),
)
assertTrue(handler.messages.value.single().attachments.isEmpty())
}
@Test
fun loadMessageHistory_consumesOutboundAttachmentOncePerDuplicateContent() {
// Two identical-text sends, only the first with an attachment: the
@@ -562,17 +562,24 @@ class DashboardApiClientTest {
}
@Test
fun signInRequiredClassifierAcceptsNoCookieButRejectsForbidden() {
fun signInRequiredClassifierAcceptsEveryUnauthorizedShapeButRejectsForbidden() {
val noCookie = DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"no_cookie\",\"detail\":\"Unauthorized\"}",
)
val expired = DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"session_expired\",\"detail\":\"invalid_or_expired_session\"}",
)
val generic = DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized")
val forbidden = DashboardHttpException(
403,
"Session failed - HTTP 403: forbidden",
)
assertTrue(noCookie.isDashboardSignInRequiredFailure())
assertTrue(expired.isDashboardSignInRequiredFailure())
assertTrue(generic.isDashboardSignInRequiredFailure())
assertFalse(forbidden.isDashboardSignInRequiredFailure())
}
@@ -19,13 +19,17 @@ import org.robolectric.annotation.GraphicsMode
class ChangelogHistoryScreenshotTest {
@get:Rule val compose = createComposeRule()
@Test fun latestReleaseIsCuratedAndInstalled() {
@Test fun latestReleaseShowsHighlightsAndCompleteDetails() {
compose.setContent {
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
ChangelogScreen(onClose = {})
}
}
compose.onNodeWithText("Supervised Mode").assertExists()
compose.onNodeWithText("v1.14.0 — Connections, delegated work, Git, and voice").assertExists()
compose.onNodeWithText("Highlights").assertExists()
compose.onNodeWithText("Fixed").assertExists()
compose.onNodeWithText("Wake-word detection starts reliably").assertExists()
compose.onNodeWithText("Compatibility").assertExists()
compose.onNodeWithText("Installed").assertExists()
compose.onRoot().captureRoboImage("build/ui-regression/changelog-history.png")
}
@@ -0,0 +1,75 @@
package com.hermesandroid.relay.screenshots
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.takahirom.roborazzi.captureRoboImage
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.ui.screens.CredentialChoiceScreen
import com.hermesandroid.relay.ui.screens.ParentAuthScreenSurface
import com.hermesandroid.relay.ui.screens.PasswordSetupScreen
import com.hermesandroid.relay.ui.screens.PinSetupScreen
import com.hermesandroid.relay.ui.screens.SupervisedParentRecoveryCodeContent
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(qualifiers = "w400dp-h900dp-432dpi")
class SupervisedParentAuthFlowScreenshotTest {
@get:Rule
val compose = createComposeRule()
@Test
fun credentialChoice() {
render("build/visual-qa/supervised-parent-choice.png", 1 to 2) {
CredentialChoiceScreen(
title = "Choose parent access",
subtitle = "Pick one way to unlock parent settings. You can change it later.",
onSelected = {},
)
}
}
@Test
fun pinSetup() {
render("build/visual-qa/supervised-parent-pin.png", 2 to 2) {
PinSetupScreen(busy = false, error = null, onComplete = {})
}
}
@Test
fun passwordSetup() {
render("build/visual-qa/supervised-parent-password.png", 2 to 2) {
PasswordSetupScreen(busy = false, error = null, onComplete = {})
}
}
@Test
fun recoveryPhrase() {
render("build/visual-qa/supervised-parent-recovery.png", 3 to 3) {
SupervisedParentRecoveryCodeContent(
enrollment = SupervisedParentEnrollment(
"maple-river-lantern-copper-sparrow-moon",
),
)
}
}
private fun render(
path: String,
step: Pair<Int, Int>,
content: @androidx.compose.runtime.Composable () -> Unit,
) {
compose.setContent {
HermesRelayTheme(themePreference = "dark") {
ParentAuthScreenSurface(step = step, onBack = {}, content = content)
}
}
compose.onRoot().captureRoboImage(path)
}
}
@@ -61,9 +61,11 @@ class WhatsNewToastScreenshotTest {
}
}
}
compose.onNodeWithText("Supervised Mode").assertExists()
compose.onNodeWithText("Also: 2 fixes").assertExists()
compose.onNodeWithText("Accurate activity, safer return…").assertExists()
compose.onNodeWithText("Connections, delegated work, Git, and voice").assertExists()
compose.onNodeWithText("Also: 2 improvements · 10 fixes").assertExists()
compose.onNodeWithText(
"Release notes stay out of your way, Chat uses one consistent presentation…",
).assertExists()
compose.onNodeWithText("View all").assertExists()
compose.onNodeWithContentDescription("Close").assertExists()
compose.onRoot().captureRoboImage("build/ui-regression/whats-new-toast-large-text.png")
@@ -84,7 +86,7 @@ class WhatsNewToastScreenshotTest {
}
}
compose.onNodeWithText("Supervised Mode").performClick()
compose.onNodeWithText("Connections, delegated work, Git, and voice").performClick()
expanded = false
compose.onNodeWithText("View all").performClick()
compose.onNodeWithContentDescription("Close").performClick()
@@ -106,7 +108,8 @@ class WhatsNewToastScreenshotTest {
}
}
compose.mainClock.advanceTimeBy(300L)
compose.onNodeWithText("Supervised Mode").performTouchInput { swipeLeft(durationMillis = 300L) }
compose.onNodeWithText("Connections, delegated work, Git, and voice")
.performTouchInput { swipeLeft(durationMillis = 300L) }
compose.mainClock.advanceTimeBy(300L)
assertTrue(dismissed)
@@ -40,32 +40,50 @@ class SupervisedNavigationPolicyTest {
@Test fun `parent access or ordinary mode permits add gateway`() {
assertTrue(mayStartAddConnection(supervisedEnabled = true, parentAccessUnlocked = true))
assertTrue(mayStartAddConnection(supervisedEnabled = false, parentAccessUnlocked = false))
assertFalse(
mayStartAddConnection(
supervisedEnabled = false,
parentAccessUnlocked = true,
activeTargetId = "already-started",
),
)
}
@Test fun `locked add gateway action has no side effects`() {
var navigated = false
var prepared = false
val started = runAddConnectionAction(
@Test fun `locked add gateway action performs no allocation or side effects`() {
val actions = mutableListOf<String>()
val target = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = false,
navigateToPair = { navigated = true },
prepareConnection = { prepared = true },
)
assertFalse(started)
assertFalse(navigated)
assertFalse(prepared)
}
@Test fun `allowed add gateway action navigates before preparation`() {
val actions = mutableListOf<String>()
val started = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = true,
activeTargetId = null,
allocateTarget = { actions += "allocate"; "target" },
recordTarget = { actions += "record" },
navigateToPair = { actions += "navigate" },
prepareConnection = { actions += "prepare" },
)
assertTrue(started)
assertTrue(actions == listOf("navigate", "prepare"))
assertTrue(target == null)
assertTrue(actions.isEmpty())
}
@Test fun `allowed add gateway action records target before navigation and preparation`() {
val actions = mutableListOf<String>()
val target = runAddConnectionAction(
supervisedEnabled = true,
parentAccessUnlocked = true,
activeTargetId = null,
allocateTarget = { actions += "allocate"; "target" },
recordTarget = { actions += "record:$it" },
navigateToPair = { actions += "navigate:$it" },
prepareConnection = { actions += "prepare:$it" },
)
assertTrue(target == "target")
assertTrue(
actions == listOf(
"allocate",
"record:target",
"navigate:target",
"prepare:target",
),
)
}
@Test fun `supervised redirect waits until the navigation graph has a route`() {
@@ -75,6 +93,7 @@ class SupervisedNavigationPolicyTest {
assertTrue(isSupervisedRouteContentAllowed(true, false, Screen.Chat.route))
assertTrue(shouldRedirectSupervisedRoute(true, false, Screen.AdvancedSettings.route))
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.AdvancedSettings.route))
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.ConnectionsSettings.route))
assertFalse(shouldRedirectSupervisedRoute(true, true, Screen.AdvancedSettings.route))
assertTrue(isSupervisedRouteContentAllowed(true, true, Screen.AdvancedSettings.route))
}
@@ -153,25 +172,23 @@ class SupervisedNavigationPolicyTest {
)
}
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
@Test fun `first enable requires configured policy and successful app parent credential`() {
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
assertFalse(
mayEnableSupervisedMode(
configured,
deviceSecure = false,
deviceCredentialConfirmed = true,
parentCredentialConfirmed = false,
),
)
assertFalse(
mayEnableSupervisedMode(
configured,
deviceSecure = true,
deviceCredentialConfirmed = false,
parentCredentialConfirmed = false,
),
)
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
assertTrue(mayEnableSupervisedMode(configured, true, true))
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true))
assertTrue(mayEnableSupervisedMode(configured, true))
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true))
}
}
@@ -37,26 +37,25 @@ class ChangelogParserTest {
}
@Test
fun parsesCuratedHighlightAndImprovements() {
fun parsesCompleteReleaseAndDerivesToastDigest() {
val raw = """
{
"schema": 2,
"schema": 3,
"versions": [
{
"version": "1.2.0",
"title": "A useful release",
"date": "2026-06-20",
"highlight": {
"title": "The main reason to care",
"summary": "A plain-language explanation.",
"bullets": ["a", "b", "c"]
},
"improvements": ["d", "e"],
"toastDigest": {
"additionalFeatureCount": 1,
"fixCount": 2,
"preview": ["Secondary feature", "Important fix"]
},
"summary": "A plain-language explanation.",
"changes": [
{"id": "new-one", "kind": "added", "title": "New one",
"summary": "Use the new thing.", "highlight": true},
{"id": "better-one", "kind": "improved", "title": "Better one",
"summary": "The old thing is easier."},
{"id": "fixed-one", "kind": "fixed", "title": "Fixed one",
"summary": "The broken thing works."}
],
"compatibility": ["Existing connections keep working."],
"playNotes": "Concise Play copy."
}
]
@@ -64,17 +63,41 @@ class ChangelogParserTest {
""".trimIndent()
val entry = ChangelogStore.parse(raw).versions.single()
val digest = entry.resolvedToastDigest()
assertEquals("The main reason to care", entry.highlight?.title)
assertEquals("A plain-language explanation.", entry.highlight?.summary)
assertEquals(listOf("a", "b", "c"), entry.highlight?.bullets)
assertEquals(listOf("d", "e"), entry.improvements)
assertEquals(1, entry.toastDigest?.additionalFeatureCount)
assertEquals(2, entry.toastDigest?.fixCount)
assertEquals(listOf("Secondary feature", "Important fix"), entry.toastDigest?.preview)
assertEquals("A plain-language explanation.", entry.summary)
assertEquals(listOf("New one"), entry.highlightedChanges().map { it.title })
assertEquals(0, digest?.additionalFeatureCount)
assertEquals(1, digest?.improvementCount)
assertEquals(1, digest?.fixCount)
assertEquals(listOf("Better one", "Fixed one"), digest?.preview)
assertEquals(listOf("Existing connections keep working."), entry.compatibility)
assertEquals("Concise Play copy.", entry.playNotes)
assertEquals("v1.2.0 · 2026-06-20", entry.versionLine())
assertEquals(listOf("The main reason to care", "Also improved"), entry.toGroups().map { it.header })
assertEquals(
listOf("Highlights", "Improved", "Fixed", "Compatibility"),
entry.toGroups().map { it.header },
)
assertEquals(3, entry.toGroups().sumOf { it.bullets.size } - entry.compatibility.size)
}
@Test
fun completeReleaseRendersEveryChangeOnce() {
val entry = ChangelogVersion(
version = "1.2.0",
title = "Complete notes",
summary = "Everything users need to know.",
changes = listOf(
ChangelogChange("a", CHANGE_KIND_ADDED, "First", "First detail", highlight = true),
ChangelogChange("b", CHANGE_KIND_FIXED, "Second", "Second detail"),
),
)
val rendered = entry.toGroups().flatMap { it.bullets }
assertEquals(2, rendered.size)
assertEquals(1, rendered.count { it.startsWith("First") })
assertEquals(1, rendered.count { it.startsWith("Second") })
}
@Test
@@ -26,6 +26,7 @@ class ImageGenerationPlaceholderTest {
)
assertTrue(active.showsImageGenerationPlaceholder())
assertTrue(active.copy(name = "willow_create_image").showsImageGenerationPlaceholder())
assertFalse(active.copy(isComplete = true, success = true).showsImageGenerationPlaceholder())
assertFalse(active.copy(name = "video_generate").showsImageGenerationPlaceholder())
}
@@ -28,6 +28,7 @@ class ToolActivityRunTest {
val standalone = listOf(
call("risk", "read_file").copy(outputRisk = "high"),
call("image", "image_generate"),
call("profile-image", "willow_create_image"),
call("approval", "request_user_input"),
call("delegate", "delegate_task"),
)
@@ -0,0 +1,233 @@
package com.hermesandroid.relay.ui.screens
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.BotGatewayRoute
import com.hermesandroid.relay.data.BotGatewayRouteKey
import com.hermesandroid.relay.data.BotRosterEntry
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.viewmodel.ChatViewModel
import java.util.concurrent.CopyOnWriteArrayList
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.serialization.json.JsonPrimitive
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(sdk = [35], qualifiers = "w390dp-h844dp-432dpi")
class BotChatScreenBindingTest {
@get:Rule
val compose = createComposeRule()
private val resources = CopyOnWriteArrayList<ScreenResources>()
@After
fun tearDown() {
resources.forEach(ScreenResources::close)
}
@Test
fun fastHistoryPublishedDuringInitialBindRendersWithoutNavigation() {
val screen = resources("research")
val handler = ChatHandler()
compose.mainClock.autoAdvance = false
compose.setContent {
MaterialTheme {
screen.content(
handler = handler,
historyLoader = { _, _, _ ->
Result.success(history(screen.sessionId, FAST_HISTORY))
},
)
}
}
compose.mainClock.advanceTimeByFrame()
compose.waitUntil(5_000) { handler.messages.value.singleOrNull()?.content == FAST_HISTORY }
compose.mainClock.autoAdvance = true
compose.waitForIdle()
compose.onNodeWithText(FAST_HISTORY).assertIsDisplayed()
compose.runOnIdle { handler.onTextDelta("live-tail", LIVE_TAIL) }
compose.onNodeWithText(LIVE_TAIL).assertIsDisplayed()
compose.runOnIdle { handler.onStreamError(HANDLER_ERROR) }
compose.onNodeWithText(HANDLER_ERROR).assertIsDisplayed()
}
@Test
fun delayedHistoryAfterCompositionRendersFromTheSameHandler() {
val screen = resources("builder")
val handler = ChatHandler()
val releaseHistory = CompletableDeferred<Unit>()
compose.setContent {
MaterialTheme {
screen.content(
handler = handler,
historyLoader = { _, _, _ ->
releaseHistory.await()
Result.success(history(screen.sessionId, DELAYED_HISTORY))
},
)
}
}
compose.waitUntil(5_000) { screen.viewModel.isLoadingHistory.value }
compose.onNodeWithText(DELAYED_HISTORY).assertDoesNotExist()
releaseHistory.complete(Unit)
compose.waitUntil(5_000) { handler.messages.value.isNotEmpty() }
compose.onNodeWithText(DELAYED_HISTORY).assertIsDisplayed()
}
@Test
fun replacementHandlerRejectsLateHistoryAndOldHandlerPublications() {
val screen = resources("operator")
val firstHandler = ChatHandler()
val secondHandler = ChatHandler()
val releaseFirstHistory = CompletableDeferred<Unit>()
val target = mutableStateOf(
Target(
revision = 0,
handler = firstHandler,
loader = { _, _, _ ->
releaseFirstHistory.await()
Result.success(history(screen.sessionId, OLD_HISTORY))
},
),
)
compose.setContent {
val current = target.value
key(current.revision) {
MaterialTheme {
screen.content(current.handler, current.loader)
}
}
}
compose.waitUntil(5_000) { screen.viewModel.isLoadingHistory.value }
compose.runOnIdle {
target.value = Target(
revision = 1,
handler = secondHandler,
loader = { _, _, _ -> Result.success(history(screen.sessionId, NEW_HISTORY)) },
)
}
compose.waitForIdle()
compose.runOnIdle { assertSame(secondHandler, screen.viewModel.boundHandler) }
compose.waitUntil(5_000) { secondHandler.messages.value.singleOrNull()?.content == NEW_HISTORY }
compose.onNodeWithText(NEW_HISTORY).assertIsDisplayed()
releaseFirstHistory.complete(Unit)
compose.waitForIdle()
assertEquals(emptyList<String>(), firstHandler.messages.value.map { it.content })
compose.runOnIdle { firstHandler.onTextDelta("old-tail", OLD_TAIL) }
compose.waitForIdle()
compose.onNodeWithText(OLD_HISTORY).assertDoesNotExist()
compose.onNodeWithText(OLD_TAIL).assertDoesNotExist()
assertEquals(listOf(OLD_TAIL), firstHandler.messages.value.map { it.content })
assertEquals(listOf(NEW_HISTORY), secondHandler.messages.value.map { it.content })
}
private fun resources(profileName: String): ScreenResources = ScreenResources(profileName).also {
resources += it
}
private fun history(sessionId: String, text: String) = listOf(
MessageItem(
id = "history-$sessionId",
sessionId = sessionId,
role = "assistant",
content = JsonPrimitive(text),
timestamp = 1.0,
finishReason = "stop",
),
)
private inner class ScreenResources(profileName: String) {
val route = BotGatewayRoute(
key = BotGatewayRouteKey("gateway-$profileName", profileName),
connectionLabel = "Fixture gateway",
)
val bot = BotRosterEntry(
profile = Profile(
name = profileName,
model = "fixture-model",
description = "Fixture profile",
),
displayName = profileName.replaceFirstChar(Char::uppercase),
route = route,
)
val sessionId = "fixture-$profileName-session"
val viewModel = ChatViewModel()
private val gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val dashboardClient = DashboardApiClient("http://127.0.0.1:1")
private val gatewayClient = GatewayChatClient(
initialDashboardClient = dashboardClient,
fixedSessionProfile = profileName,
scope = gatewayScope,
reconnectJitterUnit = { 0.0 },
)
@androidx.compose.runtime.Composable
fun content(handler: ChatHandler, historyLoader: BotChatHistoryLoader) {
BotChatScreen(
route = route,
bot = bot,
sessionId = sessionId,
gatewayClient = gatewayClient,
dashboardClient = dashboardClient,
chatViewModel = viewModel,
onBack = {},
handlerFactory = { handler },
historyLoader = historyLoader,
profileIconFlow = { _, _ -> MutableStateFlow(null) },
)
}
fun close() {
viewModel.updateGatewayClient(null)
gatewayClient.shutdown()
gatewayScope.cancel()
dashboardClient.shutdown()
}
}
private data class Target(
val revision: Int,
val handler: ChatHandler,
val loader: BotChatHistoryLoader,
)
private companion object {
const val FAST_HISTORY = "History loaded before the next frame."
const val DELAYED_HISTORY = "History loaded after composition."
const val LIVE_TAIL = "Live tail from the owned handler."
const val HANDLER_ERROR = "Owned handler error"
const val OLD_HISTORY = "Late history from the old route."
const val OLD_TAIL = "Old handler live tail."
const val NEW_HISTORY = "History from the replacement route."
}
}
@@ -0,0 +1,94 @@
package com.hermesandroid.relay.ui.screens
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.SupervisedParentCredentialType
import com.hermesandroid.relay.data.SupervisedParentEnrollment
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(qualifiers = "w400dp-h900dp-432dpi")
class SupervisedParentAuthDialogsTest {
@get:Rule
val compose = createComposeRule()
@Test
fun `choice presents mutually exclusive pin and password routes`() {
var selected: SupervisedParentCredentialType? = null
compose.setContent {
HermesRelayTheme {
CredentialChoiceScreen("Choose parent access", "Pick one.") { selected = it }
}
}
compose.onNodeWithText("Use a PIN").assertIsDisplayed().performClick()
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Pin, selected) }
compose.onNodeWithText("Use a password").assertIsDisplayed().performClick()
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Password, selected) }
}
@Test
fun `pin auth uses six positions and a dedicated numeric keypad`() {
var submitted: String? = null
compose.setContent {
HermesRelayTheme {
PinEntryScreen("Parent PIN", "Enter your 6-digit PIN.", false, null, { submitted = it })
}
}
(0..9).forEach { compose.onNodeWithText(it.toString()).assertIsDisplayed() }
compose.onNodeWithContentDescription("Delete digit").assertIsDisplayed()
(1..6).forEach { compose.onNodeWithText(it.toString()).performClick() }
compose.runOnIdle { assertEquals("123456", submitted) }
}
@Test
fun `password setup uses distinct password fields and visibility controls`() {
compose.setContent {
HermesRelayTheme { PasswordSetupScreen(false, null, {}) }
}
compose.onNodeWithText("Create a parent password").assertIsDisplayed()
compose.onNodeWithText("Password").assertIsDisplayed()
compose.onNodeWithText("Confirm password").assertIsDisplayed()
compose.onAllNodesWithContentDescription("Show password").assertCountEquals(2)
}
@Test
fun `recovery phrase handoff exposes sharing copy and cleanup guidance`() {
var shares = 0
var copies = 0
compose.setContent {
HermesRelayTheme {
SupervisedParentRecoveryCodeContent(
SupervisedParentEnrollment("maple-river-lantern-copper-sparrow-moon"),
onShare = { shares += 1 },
onCopy = { copies += 1 },
)
}
}
compose.onNodeWithText("maple-river-lantern", substring = true).assertIsDisplayed()
compose.onNodeWithText("copper-sparrow-moon", substring = true).assertIsDisplayed()
compose.onNodeWithText("Share").assertIsDisplayed()
compose.onNodeWithText("Copy phrase").assertIsDisplayed()
compose.onNodeWithText("delete the message or saved copy", substring = true).assertIsDisplayed()
compose.onNodeWithText("Share").performClick()
compose.onNodeWithText("Copy phrase").performClick()
compose.runOnIdle {
assertEquals(1, shares)
assertEquals(1, copies)
}
}
}
@@ -238,6 +238,63 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals("gateway", diagnostic.endpointRole)
}
@Test
fun normalCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
DiagnosticsLog.clear()
apiMessageRequestCount.set(0)
val owner = Profile(name = "owner", model = "model-a", description = "Owner")
val requestedProfiles = mutableListOf<String?>()
val sessionRefreshes = AtomicInteger(0)
val signInRequests = AtomicInteger(0)
viewModel.setSelectedProfileProvider { owner }
viewModel.setSessionProfileNameProvider { owner.name }
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
requestedProfiles += profileName
assertEquals(STORED_SESSION_ID, sessionId)
Result.failure(
DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized"),
)
}
viewModel.setProfileSessionLister { profileName ->
assertEquals(owner.name, profileName)
sessionRefreshes.incrementAndGet()
Result.success(emptyList())
}
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
viewModel.sendMessage("Keep this local prompt")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"message.delta",
buildJsonObject { put("text", "Keep this local answer") },
"live-resumed",
),
)
serverWs.send(
gatewayHarness.eventFrame(
"message.complete",
buildJsonObject { put("text", "Keep this local answer") },
"live-resumed",
),
)
awaitCondition {
!handler.isStreaming.value &&
signInRequests.get() == 1 &&
sessionRefreshes.get() >= 1
}
assertTrue(handler.messages.value.any { it.content == "Keep this local prompt" })
assertTrue(handler.messages.value.any { it.content == "Keep this local answer" })
assertEquals(listOf(owner.name), requestedProfiles)
assertEquals(0, apiMessageRequestCount.get())
assertFalse(viewModel.steerableTurn.value)
assertNull(viewModel.chatFailure.value)
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
assertTrue(diagnostic.suggestion.orEmpty().contains("Sign in to Dashboard"))
}
@Test
fun missingRequiredProfileHistoryLoaderFailsClosedWithoutApiRead() {
DiagnosticsLog.clear()
@@ -2746,6 +2803,92 @@ class ChatViewModelGatewayInboundTurnTest {
)
}
@Test
fun recoveredCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
DiagnosticsLog.clear()
apiMessageRequestCount.set(0)
val checkpointStore = MemoryCheckpointStore(
ChatTurnCheckpoint(
contextKey = PROFILE_CONTEXT,
sessionId = STORED_SESSION_ID,
liveSessionId = "live-resumed",
transport = "gateway",
user = ChatTurnUserCheckpoint("prior-user", "Recovered prompt", 1L),
assistant = ChatTurnAssistantCheckpoint(
id = "prior-assistant",
content = "Recovered partial",
timestamp = 2L,
),
priorUserMessageCount = 0,
baselineAssistantCount = 0,
startedAt = 2L,
updatedAt = System.currentTimeMillis(),
),
)
val requestedProfiles = mutableListOf<String?>()
val sessionRefreshes = AtomicInteger(0)
val signInRequests = AtomicInteger(0)
var failHistory = false
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
requestedProfiles += profileName
assertEquals(STORED_SESSION_ID, sessionId)
if (failHistory) {
Result.failure(
DashboardHttpException(
401,
"Session failed - HTTP 401: {\"reason\":\"session_expired\"}",
),
)
} else {
Result.success(emptyList())
}
}
viewModel.setProfileSessionLister { profileName ->
assertNull(profileName)
sessionRefreshes.incrementAndGet()
Result.success(emptyList())
}
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
gatewayHarness.recoveryRunning = true
gatewayHarness.recoveryAssistant = "Recovered partial"
viewModel.setChatTurnCheckpointStore(checkpointStore)
handler.setSessionId(null)
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
viewModel.prewarmGateway()
gatewayHarness.awaitRpc("session.activate")
awaitCondition {
handler.messages.value.any { it.id == "prior-assistant" && it.isStreaming }
}
failHistory = true
serverWs.send(
gatewayHarness.eventFrame(
"message.complete",
buildJsonObject { put("text", "Recovered answer") },
"live-resumed",
),
)
awaitCondition {
!handler.isStreaming.value &&
signInRequests.get() == 1 &&
sessionRefreshes.get() >= 1
}
assertTrue(handler.messages.value.any {
it.id == "prior-assistant" &&
it.content.contains("Recovered answer") &&
!it.isStreaming
})
assertTrue(requestedProfiles.isNotEmpty())
assertTrue(requestedProfiles.all { it == null })
assertEquals(0, apiMessageRequestCount.get())
assertFalse(viewModel.steerableTurn.value)
awaitCondition { checkpointStore.checkpoint == null }
assertNull(viewModel.chatFailure.value)
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
}
@Test
fun lateCanceledCompletionDrainsBeforeImmediateNextTurn() {
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
+148
View File
@@ -0,0 +1,148 @@
# Android build execution
Hermes-Relay prefers isolated GitHub-hosted runners for heavy Android
verification after an exact commit is pushed. Windows retains one machine-wide
local Android build lane for narrow feedback, explicit full-local verification,
device work, and cloud outages. Every local worktree shares the same named
operating-system mutex through
`scripts/android-lane.ps1`. When commands use the wrapper, Gradle, Kotlin
compilation, lint, tests, assemblies, connected tests, and APK installation do
not compete for the same host resources and shared caches.
## Cloud-preferred verification
`Android On-Demand` accepts a full 40-character pushed commit SHA and one of
five presets:
| Preset | Work |
|---|---|
| `focused` | Repository checks plus focused sideload and Google Play unit tests |
| `lint` | Repository checks plus full Android lint |
| `assemble-debug` | Both debug flavors, native compatibility scan, APK artifacts |
| `release-smoke` | Both release flavors, DEX/native scans, APK/AAB artifacts |
| `all-final` | All four compute jobs concurrently on isolated runners |
Check recent runs before dispatching so another task does not duplicate the
same SHA and preset:
```powershell
$base = git merge-base origin/dev HEAD
$sha = git rev-parse HEAD
gh run list --workflow ci-required.yml --event workflow_dispatch --limit 20
gh workflow run ci-required.yml --ref dev `
-f base_sha=$base `
-f head_sha=$sha `
-f android_preset=focused
gh run list --workflow ci-required.yml --event workflow_dispatch --limit 5
```
The SHA must already exist on GitHub. Do not push solely to obtain cloud compute
without push authorization. On-demand jobs read shared Gradle cache state but
do not write it, so task commits cannot replace the cache populated by trusted
`dev`/`main` CI. The on-demand result supplements rather than replaces required
PR checks. `Required checks` is the registered dispatcher because GitHub only
registers manual workflow entry points from the default branch; it calls the
Android workflow from the selected `dev` ref.
## Local use
The Windows `scripts/dev.bat` commands and `scripts/android-prepush.py` acquire
the lane automatically. For an ad hoc Gradle command, use:
```powershell
.\scripts\android-lane.ps1 gradle `
:app:testSideloadDebugUnitTest `
--tests "*ChatViewModelTest*" `
--console=plain
```
The wrapper waits until the current owner exits and releases the mutex. Windows
also releases the mutex if its owner crashes; the next waiter reports that it
recovered an abandoned lane. Use Ctrl+C to cancel a waiter without stopping the
owner. A bounded wait is available when a caller has its own deadline:
```powershell
.\scripts\android-lane.ps1 --timeout-seconds 900 gradle :app:lintSideloadDebug
```
Check the lane without starting work:
```powershell
.\scripts\android-lane.ps1 status
```
`status` exits 0 when idle and 1 when busy. It intentionally does not expose the
owning process's arguments because Gradle properties can contain credentials.
Use `exec` for a connected/device workflow that must exclude every
wrapper-managed Gradle lane, including explicit APK installation:
```powershell
.\scripts\android-lane.ps1 exec python scripts/android-gateway-certify.py <arguments>
.\scripts\android-lane.ps1 exec adb -t <transport-id> install -r <apk>
```
Raw `gradlew`, Android Studio sync/build/run, and raw `adb install` do not pass
through the mutex. Before using one of those paths, check that the lane is idle
and keep all queued wrappers idle until it finishes. During final integration,
close or pause Android Studio's automatic Gradle activity and let one
coordinator own the sequence.
## Final coordinator gate
For an exact candidate commit that is already pushed, the coordinator normally
dispatches `all-final`. Focused tests, lint, debug assemblies, and release smoke
may run concurrently because each owns an isolated GitHub-hosted runner. After
all selected cloud jobs and required PR checks pass against that exact SHA, the
coordinator runs any required connected/instrumentation or physical-device
checks locally, then performs the explicit APK install.
Full local verification remains available when explicitly wanted or when cloud
execution is unavailable. In that mode, keep the following sequence serial on
the machine-wide lane:
```powershell
scripts\dev.bat prepush
```
That command runs repository checks, full Android lint, and both focused flavor
shards in one local Gradle invocation. The full local sequence remains:
1. Focused sideload unit tests.
2. Focused Google Play unit and policy tests.
3. Android lint.
4. Sideload and Google Play assemblies (or the release-equivalent both-flavor gate).
5. Connected/instrumentation and physical-device checks when the change needs them.
6. The explicit APK install only after every preceding gate passes.
Do not run these heavy gates in parallel on one local host. A timeout from an
outer agent or terminal is not evidence that Gradle failed; use the wrapper's
process exit and Gradle output as the result. Cloud concurrency is safe because
the jobs do not share a daemon, Gradle user home, project cache, or device.
## Resource policy
The normal serialized path retains the repository defaults:
- the shared Gradle user home, wrapper distributions, dependency cache, build
cache, configuration cache, and compatible warm daemon;
- `org.gradle.jvmargs=-Xmx4g`, `org.gradle.daemon=true`,
`org.gradle.caching=true`, `org.gradle.configuration-cache=true`, and
`org.gradle.parallel=true`;
- Gradle's normal worker selection inside the one active invocation.
`--max-workers` limits workers only inside one Gradle invocation. It does not
prevent another worktree, Android Studio, or an APK-install lane from running.
Likewise, `--no-daemon` can still start a single-use daemon to honor the required
JVM settings; it is not a cross-process isolation mechanism.
Use a worktree-specific `GRADLE_USER_HOME`, `--no-build-cache`,
`--max-workers=1`, or `-Pkotlin.compiler.execution.strategy=in-process` only to
recover from a confirmed daemon/cache failure or for an explicitly isolated
exception. Those modes discard normal cache and warm-daemon benefits, can use
more disk and memory, and must still acquire the Android lane.
If recovery is required, first preserve the failing output and verify that no
other owner is active. Do not kill unrelated Java, Gradle, Kotlin, Android
Studio, or ADB processes merely to clear the lane; an OS-abandoned mutex is
recoverable automatically.
+135
View File
@@ -0,0 +1,135 @@
# Android emulator testing
Hermes-Relay Android uses individually selected Gradle Managed Devices for
repeatable, on-demand instrumentation. The routine virtual baseline is API 36.
There is deliberately no aggregate matrix task and no scheduled emulator job:
choose the smallest lane that can prove the behavior under review.
## Lanes
| Evidence lane | Gradle device | Hardware profile | Use it for |
|---|---|---|---|
| Real Device | None | Explicitly selected physical hardware | Firmware, radio, audio, camera, biometrics, background limits, accessibility, and release-candidate claims |
| Compact Phone | `compactPhoneApi36` | Pixel 2 | Narrow phone layouts, compact height, keyboard pressure |
| Standard Phone | `standardPhoneApi36` | Pixel 6 | Default functional and regression instrumentation |
| Large Phone | `largePhoneApi36` | Pixel 7 Pro | Large handset layout and reachability |
| Foldable | `foldableApi36` | Pixel Fold | Fold/unfold, posture, continuity, and width-class changes |
| Tablet | `tabletApi36` | Pixel Tablet | Expanded layout, panes, and large-window behavior |
| Future platform / native canary | `futureApi37Ps16k` | Pixel 7 Pro, API 37, forced 16 KB pages | On-demand platform and native-library compatibility only |
Routine API 36 lanes use the AOSP x86_64 image so deterministic app tests do not
spend host capacity on unrelated Google-service startup. The API 37/16 KB device
is not a screen-size lane and is not part of routine testing. Gradle Managed
Devices may download a missing image on first use; that setup can be large and
slow.
## Commands
List the registered tasks:
```powershell
.\scripts\android-lane.ps1 gradle :app:tasks --all |
Select-String 'Api36|Ps16k'
```
Compile the app and instrumentation APK without starting an emulator:
```powershell
.\scripts\android-lane.ps1 gradle `
:app:assembleSideloadDebug `
:app:assembleSideloadDebugAndroidTest
```
Run one complete lane, normally Standard Phone first:
```powershell
.\scripts\android-lane.ps1 gradle `
:app:standardPhoneApi36SideloadDebugAndroidTest
```
Run one test class on one lane:
```powershell
.\scripts\android-lane.ps1 gradle `
:app:standardPhoneApi36SideloadDebugAndroidTest `
'-Pandroid.testInstrumentationRunnerArguments.class=com.hermesandroid.relay.viewmodel.GatewayForegroundRecoveryInstrumentedTest'
```
Run the other virtual lanes only when their form factor is relevant:
```powershell
.\scripts\android-lane.ps1 gradle :app:compactPhoneApi36SideloadDebugAndroidTest
.\scripts\android-lane.ps1 gradle :app:largePhoneApi36SideloadDebugAndroidTest
.\scripts\android-lane.ps1 gradle :app:foldableApi36SideloadDebugAndroidTest
.\scripts\android-lane.ps1 gradle :app:tabletApi36SideloadDebugAndroidTest
```
Run the future-platform/native canary explicitly:
```powershell
.\scripts\android-lane.ps1 gradle `
:app:futureApi37Ps16kSideloadDebugAndroidTest
```
All Windows commands use the repository's machine-wide build lane; see
[`docs/android-build-lane.md`](android-build-lane.md). Check the lane without
starting work with:
```powershell
.\scripts\android-lane.ps1 status
```
Do not invoke every device task as one command. Run lanes serially, record each
result, and stop when the relevant evidence is complete or the host reaches a
capacity limit.
## Configuration coverage
Form factor is only one axis. Select additional states according to the change:
- Test dark mode first; also cover light mode when colors, contrast, system bars,
or theme persistence changed.
- Cover portrait and landscape when layout, keyboard, media, drawers, or panes
changed. Foldable work must include a posture or width-class transition.
- Check default font scale and at least one enlarged scale for text-heavy or
accessibility-sensitive UI.
- Use the default locale for functional regressions; add a long-string locale
and an RTL locale when copy, formatting, or layout direction changed.
- Record gesture versus three-button navigation when bottom insets, edge-to-edge,
back handling, sheets, or overlays changed.
These dimensions are selected test conditions, not permanent duplicated device
definitions. Record any non-default setting in the evidence.
## Deterministic fixtures and live servers
Embedded MockWebServer tests own deterministic transport regressions. They use
production clients and view models against loopback HTTP/WebSocket boundaries,
require no credentials, mutate no real sessions, and are the correct lane for
authentication loss, reconnect gaps, malformed frames, profile isolation, and
repeatable lifecycle assertions.
Live-server testing is separate and on demand. Use a disposable test or staging
Hermes server with disposable profiles and sessions. Normally run only the
Standard Phone emulator plus one explicitly selected real device when physical
evidence is required. Never multiply live mutation testing across the full size
matrix, use a production server, or use personal conversation data. Sanitize
logs and exports before attaching them to a pull request.
## Evidence
For each executed lane, record:
```text
Commit: <exact SHA>
Artifact/variant: sideloadDebug app + androidTest
Lane: Standard Phone (standardPhoneApi36), API 36
Test selection: <class or package>
Configuration: dark/light, orientation/posture, font scale, locale, navigation
Result: pass/fail/blocked, test count, report path
Notes: retries, emulator/image limitation, relevant sanitized observation
```
Keep claims lane-specific. Emulator proof is not physical-device proof. A
passing API 37/16 KB canary proves only that selected platform/native lane; it
does not replace API 36 form-factor coverage or physical firmware evidence.
+57 -5
View File
@@ -3772,7 +3772,7 @@ be considered later without being silently introduced now.
## ADR 66 — Android Supervised Mode is a parent-controlled client policy
**Status:** Implemented in code; physical managed-device certification pending (2026-08-24).
**Status:** Implemented in code; app-specific parent credential and physical managed-device certification pending (2026-08-31).
**Context.** Some operators prepare a deliberately restricted Hermes profile
for use through a parent-supervised Android client. The profile remains the
@@ -3784,9 +3784,10 @@ child security or as a server-enforced account type.
**Decision.** Android will treat Supervised Mode as an opt-in, locally enforced
policy pinned to one existing Connection and one existing Hermes profile. The
parent is responsible for preparing and reviewing that profile before enabling
the mode. Entering, changing, or leaving the parent policy requires Android
device authentication. That prompt authenticates an enrolled device user, not
a distinct server-side parent identity. While the policy is active, the app restores directly
the mode. Entering, changing, or leaving the parent policy requires the
app-global parent PIN or password. Android's screen lock, device credential,
and enrolled biometrics are not parent authority because the supervised user
may legitimately control them. While the policy is active, the app restores directly
into a restricted root and never renders the ordinary app behind an
authentication prompt. A missing Connection, missing profile, malformed policy,
failed authentication, process restart, or restored route that cannot prove its
@@ -3800,6 +3801,37 @@ recreation, and leaving parent settings relock parent access according to the
policy. Deep links, notification actions, restored navigation, shortcuts, and
programmatic routes pass the same gate.
The parent credential store persists only salted verifiers in app-private
DataStore. Parent and recovery verifiers use independent 128-bit salts and
PBKDF2-HMAC-SHA256 with 310,000 iterations; candidate comparison is
constant-time. Five failures start a persisted 30-second delay, repeated
failures increase it to a capped 15 minutes, and successful verification clears
the counter. Enrollment first requires an explicit choice: an exactly six-digit
PIN entered through the app keypad, or a password of at least eight and at most
64 characters entered through the normal password keyboard. It returns a randomly
generated six-word recovery phrase exactly once. Six distinct words from a
128-word vocabulary provide about 42 bits of entropy: deliberately less than the
previous opaque code, but materially easier to read, type, and send for this
family-facing client restriction. Authenticated change and recovery
reset replace both verifiers and issue a new recovery phrase; unauthenticated
enrollment cannot overwrite an existing or corrupt record.
An authenticated parent may remove the app-global credential without presenting
the recovery phrase. Removal atomically deletes the credential record and sets
every supervised policy to `enabled = false`, so no policy can remain active
without an unlock path. All other policy configuration is retained for later
re-enrollment. It does not delete server-owned Hermes sessions or history. If both the parent
credential and recovery phrase are lost, the deliberate last-resort escape hatch
is Android's **Clear data** action for the app. Uninstall/reinstall is not the
documented recovery path because Android backup restore may restore local state.
Missing, malformed, unsupported-version, weakened-KDF, and unreadable records
fail closed. A legacy enabled policy has no trustworthy app parent identity to
migrate, so it stays at the restricted root. Recovery requires resetting local
app data, reconnecting, and configuring Supervised Mode again; Android must not
disable the policy or promote the current device user automatically. Server
sessions and history are not deleted by that local reset.
The parent policy controls capabilities rather than imposing a special
attachment count. Initial capabilities are text chat, new chat, cancel, steer,
attachments, standard voice, generated-media viewing, save/share media, copy,
@@ -3872,8 +3904,28 @@ or applicable legal obligations. Public language uses **Supervised Mode** or
**parent-controlled client**, not "child account," "safe for children," or
"server enforced."
The verifier design raises the cost of an offline guess but cannot make a
six-digit PIN high entropy. A privileged attacker who can copy or roll back the
app-private store can attempt guesses offline or weaken the persisted backoff;
device integrity, backup policy, and a strong parent password remain relevant.
The recovery phrase may be copied or shared with a brief instruction to remove
the message or saved copy from the phone after it reaches a parent-only place.
It must otherwise be stored outside the supervised user's reach. Stock
Android also cannot give one app a parent-only biometric enrollment or tell the
app which enrolled fingerprint or face authenticated. Biometric convenience may
be considered only as an explicit second layer over this app credential, never
as proof of a distinct parent.
**Localization decision.** Until physical certification and fluent security-copy
review, the Supervised Mode and parent-authentication surface remains canonical
English in every app locale. It intentionally falls back to English and must not
be described as localized. Security-critical setup, recovery, migration, and
lockout wording will move into the translated catalogs together after review;
machine-translating only part of this boundary is not accepted.
**Verification gate.** Implementation requires policy, authentication,
navigation, process-death, deep-link, notification, capability, attachment,
navigation, KDF-record validation, persisted throttling, change/recovery
rotation, corruption/migration, process-death, deep-link, notification, capability, attachment,
voice, session-ownership, Relay-tag, and revocation tests. Physical testing must
cover the exact Android build on a managed/restricted device, including relock,
restart, offline recovery, and attempts to escape the restricted root. Until
+1 -1
View File
@@ -58,7 +58,7 @@ The `area:*` label decides whether a fix can be proven by CI or needs a human.
|--------------------|-------|--------|--------------|
| `area:plugin` | `plugin/` | `python -m unittest plugin.tests.test_<name>` | ✅ ci-plugin.yml |
| `area:cli` | `desktop/` | `cd desktop && npm run build && npm run smoke` + unit | ✅ ci-desktop.yml |
| `area:android` (logic) | `app/` VM/mapper/pure Kotlin | `./gradlew :app:testGooglePlayDebugUnitTest` + `:app:lint` | ✅ ci-android.yml |
| `area:android` (logic) | `app/` VM/mapper/pure Kotlin | focused local test, then exact-SHA `Android On-Demand`/PR CI | ✅ ci-android.yml |
| `area:android` (UI/behavior) | `app/` Compose / device behavior | Android Studio ▶ on a real device | ❌ **human gate** |
| `area:dashboard` | `plugin/dashboard/` | dashboard bundle build | ✅ ci-dashboard.yml |
| `area:docs` | `docs/`, `user-docs/` | docs build | ✅ docs.yml |
+4 -3
View File
@@ -66,6 +66,7 @@ the upstream contract identifiers it depends on.
| Scenario | Contract exercised |
|---|---|
| `initial_history_bind` | Durable, profile-scoped history is already available when the client resumes and first binds its rendered transcript |
| `ordinary_turn` | Normal message start, deltas, completion, and persisted history |
| `rapid_tools_interims` | Rapid chunks, reasoning, tool activity, and interim assistant boundaries |
| `queued_follow_up` | Two explicitly owned turns and ordered queue drainage |
@@ -110,8 +111,8 @@ turn is live. The external lane consumes the shared Python fixture and reads
its authoritative history over HTTP.
```powershell
.\gradlew.bat :app:compileSideloadDebugAndroidTestKotlin
.\gradlew.bat :app:assembleSideloadDebug :app:assembleSideloadDebugAndroidTest
.\scripts\android-lane.ps1 gradle :app:compileSideloadDebugAndroidTestKotlin
.\scripts\android-lane.ps1 gradle :app:assembleSideloadDebug :app:assembleSideloadDebugAndroidTest
```
The external test is opt-in through the instrumentation argument
@@ -125,7 +126,7 @@ transport ID, targets only `com.axiomlabs.hermesrelay.sideload`, and performs no
installation unless its corresponding install flag is supplied.
```powershell
python scripts/android-gateway-certify.py `
.\scripts\android-lane.ps1 exec python scripts/android-gateway-certify.py `
--transport-id <adb-transport-id> `
--apk app/build/outputs/apk/sideload/debug/<sideload-apk> `
--test-apk app/build/outputs/apk/androidTest/sideload/debug/<test-apk> `
+6 -6
View File
@@ -13,7 +13,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
@@ -48,7 +48,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
@@ -72,7 +72,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
@@ -96,7 +96,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
@@ -120,7 +120,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
@@ -135,7 +135,7 @@
"verification": "ai-translated",
"review_refs": [],
"source_sha256": {
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
},
"surfaces": {
+1 -1
View File
@@ -91,7 +91,7 @@ This app is a community project and is not affiliated with or endorsed by NousRe
Paste into Play Console → **What's new** (≤500 characters):
```
v1.14.0 - Connections that follow you
v1.14.0 - Connections, delegated work, Git, and voice
Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.
```
+22 -1
View File
@@ -7,7 +7,7 @@ Android's declarative plugin surface is specified in
**Status:** v1.0.0 stable. The default path supports chat, Manage, and voice on vanilla upstream Hermes without installing the Relay plugin. Relay is additive: terminal, bridge/device control, notification companion, remote access, extra/provider-native voice, desktop tooling, and dashboard Relay management. Historical phase notes remain in this file for context; the current route ownership source of truth is [`docs/upstream-surface-matrix.md`](upstream-surface-matrix.md).
**Repo:** [Codename-11/hermes-relay](https://github.com/Codename-11/hermes-relay)
**Updated:** 2026-08-29
**Updated:** 2026-08-31
---
@@ -51,6 +51,27 @@ token, terminal/bridge grants, and optional network candidates.
selected Hermes profile, server, or agent child-safe. See ADR 66 and the
[Supervised Mode guide](../user-docs/guide/supervised-mode.md).
Supervised Mode parent authority is an app-global PIN or password, not Android's
screen lock, device credential, or biometric prompt. The app stores only
independently salted PBKDF2-HMAC-SHA256 verifiers (310,000 iterations) for the
parent credential and a one-time six-word recovery phrase in app-private DataStore.
The phrase uses six distinct words from a 128-word app vocabulary (about 42 bits)
to favor accurate reading, typing, and parent-to-parent handoff for this client policy.
Verification uses constant-time byte comparison and a persisted, capped backoff.
Missing, malformed, unsupported, or weakened records fail closed. Enrollment is
allowed only when the record is missing; changing it requires the current
credential, and recovery reset requires the current recovery phrase. Both
successful rotation paths issue a new recovery phrase and invalidate the old one.
An authenticated parent may remove the app-global credential without the
recovery phrase; the same atomic write sets every supervised policy to disabled
while preserving its pinned profile, capability toggles, appearance, visibility,
session controls, and relock settings.
If both the credential and recovery phrase are lost, the supported local escape
hatch is Android Settings → Apps → Hermes-Relay → Storage → Clear data.
An existing enabled policy from before this credential scheme has no safe parent
identity to migrate, so it remains restricted and requires local app-data reset
and supervised reconfiguration rather than silently trusting a device user.
---
## 3. Architecture
+4 -4
View File
@@ -4,7 +4,7 @@ appVersionCode = "52"
agp = "9.3.2"
kotlin = "2.4.10"
compose-bom = "2026.08.00"
navigation-compose = "2.9.8"
navigation-compose = "2.10.0"
okhttp = "5.5.0"
kotlinx-serialization = "1.11.0"
kotlinx-coroutines = "1.11.0"
@@ -21,9 +21,9 @@ core-ktx = "1.19.0"
exifinterface = "1.4.2"
datastore = "1.2.1"
splashscreen = "1.2.0"
markdown-renderer = "0.44.0"
coil = "3.5.0"
haze = "1.7.2"
markdown-renderer = "0.45.0"
coil = "3.6.0"
haze = "1.7.3"
mlkit-barcode = "17.3.0"
zxing-core = "3.5.4"
camera = "1.6.1"
+141
View File
@@ -0,0 +1,141 @@
# Hermes-Relay's machine-wide Windows lane for Gradle and Android device work.
# Every worktree uses the same named mutex. Keep this script dependency-free so
# it can run under the Windows PowerShell bundled with Windows.
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$mutexName = "Global\HermesRelay.AndroidBuildLane.v1"
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
function Show-Usage {
Write-Host @"
Usage:
.\scripts\android-lane.ps1 status
.\scripts\android-lane.ps1 [--timeout-seconds <seconds>] gradle <gradle-args...>
.\scripts\android-lane.ps1 [--timeout-seconds <seconds>] exec <command> <args...>
Examples:
.\scripts\android-lane.ps1 gradle :app:testSideloadDebugUnitTest --tests "*ChatViewModelTest*"
.\scripts\android-lane.ps1 exec python scripts/android-gateway-certify.py --help
The default wait is unbounded. Ctrl+C cancels a waiter without affecting the
current owner. Use exec for connected-test or APK-install workflows that must
serialize with wrapper-managed Gradle lanes. Keep Android Studio idle separately.
"@
}
function New-AndroidLaneMutex {
try {
return [System.Threading.Mutex]::new($false, $mutexName)
}
catch [System.UnauthorizedAccessException] {
throw "The machine-wide Hermes-Relay Android lane exists but this Windows account cannot open it. Run all worktrees under the same account or correct the mutex permissions."
}
}
function Test-AcquireMutex {
param(
[System.Threading.Mutex] $Mutex,
[TimeSpan] $Wait
)
try {
return $Mutex.WaitOne($Wait)
}
catch [System.Threading.AbandonedMutexException] {
Write-Warning "The previous Android lane owner exited without releasing the mutex; ownership was recovered."
return $true
}
}
$tokens = @($args)
if ($tokens.Count -eq 0 -or $tokens[0] -in @("help", "--help", "-h")) {
Show-Usage
exit 0
}
$timeoutSeconds = 0
if ($tokens[0] -eq "--timeout-seconds") {
if ($tokens.Count -lt 3) {
throw "--timeout-seconds requires a non-negative integer and a mode."
}
$parsedTimeout = 0
if (-not [int]::TryParse($tokens[1], [ref] $parsedTimeout) -or $parsedTimeout -lt 0) {
throw "--timeout-seconds must be a non-negative integer."
}
$timeoutSeconds = $parsedTimeout
$tokens = @($tokens[2..($tokens.Count - 1)])
}
$mode = $tokens[0]
$mutex = New-AndroidLaneMutex
$acquired = $false
try {
if ($mode -eq "status") {
$acquired = Test-AcquireMutex -Mutex $mutex -Wait ([TimeSpan]::Zero)
if ($acquired) {
Write-Host "Hermes-Relay Android lane: IDLE"
$mutex.ReleaseMutex()
$acquired = $false
exit 0
}
Write-Host "Hermes-Relay Android lane: BUSY"
exit 1
}
if ($mode -notin @("gradle", "exec")) {
throw "Unknown mode '$mode'. Use status, gradle, or exec."
}
if ($mode -eq "exec" -and $tokens.Count -lt 2) {
throw "exec requires a command."
}
$waitDescription = if ($timeoutSeconds -eq 0) { "without a timeout" } else { "for up to $timeoutSeconds seconds" }
Write-Host "Waiting for the machine-wide Hermes-Relay Android lane $waitDescription..."
$startedWaiting = [System.Diagnostics.Stopwatch]::StartNew()
while (-not $acquired) {
$sliceSeconds = 30
if ($timeoutSeconds -gt 0) {
$remaining = $timeoutSeconds - [int][Math]::Floor($startedWaiting.Elapsed.TotalSeconds)
if ($remaining -le 0) {
throw "Timed out waiting for the machine-wide Hermes-Relay Android lane after $timeoutSeconds seconds."
}
$sliceSeconds = [Math]::Min($sliceSeconds, $remaining)
}
$acquired = Test-AcquireMutex -Mutex $mutex -Wait ([TimeSpan]::FromSeconds($sliceSeconds))
if (-not $acquired) {
Write-Host "Still waiting for the Hermes-Relay Android lane ($([int]$startedWaiting.Elapsed.TotalSeconds)s elapsed)..."
}
}
Write-Host "Acquired the machine-wide Hermes-Relay Android lane."
Push-Location $repoRoot
try {
if ($mode -eq "gradle") {
$executable = Join-Path $repoRoot "gradlew.bat"
$commandArguments = if ($tokens.Count -gt 1) { @($tokens[1..($tokens.Count - 1)]) } else { @() }
}
else {
$executable = $tokens[1]
$commandArguments = if ($tokens.Count -gt 2) { @($tokens[2..($tokens.Count - 1)]) } else { @() }
}
& $executable @commandArguments
$commandExitCode = if ($null -eq $LASTEXITCODE) { 0 } else { $LASTEXITCODE }
}
finally {
Pop-Location
}
exit $commandExitCode
}
finally {
if ($acquired) {
$mutex.ReleaseMutex()
Write-Host "Released the machine-wide Hermes-Relay Android lane."
}
$mutex.Dispose()
}
+34 -9
View File
@@ -1,8 +1,11 @@
#!/usr/bin/env python3
"""Run fast Android checks before pushing a PR update.
"""Run the optional full local Android pre-push gate.
The command checks the primary Play debug variant and focused CI unit tests in
one Gradle invocation. Hosted CI remains the exhaustive all-variant gate.
By default the command checks the primary Play debug variant and focused CI
unit tests in one Gradle invocation. `--both-flavors` expands that to full lint
and both focused flavor shards. Agents should prefer Android On-Demand after an
exact commit is already pushed; this remains available when full local proof is
explicitly wanted or cloud execution is unavailable.
"""
from __future__ import annotations
@@ -71,6 +74,11 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--skip-lint", action="store_true", help="Skip Android lint")
parser.add_argument("--skip-tests", action="store_true", help="Skip the focused unit-test shard")
parser.add_argument(
"--both-flavors",
action="store_true",
help="Run full lint and focused tests for sideload and Google Play",
)
args = parser.parse_args()
env = android_environment()
@@ -79,24 +87,41 @@ def main() -> int:
tasks: list[str] = []
if not args.skip_lint:
tasks.append(":app:lintGooglePlayDebug")
tasks.append("lint" if args.both_flavors else ":app:lintGooglePlayDebug")
if not args.skip_tests:
tasks.append(":app:testSideloadDebugUnitTest")
if args.both_flavors:
tasks.append(":app:testGooglePlayDebugUnitTest")
if not tasks:
print("\nAndroid repository checks passed.")
return 0
wrapper = REPO_ROOT / ("gradlew.bat" if sys.platform == "win32" else "gradlew")
gradle = [
str(wrapper),
if sys.platform == "win32":
gradle = [
"powershell.exe",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(REPO_ROOT / "scripts" / "android-lane.ps1"),
"gradle",
]
else:
gradle = [str(REPO_ROOT / "gradlew")]
gradle.extend([
"--console=plain",
"--configuration-cache",
*tasks,
]
])
if not args.skip_tests:
for test_name in FOCUSED_TESTS:
gradle.extend(("--tests", test_name))
run("Google Play lint and focused tests", gradle, env)
label = (
"Full local Android lint and focused tests"
if args.both_flavors
else "Google Play lint and focused tests"
)
run(label, gradle, env)
print("\nAndroid pre-push checks passed.")
return 0
+3 -3
View File
@@ -68,9 +68,9 @@ echo ""
echo " Next steps:"
echo " 1. Update CHANGELOG.md, RELEASE_NOTES.md, and prepend the curated Android"
echo " release entry to app/src/main/assets/changelog.json. The newest entry"
echo " requires highlight {title,summary,bullets[1..3]}, improvements[0..2],"
echo " toastDigest {additionalFeatureCount,fixCount,preview[0..2]}, playNotes,"
echo " and the technical sections retained for history."
echo " requires one overall title + summary, a complete changes[] inventory"
echo " with unique ids/kinds/titles/explanations and 1..4 highlights, optional"
echo " compatibility bullets, and playNotes. Toast counts/previews are derived."
echo " 2. Refresh and validate the derived in-app fallback + Play notes:"
echo " python scripts/check-android-release-notes.py --write"
echo " python scripts/check-android-release-notes.py"
+72 -62
View File
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
"""Validate and synchronize Android release-note surfaces.
The newest ``changelog.json`` entry is the curated source for the in-app
What's New experience. ``--write`` refreshes the legacy text fallback, Google
Play notes, and the matching operator copy in ``docs/play-store-listing.md``.
The technical CHANGELOG and GitHub release body remain fuller records, but
their version headings are checked so release prep cannot silently drift.
The newest ``changelog.json`` entry is the complete user-visible source for the
in-app What's New experience. ``--write`` refreshes the legacy text fallback,
Google Play notes, and the matching operator copy in
``docs/play-store-listing.md``. The technical CHANGELOG and GitHub release body
remain separate records, but their version headings are checked so release
prep cannot silently drift.
"""
from __future__ import annotations
@@ -29,6 +30,12 @@ PLAY_SECTION_RE = re.compile(
r"\(≤500 characters\):\s+```\s*\n)(.*?)(\n```\s*\n## Category)",
re.DOTALL,
)
CHANGE_KINDS = ("added", "improved", "fixed")
CHANGE_KIND_LABELS = {
"added": "Added",
"improved": "Improved",
"fixed": "Fixed",
}
def _read_text(relative: pathlib.Path) -> str:
@@ -44,8 +51,8 @@ def _android_version() -> str:
def _latest_entry() -> dict[str, Any]:
data = json.loads(_read_text(CHANGELOG_JSON))
if not isinstance(data, dict) or data.get("schema") != 2:
raise ValueError("changelog.json must use schema 2")
if not isinstance(data, dict) or data.get("schema") != 3:
raise ValueError("changelog.json must use schema 3")
versions = data.get("versions")
if not isinstance(versions, list) or not versions or not isinstance(versions[0], dict):
raise ValueError("changelog.json must contain at least one version")
@@ -60,60 +67,51 @@ def validate_curated_entry(entry: dict[str, Any], expected_version: str) -> list
f"latest changelog version is {version!r}, expected Android {expected_version!r}"
)
for field in ("title", "date"):
for field in ("title", "date", "summary"):
if not isinstance(entry.get(field), str) or not entry[field].strip():
errors.append(f"latest changelog entry requires non-empty {field}")
highlight = entry.get("highlight")
if not isinstance(highlight, dict):
errors.append("latest changelog entry requires a highlight object")
highlight = {}
for field in ("title", "summary"):
if not isinstance(highlight.get(field), str) or not highlight[field].strip():
errors.append(f"latest changelog highlight requires non-empty {field}")
changes = entry.get("changes")
if not isinstance(changes, list) or not changes:
errors.append("latest changelog entry requires a non-empty changes array")
changes = []
bullets = highlight.get("bullets")
if not isinstance(bullets, list):
errors.append("latest changelog highlight bullets must be an array")
bullets = []
elif not 1 <= len(bullets) <= 3:
errors.append("latest changelog highlight must contain 1-3 bullets")
if any(not isinstance(item, str) or not item.strip() for item in bullets):
errors.append("latest changelog highlight bullets must be non-empty strings")
improvements = entry.get("improvements", [])
if not isinstance(improvements, list):
errors.append("latest changelog improvements must be an array")
improvements = []
elif len(improvements) > 2:
errors.append("latest changelog may contain at most 2 improvements")
if any(not isinstance(item, str) or not item.strip() for item in improvements):
errors.append("latest changelog improvements must be non-empty strings")
if len(bullets) + len(improvements) > 5:
errors.append("latest changelog may expose at most 5 total list items")
digest = entry.get("toastDigest")
if not isinstance(digest, dict):
errors.append("latest changelog entry requires a toastDigest object")
digest = {}
digest_counts: list[int] = []
for field in ("additionalFeatureCount", "fixCount"):
count = digest.get(field)
if isinstance(count, bool) or not isinstance(count, int) or count < 0:
errors.append(f"latest changelog toastDigest {field} must be a non-negative integer")
seen_ids: set[str] = set()
highlight_count = 0
for index, change in enumerate(changes):
prefix = f"latest changelog change {index + 1}"
if not isinstance(change, dict):
errors.append(f"{prefix} must be an object")
continue
change_id = change.get("id")
if not isinstance(change_id, str) or not change_id.strip():
errors.append(f"{prefix} requires a non-empty id")
elif change_id in seen_ids:
errors.append(f"latest changelog change id {change_id!r} is duplicated")
else:
digest_counts.append(count)
digest_preview = digest.get("preview")
if not isinstance(digest_preview, list):
errors.append("latest changelog toastDigest preview must be an array")
digest_preview = []
elif any(not isinstance(item, str) or not item.strip() for item in digest_preview):
errors.append("latest changelog toastDigest preview items must be non-empty strings")
if len(digest_counts) == 2:
if sum(digest_counts) == 0 and digest_preview:
errors.append("latest changelog toastDigest preview must be empty when counts are zero")
elif sum(digest_counts) > 0 and not 1 <= len(digest_preview) <= 2:
errors.append("latest changelog toastDigest preview must contain 1-2 items when secondary items exist")
seen_ids.add(change_id)
if change.get("kind") not in CHANGE_KINDS:
errors.append(f"{prefix} kind must be one of {', '.join(CHANGE_KINDS)}")
for field in ("title", "summary"):
if not isinstance(change.get(field), str) or not change[field].strip():
errors.append(f"{prefix} requires non-empty {field}")
is_highlight = change.get("highlight", False)
if not isinstance(is_highlight, bool):
errors.append(f"{prefix} highlight must be a boolean")
elif is_highlight:
highlight_count += 1
if not 1 <= highlight_count <= 4:
errors.append("latest changelog must select 1-4 highlighted changes")
compatibility = entry.get("compatibility", [])
if not isinstance(compatibility, list):
errors.append("latest changelog compatibility must be an array")
elif any(not isinstance(item, str) or not item.strip() for item in compatibility):
errors.append("latest changelog compatibility items must be non-empty strings")
for legacy_field in ("highlight", "improvements", "toastDigest"):
if legacy_field in entry:
errors.append(f"latest changelog must derive presentation instead of defining {legacy_field}")
play_notes = entry.get("playNotes")
if not isinstance(play_notes, str) or not play_notes.strip():
@@ -124,19 +122,31 @@ def validate_curated_entry(entry: dict[str, Any], expected_version: str) -> list
def render_whats_new(entry: dict[str, Any]) -> str:
highlight = entry["highlight"]
lines = [
f"v{entry['version']} - {entry['title']}",
"",
highlight["title"],
*(f"* {bullet}" for bullet in highlight["bullets"]),
"Summary",
f"* {entry['summary']}",
]
improvements = entry.get("improvements", [])
if improvements:
lines.extend(("", "Also improved", *(f"* {item}" for item in improvements)))
changes = entry["changes"]
highlights = [change for change in changes if change.get("highlight", False)]
if highlights:
lines.extend(("", "Highlights", *(_render_change(change) for change in highlights)))
remaining = [change for change in changes if not change.get("highlight", False)]
for kind in CHANGE_KINDS:
items = [change for change in remaining if change["kind"] == kind]
if items:
lines.extend(("", CHANGE_KIND_LABELS[kind], *(_render_change(change) for change in items)))
compatibility = entry.get("compatibility", [])
if compatibility:
lines.extend(("", "Compatibility", *(f"* {item}" for item in compatibility)))
return "\n".join(lines) + "\n"
def _render_change(change: dict[str, Any]) -> str:
return f"* {change['title']} — {change['summary']}"
def render_play_notes(entry: dict[str, Any]) -> str:
return f"v{entry['version']} - {entry['title']}\n\n{entry['playNotes'].strip()}\n"
+30 -18
View File
@@ -4,6 +4,11 @@ REM Usage: scripts\dev.bat <command>
cd /d "%~dp0\.."
REM Secondary worktrees normally do not carry local.properties. Reuse the
REM standard per-user SDK location when the caller has not selected one.
if not defined ANDROID_HOME if exist "%LOCALAPPDATA%\Android\Sdk" set "ANDROID_HOME=%LOCALAPPDATA%\Android\Sdk"
if not defined ANDROID_SDK_ROOT if defined ANDROID_HOME set "ANDROID_SDK_ROOT=%ANDROID_HOME%"
if "%1"=="" goto help
if "%1"=="build" goto build
if "%1"=="release" goto release
@@ -27,14 +32,15 @@ goto help
:build
echo Building sideload debug APK...
call gradlew.bat :app:assembleSideloadDebug --console=plain
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:assembleSideloadDebug --console=plain
if errorlevel 1 exit /b %errorlevel%
echo APK: app\build\outputs\apk\sideload\debug\
goto end
:release
echo Building release APK...
call gradlew.bat assembleRelease
if errorlevel 1 goto end
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle assembleRelease
if errorlevel 1 exit /b %errorlevel%
echo.
echo Release APK:
dir /b app\build\outputs\apk\release\*.apk 2>nul
@@ -43,8 +49,8 @@ goto end
:bundle
echo Building release AAB (for Google Play upload)...
call gradlew.bat bundleRelease
if errorlevel 1 goto end
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle bundleRelease
if errorlevel 1 exit /b %errorlevel%
echo.
echo Release AAB:
dir /b app\build\outputs\bundle\release\*.aab 2>nul
@@ -53,8 +59,8 @@ goto end
:install
echo Building and installing sideload debug to connected device...
call gradlew.bat :app:installSideloadDebug --console=plain
if errorlevel 1 goto end
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:installSideloadDebug --console=plain
if errorlevel 1 exit /b %errorlevel%
echo Launching app...
REM Explicit FQCN: the sideload applicationId includes the flavor suffix but the
REM namespace (and thus the real class FQCN) is still com.hermesandroid.relay,
@@ -64,8 +70,8 @@ goto end
:run
echo Building, installing, and launching sideload debug...
call gradlew.bat :app:installSideloadDebug --console=plain
if errorlevel 1 goto end
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:installSideloadDebug --console=plain
if errorlevel 1 exit /b %errorlevel%
REM Explicit FQCN: the sideload applicationId includes the flavor suffix but the
REM namespace (and thus the real class FQCN) is still com.hermesandroid.relay,
REM so the `.MainActivity` shorthand no longer resolves correctly.
@@ -75,7 +81,8 @@ goto end
:compile
echo Compiling sideload debug Kotlin...
call gradlew.bat :app:compileSideloadDebugKotlin --console=plain
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:compileSideloadDebugKotlin --console=plain
if errorlevel 1 exit /b %errorlevel%
goto end
:testone
@@ -84,35 +91,40 @@ if "%~2"=="" (
exit /b 2
)
echo Running focused sideload test: %~2
call gradlew.bat :app:testSideloadDebugUnitTest --tests "%~2" --console=plain
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:testSideloadDebugUnitTest --tests "%~2" --console=plain
if errorlevel 1 exit /b %errorlevel%
goto end
:installfast
echo Building arm64 sideload debug and installing to connected phone...
call gradlew.bat :app:installSideloadDebug -Phermes.devAbi=arm64-v8a --console=plain
if errorlevel 1 goto end
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:installSideloadDebug -Phermes.devAbi=arm64-v8a --console=plain
if errorlevel 1 exit /b %errorlevel%
echo Launching app...
adb shell am start -n com.axiomlabs.hermesrelay.sideload/com.hermesandroid.relay.MainActivity
goto end
:test
echo Running sideload debug unit tests...
call gradlew.bat :app:testSideloadDebugUnitTest --console=plain
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:testSideloadDebugUnitTest --console=plain
if errorlevel 1 exit /b %errorlevel%
goto end
:lint
echo Running sideload debug lint...
call gradlew.bat :app:lintSideloadDebug --console=plain
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle :app:lintSideloadDebug --console=plain
if errorlevel 1 exit /b %errorlevel%
goto end
:prepush
echo Running Android pre-push checks...
python scripts\android-prepush.py
python scripts\android-prepush.py --both-flavors
if errorlevel 1 exit /b %errorlevel%
goto end
:clean
echo Cleaning build...
call gradlew.bat clean
call powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\android-lane.ps1 gradle clean
if errorlevel 1 exit /b %errorlevel%
goto end
:devices
@@ -162,7 +174,7 @@ echo test-one Run one test class or wildcard pattern
echo install-fast Build arm64 only + install + launch
echo test Run sideload debug unit tests
echo lint Run lint checks
echo prepush Run Android repository checks, lint, and focused CI tests
echo prepush Run the optional full local Android verification gate
echo clean Clean build outputs
echo devices List connected devices
echo version Show current version from libs.versions.toml
+2 -2
View File
@@ -57,7 +57,7 @@ case "${1:-help}" in
;;
prepush)
echo "Running Android pre-push checks..."
python3 scripts/android-prepush.py
python3 scripts/android-prepush.py --both-flavors
;;
clean)
echo "Cleaning build..."
@@ -103,7 +103,7 @@ case "${1:-help}" in
echo " install-fast Build arm64 only + install + launch"
echo " test Run sideload debug unit tests"
echo " lint Run lint checks"
echo " prepush Run Android repository checks, lint, and focused CI tests"
echo " prepush Run the optional full local Android verification gate"
echo " clean Clean build outputs"
echo " devices List connected devices"
echo " wireless Pair for wireless debugging"
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import importlib.util
import sys
import unittest
from pathlib import Path
from unittest import mock
SCRIPT_PATH = Path(__file__).resolve().parents[1] / "android-prepush.py"
SPEC = importlib.util.spec_from_file_location("android_prepush", SCRIPT_PATH)
if SPEC is None or SPEC.loader is None:
raise RuntimeError(f"Unable to load {SCRIPT_PATH}")
android_prepush = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(android_prepush)
class AndroidPrepushTest(unittest.TestCase):
def run_main(self, *arguments: str) -> list[mock._Call]:
with (
mock.patch.object(sys, "argv", ["android-prepush.py", *arguments]),
mock.patch.object(android_prepush, "android_environment", return_value={}),
mock.patch.object(android_prepush, "run") as run,
):
self.assertEqual(android_prepush.main(), 0)
return run.call_args_list
def test_default_local_gate_runs_sideload_tests_only(self) -> None:
calls = self.run_main()
gradle = calls[-1].args[1]
self.assertIn(":app:lintGooglePlayDebug", gradle)
self.assertIn(":app:testSideloadDebugUnitTest", gradle)
self.assertNotIn(":app:testGooglePlayDebugUnitTest", gradle)
def test_both_flavors_adds_google_play_focused_tests(self) -> None:
calls = self.run_main("--both-flavors")
gradle = calls[-1].args[1]
self.assertIn("lint", gradle)
self.assertNotIn(":app:lintGooglePlayDebug", gradle)
self.assertIn(":app:testSideloadDebugUnitTest", gradle)
self.assertIn(":app:testGooglePlayDebugUnitTest", gradle)
if __name__ == "__main__":
unittest.main()
@@ -12,85 +12,78 @@ release_notes = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(release_notes)
def entry(*, bullets: int = 3, improvements: int = 2) -> dict[str, object]:
def entry(*, highlight_count: int = 2) -> dict[str, object]:
changes = [
{
"id": f"change-{index}",
"kind": ("added", "improved", "fixed")[index % 3],
"title": f"Change {index}",
"summary": f"User-facing explanation {index}.",
"highlight": index < highlight_count,
}
for index in range(5)
]
return {
"version": "1.2.3",
"title": "A useful release",
"date": "2026-08-26",
"highlight": {
"title": "The main reason to care",
"summary": "A short explanation in plain language.",
"bullets": [f"Benefit {index}" for index in range(bullets)],
},
"improvements": [f"Improvement {index}" for index in range(improvements)],
"toastDigest": {
"additionalFeatureCount": 1,
"fixCount": 2,
"preview": ["Secondary feature", "Important fix"],
},
"summary": "A short explanation in plain language.",
"changes": changes,
"compatibility": ["Works with existing connections."],
"playNotes": "A concise Play Store summary.",
}
class AndroidReleaseNotesTest(unittest.TestCase):
def test_allows_three_highlights_and_two_improvements(self) -> None:
def test_accepts_complete_change_inventory(self) -> None:
self.assertEqual([], release_notes.validate_curated_entry(entry(), "1.2.3"))
def test_rejects_more_than_three_highlights(self) -> None:
errors = release_notes.validate_curated_entry(entry(bullets=4, improvements=0), "1.2.3")
self.assertIn("latest changelog highlight must contain 1-3 bullets", errors)
def test_rejects_more_than_four_highlights(self) -> None:
errors = release_notes.validate_curated_entry(entry(highlight_count=5), "1.2.3")
self.assertIn("latest changelog must select 1-4 highlighted changes", errors)
def test_rejects_more_than_five_visible_items(self) -> None:
errors = release_notes.validate_curated_entry(entry(bullets=3, improvements=3), "1.2.3")
self.assertIn("latest changelog may contain at most 2 improvements", errors)
self.assertIn("latest changelog may expose at most 5 total list items", errors)
def test_rejects_duplicate_change_ids(self) -> None:
release = entry()
release["changes"][1]["id"] = "change-0" # type: ignore[index]
errors = release_notes.validate_curated_entry(release, "1.2.3")
self.assertIn("latest changelog change id 'change-0' is duplicated", errors)
def test_renders_fallback_with_curated_groups(self) -> None:
rendered = release_notes.render_whats_new(entry(bullets=1, improvements=1))
self.assertIn("The main reason to care\n* Benefit 0", rendered)
self.assertIn("Also improved\n* Improvement 0", rendered)
def test_rejects_unknown_change_kind(self) -> None:
release = entry()
release["changes"][2]["kind"] = "technical" # type: ignore[index]
errors = release_notes.validate_curated_entry(release, "1.2.3")
self.assertIn("latest changelog change 3 kind must be one of added, improved, fixed", errors)
def test_renders_complete_fallback_without_duplicate_highlights(self) -> None:
rendered = release_notes.render_whats_new(entry())
self.assertIn("Summary\n* A short explanation in plain language.", rendered)
self.assertIn("Highlights\n* Change 0 — User-facing explanation 0.", rendered)
self.assertIn("Fixed\n* Change 2 — User-facing explanation 2.", rendered)
self.assertEqual(1, rendered.count("Change 0 — User-facing explanation 0."))
self.assertIn("Compatibility\n* Works with existing connections.", rendered)
def test_play_notes_include_version_and_stay_bounded(self) -> None:
rendered = release_notes.render_play_notes(entry())
self.assertTrue(rendered.startswith("v1.2.3 - A useful release"))
self.assertLessEqual(len(rendered), 500)
def test_allows_a_hero_only_release_without_secondary_filler(self) -> None:
def test_allows_a_highlights_only_release(self) -> None:
release = entry()
release["toastDigest"] = {
"additionalFeatureCount": 0,
"fixCount": 0,
"preview": [],
}
release["changes"] = release["changes"][:2] # type: ignore[index]
self.assertEqual([], release_notes.validate_curated_entry(release, "1.2.3"))
def test_rejects_preview_when_secondary_counts_are_zero(self) -> None:
release = entry()
release["toastDigest"] = {
"additionalFeatureCount": 0,
"fixCount": 0,
"preview": ["Invented filler"],
}
errors = release_notes.validate_curated_entry(release, "1.2.3")
self.assertIn("latest changelog toastDigest preview must be empty when counts are zero", errors)
def test_requires_a_bounded_preview_for_secondary_items(self) -> None:
def test_rejects_legacy_manual_digest(self) -> None:
release = entry()
release["toastDigest"] = {
"additionalFeatureCount": 1,
"fixCount": 2,
"preview": ["one", "two", "three"],
"preview": ["Duplicated summary"],
}
errors = release_notes.validate_curated_entry(release, "1.2.3")
self.assertIn(
"latest changelog toastDigest preview must contain 1-2 items when secondary items exist",
errors,
)
self.assertIn("latest changelog must derive presentation instead of defining toastDigest", errors)
if __name__ == "__main__":
+4
View File
@@ -88,6 +88,10 @@ The initial catalog covers ordinary streaming, rapid chunks/reasoning/tool
events, queued turns, scoped and foreign/unscoped inputs, persisted history,
and both issue #365 terminal-gap forms:
- `initial_history_bind`: a durable, profile-scoped transcript exists before
the client resumes, so rendered clients can exercise first-composition
binding without relying on a new turn to trigger recomposition.
- `subagent_child_preview`: interleaved concurrent child lifecycle events carry
stable child/session identity, thinking/progress/tool previews, and distinct
completed/interrupted terminal states. Its upstream requirement also proves
@@ -77,6 +77,29 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
await rejected.release()
await ws.close()
async def test_initial_history_is_available_before_session_resume(self) -> None:
fixture, base_url = await self.start("initial_history_bind")
async with self.session.get(
f"{base_url}/api/sessions/{fixture.scenario.stored_session_id}/messages",
params={"profile": "research", "limit": 500, "offset": 0, "order": "asc"},
) as response:
history = await response.json()
self.assertEqual(
["Open the durable Bot Chat.", "Durable Bot Chat history is ready."],
[row["content"] for row in history["messages"]],
)
ws, _ = await self.connect(base_url)
await self.rpc(
ws,
1,
"session.resume",
{"session_id": fixture.scenario.stored_session_id, "profile": "research"},
)
resumed = (await ws.receive_json())["result"]
self.assertEqual(fixture.scenario.live_session_id, resumed["session_id"])
self.assertEqual(fixture.scenario.stored_session_id, resumed["stored_session_id"])
async def test_ordinary_turn_persists_authoritative_history(self) -> None:
fixture, base_url = await self.start("ordinary_turn")
ws, _ = await self.connect(base_url)
@@ -307,6 +330,7 @@ class ScenarioTestCase(unittest.TestCase):
"active_status_profile_scope",
"active_status_unsupported",
"cross_client_observation",
"initial_history_bind",
"ordinary_turn",
"rapid_tools_interims",
"subagent_child_preview",
@@ -334,7 +358,11 @@ class ScenarioTestCase(unittest.TestCase):
from vanilla_gateway.scenario import Scenario
Scenario.from_dict(scenario)
def test_terminal_gap_manifests_select_upstream_contracts(self) -> None:
def test_contract_manifests_select_upstream_contracts(self) -> None:
self.assertEqual(
("gateway.session_resume_durable",),
load_scenario("initial_history_bind").contract_requirements,
)
self.assertEqual(
(
"gateway.message_complete",
@@ -0,0 +1,14 @@
{
"name": "initial_history_bind",
"live_session_id": "fixture-live-history",
"stored_session_id": "20260829_120000_bot_chat",
"profile": "research",
"contract_requirements": [
"gateway.session_resume_durable"
],
"initial_history": [
{"id": 1, "role": "user", "content": "Open the durable Bot Chat.", "timestamp": 1.0},
{"id": 2, "role": "assistant", "content": "Durable Bot Chat history is ready.", "timestamp": 2.0, "finish_reason": "stop"}
],
"turns": []
}
+1 -1
View File
@@ -17,7 +17,7 @@ plugins {
kotlin("jvm")
// Compose compiler — version inherited from the root plugins {} block.
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.compose") version "1.11.1"
id("org.jetbrains.compose") version "1.12.0"
}
kotlin {
+48 -14
View File
@@ -41,11 +41,16 @@ From full Android Settings, the parent:
1. Open **Settings → Advanced → Supervised Mode** for the active Hermes
Connection.
2. Choose one existing named profile. Android requires a secure device screen
lock before the mode can be enabled.
3. Select the allowed features and any stricter attachment or history limits.
4. Choose a visibility preset or customize what appears in Chat.
5. Review the summary, then enable the mode.
2. Choose one existing named profile.
3. Choose either an app-specific six-digit parent PIN or a parent password of
at least eight characters. The PIN uses the app keypad; passwords use the
normal keyboard and password-manager flow. This is separate from the phone's screen lock.
4. Save the one-time six-word recovery phrase somewhere the supervised user
cannot access. You may share it to a parent-only destination; delete the
message or saved copy from this phone afterward.
5. Select the allowed features and any stricter attachment or history limits.
6. Choose a visibility preset or customize what appears in Chat.
7. Review the summary, then verify the parent credential to enable the mode.
The app returns to the pinned profile's Chat screen. If the Connection or
profile is unavailable, the restricted client shows a recovery state
@@ -58,8 +63,9 @@ Supervised Mode banner consuming conversation space. The agent name and avatar
remain the primary identity, with a small connection state when permitted.
The existing Settings button opens **Restricted Settings**, which contains only
approved preferences. A clearly labelled **Parent access** row starts device
authentication before any parent controls or full application settings appear.
approved preferences. A clearly labelled **Parent access** row asks for the
app-specific parent PIN or password before any parent controls or full
application settings appear.
Restricted Settings may include:
@@ -166,14 +172,38 @@ and avatar provide the normal identity in the Simple preset.
## Parent access and relocking
Enabling, changing, or ending Supervised Mode requires Android device
authentication. Parent access should relock when its authenticated task closes,
after the configured inactivity period, when the app backgrounds, or after
process recreation.
Enabling, changing, or ending Supervised Mode requires the app-specific parent
PIN or password. Parent access relocks when its authenticated task closes, after
the configured inactivity period, when the app backgrounds, or after process
recreation. Failure delays persist across app restart.
Android's device-credential prompt authenticates any user enrolled for that
device; it does not establish a separate parent identity. Use a device lock the
supervised user does not know, or keep the device under direct supervision.
The credential is global to this Android app installation, not scoped to one
Connection. Changing it or resetting it with the current recovery phrase rotates
the phrase, which is shown only once. If the credential record is missing
or damaged, Supervised Mode fails closed. A legacy installation that was already
enabled before app-specific parent credentials existed must reset local app
data, reconnect, and configure the mode again; it does not silently trust the
current Android user. That reset does not delete server-owned Hermes history.
While parent access is unlocked, **Remove parent credential** is available in
the parent controls even if the recovery phrase has been lost. Confirming it
disables Supervised Mode for every Connection and removes the app-wide PIN or
password and recovery verifier. Pinned profiles, capability toggles, appearance,
visibility, session controls, and relock settings are preserved. Server sessions
and history are preserved.
If both the parent credential and recovery phrase are lost, use Android
**Settings → Apps → Hermes-Relay → Storage → Clear data**. This also removes
local Connections, sign-ins, preferences, and caches, but does not delete
server-owned Hermes sessions. Uninstall/reinstall is not the documented escape
hatch because Android may restore backed-up local app state.
The app stores salted PBKDF2 verifiers, not the parent password or recovery phrase,
and applies persisted attempt delays. Prefer a strong password: a six-digit PIN
still has limited resistance if a privileged attacker copies the app-private
data and guesses offline. Stock Android cannot create parent-only biometric
enrollment for one app or tell the app which enrolled fingerprint or face was
used, so device biometrics are not accepted as parent identity.
The restricted root is restored before the first interactive screen. Deep
links, notification actions, shortcuts, saved back stacks, and share intents
@@ -209,6 +239,10 @@ Supervised Mode cannot control:
- the developmental suitability or factual accuracy of model output;
- Android behavior outside the Hermes-Relay app.
The experimental Supervised Mode and parent-authentication screens currently use
canonical English in every app locale pending fluent review of the complete
security and recovery wording. Do not assume those screens are localized.
Use it alongside a restrictive Hermes profile, parental supervision, Android
parental or enterprise controls where appropriate, and regular review of the
profile and its conversations.