Merge origin/dev into fix/android-stale-stream-liveness
# Conflicts: # CHANGELOG.md # docs/spec.md # docs/upstream-surface-matrix.md
This commit is contained in:
@@ -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,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.
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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,6 +101,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -85,6 +85,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -7,12 +7,15 @@ coding agent (Claude Code, Codex, Cursor, etc.).
|
||||
|
||||
This file is the provider-neutral canonical agent context. Read it before
|
||||
touching code, then `docs/spec.md` and `docs/decisions.md`. Provider adapters
|
||||
such as **[CLAUDE.md](CLAUDE.md)** may add tool-specific guidance, but they do
|
||||
not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
|
||||
such as **[CLAUDE.md](CLAUDE.md)** import this file instead of duplicating
|
||||
policy. They do not redefine the branch, release, hotfix, or verification
|
||||
contract here and in `RELEASE.md`.
|
||||
|
||||
- Release process → **[RELEASE.md](RELEASE.md)**
|
||||
- Contributor setup → **[CONTRIBUTING.md](CONTRIBUTING.md)**
|
||||
- Gateway/session/reconnect testing → **[docs/gateway-contract-testing.md](docs/gateway-contract-testing.md)**
|
||||
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
|
||||
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
|
||||
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
|
||||
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
|
||||
@@ -62,8 +65,10 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
||||
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||
compatibility surface; Relay adds optional extensions. A Gateway-owned
|
||||
conversation never changes transport because Gateway auth or reachability
|
||||
changes. This
|
||||
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
@@ -83,16 +88,21 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
Version bumps happen only on a release-prep branch targeting `dev`, and
|
||||
production tags are cut only from `main`.
|
||||
- **Android:** Jetpack Compose only (no XML), kotlinx.serialization (no Gson),
|
||||
OkHttp (no Ktor), `wss://` only. Run `./gradlew lint` before pushing Kotlin.
|
||||
For interactive device-review loops, run focused tests plus the affected
|
||||
assemble/install task; run the full affected-variant lint once when the
|
||||
combined candidate is final, or earlier only for lint-sensitive resource,
|
||||
manifest, dependency, or build-configuration changes. Do not repeat full
|
||||
variant lint after every small Kotlin iteration.
|
||||
OkHttp (no Ktor), `wss://` only. While editing, use only the narrow local
|
||||
compile or focused test needed for feedback, through `scripts/android-lane.ps1`
|
||||
on Windows. Once an exact commit is already pushed, prefer the `Android
|
||||
On-Demand` workflow for lint, the focused shards, both-flavor assemblies, and
|
||||
release smoke; isolated cloud jobs may run concurrently. Do not push solely
|
||||
to obtain cloud compute without push authorization, and do not duplicate a
|
||||
preset already running for the same SHA. Full local verification remains
|
||||
available through `scripts/dev.bat prepush` (or `./scripts/dev.sh prepush`)
|
||||
when explicitly wanted or when cloud execution is unavailable.
|
||||
Physical-device checks and APK installation remain separately owned local
|
||||
evidence.
|
||||
- **Plugin (Python 3.11+):** aiohttp + asyncio (no threading), type hints
|
||||
everywhere, structured `logging` (no `print`). **Desktop CLI (Node ≥21):**
|
||||
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Full
|
||||
per-language style and the dev loop live in CLAUDE.md → "Code Style".
|
||||
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Contributor
|
||||
commands and the development loop live in `CONTRIBUTING.md`.
|
||||
|
||||
## Review guidelines
|
||||
|
||||
|
||||
@@ -6,10 +6,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
|
||||
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
|
||||
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
|
||||
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
|
||||
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
|
||||
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
|
||||
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
|
||||
- **Android Chat settles an owned Gateway turn when its terminal frame is lost.** An exact idle `session.active_list` snapshot now completes the matching local stream, reconciles durable history, and drains its queued follow-up without interrupting or claiming Desktop/TUI work.
|
||||
- **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
|
||||
|
||||
|
||||
@@ -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 `` 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 > 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 > zip > 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` -> 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
@@ -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.
|
||||
|
||||
@@ -1,5 +1,40 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-08-31 — Android Gateway compaction watchdog lease
|
||||
|
||||
Gateway turns now recognize the upstream `status.update` payload kind
|
||||
`compacting` and arm a ten-minute idle lease instead of the ordinary
|
||||
three-minute watchdog. A single current-Gateway status protects silent
|
||||
compaction, while repeated status heartbeats from newer gateways refresh the
|
||||
same lease. Other status payloads retain the ordinary watchdog.
|
||||
|
||||
Focused Gateway client coverage uses shortened timeout seams to prove the
|
||||
single-status, repeated-heartbeat, ordinary-silence, and payload-fencing paths
|
||||
without waiting production minutes. The declarative vanilla-Gateway fixture
|
||||
also models repeated compaction status before terminal completion.
|
||||
|
||||
## 2026-08-31 — Complete, readable Android release notes
|
||||
|
||||
Android release metadata now keeps one overall title and summary plus a complete
|
||||
typed inventory of user-visible additions, improvements, and fixes. Stable
|
||||
change ids prevent duplicate records, selected highlights lead the expanded
|
||||
view, and compatibility boundaries remain visible without turning the compact
|
||||
notice into technical release documentation. Toast counts and previews are
|
||||
derived from the same non-highlighted changes the dialog and history render, so
|
||||
View all reaches every counted item. Older bundled changelog entries retain
|
||||
their existing rendering path.
|
||||
|
||||
The Android 1.14.0 record was migrated to the complete schema and reconciled
|
||||
against its released Android changelog: four highlights, two additional
|
||||
improvements, ten fixes, and three compatibility notes. The dialog, full
|
||||
history, large-text toast, seven Android resource catalogs, legacy text
|
||||
fallback, Play note, listing copy, release-prep instructions, and validation
|
||||
tests were updated together.
|
||||
|
||||
Structured release-note tests, focused Kotlin tests, Android locale and
|
||||
collection-API gates, rendered 360×640 dark-theme screenshots including 135%
|
||||
text, sideload APK assembly, Android lint, and diff checks passed.
|
||||
|
||||
## 2026-08-27 — Fixed issue ownership and bounded PR intake
|
||||
|
||||
The automated issue first-response lane now assigns only `Codename-11` when the
|
||||
|
||||
@@ -99,7 +99,7 @@ The wizard probes everything and finishes with a capability card:
|
||||
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
||||
| **API fallback** | Optional API route available/unavailable |
|
||||
| **Direct API** | Optional API-only compatibility route available/unavailable |
|
||||
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
@@ -140,7 +140,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
|
||||
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
|
||||
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. The API fallback is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -240,13 +240,13 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||
```
|
||||
|
||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
||||
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
|
||||
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
|
||||
install needs no plugin for either. The optional relay on `:8767` adds the power
|
||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
||||
|
||||
+30
-27
@@ -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
|
||||
|
||||
@@ -6,6 +6,31 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Restore the plugin manifest v2 declaration after the Hermes installer fix ships
|
||||
|
||||
Hermes installers in affected stable releases reject `manifest_version: 2`
|
||||
before the v2-capable runtime loader can inspect the plugin. Track upstream
|
||||
[PR #85893](https://github.com/NousResearch/hermes-agent/pull/85893). Restore
|
||||
`plugin/plugin.yaml` to `manifest_version: 2` only after that fix ships in a
|
||||
stable Hermes release that Hermes-Relay can treat as its minimum supported
|
||||
version. Until then, keep the v1 compatibility declaration and the additive
|
||||
metadata consumed by newer hosts.
|
||||
|
||||
---
|
||||
|
||||
## Consider hosted Android emulator execution
|
||||
|
||||
The local API 36 Gradle Managed Device lanes are intentionally on demand and
|
||||
individually selected. The current Android On-Demand workflow covers hosted
|
||||
source, unit, lint, and build verification only; it does not run emulators. If
|
||||
local emulator capacity becomes a recurring constraint, evaluate a separately
|
||||
approved hosted-emulator design with explicit cost, concurrency, artifact
|
||||
retention, and trigger policy. Do not schedule the full form-factor matrix or
|
||||
add a device farm until that policy is approved; keep live-server mutation tests
|
||||
outside any automatic matrix.
|
||||
|
||||
---
|
||||
|
||||
## Upstream a public Dashboard plugin WebSocket admission seam
|
||||
|
||||
The same-origin Relay ingress follows current upstream's bundled Dashboard
|
||||
|
||||
@@ -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)
|
||||
|
||||
+1
-1
@@ -6,7 +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.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
|
||||
+201
-7
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -292,9 +311,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(
|
||||
@@ -309,6 +325,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)
|
||||
@@ -333,6 +360,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"
|
||||
@@ -341,6 +503,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,6 +539,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)
|
||||
@@ -417,6 +602,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)
|
||||
}
|
||||
}
|
||||
@@ -428,7 +618,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 =
|
||||
@@ -446,7 +636,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)
|
||||
@@ -455,7 +645,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)
|
||||
@@ -465,6 +655,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() {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
|
||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Stable owner for an Auto chat before a conversation is opened.
|
||||
*
|
||||
* A legacy API-only record has no persisted Dashboard route; the conventional
|
||||
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
|
||||
* must not silently turn that compatibility record into a Gateway-owned chat.
|
||||
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
|
||||
* standard Chat belongs to Gateway even while that route is signed out or
|
||||
* temporarily unreachable.
|
||||
*/
|
||||
val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
if (preference == "auto") automaticChatTransport
|
||||
else SessionTransport.forEndpoint(preference)
|
||||
|
||||
@@ -124,7 +124,7 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback" -> "api"
|
||||
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "API fallback",
|
||||
label = "Direct API",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
|
||||
@@ -81,6 +81,24 @@ class SupervisedModeStore private constructor(
|
||||
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
|
||||
}
|
||||
|
||||
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
|
||||
internal suspend fun disableAllAndRemoveCredential(
|
||||
parentCredentialKey: Preferences.Key<String>,
|
||||
) {
|
||||
dataStore.edit { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt || decoded.policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
val disabled = decoded.policies.mapValues { (_, policy) ->
|
||||
policy.copy(enabled = false).normalized()
|
||||
}
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
|
||||
}
|
||||
preferences.remove(parentCredentialKey)
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodeResult {
|
||||
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
|
||||
return try {
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Availability of the app-specific parent credential. */
|
||||
enum class SupervisedParentAuthStatus {
|
||||
Missing,
|
||||
Configured,
|
||||
Corrupt,
|
||||
}
|
||||
|
||||
/** Input method selected for the app-specific parent credential. */
|
||||
@Serializable
|
||||
enum class SupervisedParentCredentialType {
|
||||
Legacy,
|
||||
Pin,
|
||||
Password,
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private enum class SupervisedRecoveryFormat {
|
||||
LegacyCode,
|
||||
WordPhrase,
|
||||
}
|
||||
|
||||
/** Result of a parent-secret or recovery-phrase verification attempt. */
|
||||
sealed interface SupervisedParentAuthResult {
|
||||
data object Success : SupervisedParentAuthResult
|
||||
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
|
||||
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
|
||||
data object Missing : SupervisedParentAuthResult
|
||||
data object Corrupt : SupervisedParentAuthResult
|
||||
}
|
||||
|
||||
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
|
||||
data class SupervisedParentEnrollment(val recoveryPhrase: String)
|
||||
|
||||
/** Validation result for a new parent PIN or password. */
|
||||
data class SupervisedParentSecretValidation(
|
||||
val valid: Boolean,
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
|
||||
interface SupervisedParentAuthenticator {
|
||||
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
|
||||
suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
|
||||
suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
}
|
||||
|
||||
/**
|
||||
* App-specific parent authentication for Supervised Mode.
|
||||
*
|
||||
* This store deliberately does not delegate to Android's device credential: a
|
||||
* child can legitimately own the PIN or biometrics on their Android profile.
|
||||
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
|
||||
* secret and recovery phrase are never persisted.
|
||||
*/
|
||||
class SupervisedParentAuthStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
private val iterations: Int,
|
||||
private val minimumAcceptedIterations: Int,
|
||||
private val random: SecureRandom,
|
||||
private val nowMillis: () -> Long,
|
||||
) : SupervisedParentAuthenticator {
|
||||
constructor(context: Context) : this(
|
||||
dataStore = context.applicationContext.relayDataStore,
|
||||
iterations = DEFAULT_PBKDF2_ITERATIONS,
|
||||
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
|
||||
random = SecureRandom(),
|
||||
nowMillis = System::currentTimeMillis,
|
||||
)
|
||||
|
||||
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
|
||||
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).status
|
||||
}
|
||||
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).record?.credentialType
|
||||
}
|
||||
|
||||
override suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
|
||||
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
|
||||
}
|
||||
runCatching { enrollLocked(newSecret, credentialType) }
|
||||
}
|
||||
|
||||
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
|
||||
verifyLocked(secret, AuthTarget.ParentSecret)
|
||||
}
|
||||
|
||||
override suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
val record = decode(dataStore.data.first()[KEY_RECORD]).record
|
||||
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
|
||||
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
|
||||
try {
|
||||
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
} finally {
|
||||
normalizedRecovery.fill('\u0000')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated escape hatch used by the parent controls.
|
||||
*
|
||||
* The app-global credential cannot be removed while leaving any supervised
|
||||
* policy enabled. Every policy is disabled, but its configuration is retained,
|
||||
* in the same transaction that removes the credential.
|
||||
*/
|
||||
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
|
||||
runCatching {
|
||||
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun enrollLocked(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentEnrollment {
|
||||
require(credentialType != SupervisedParentCredentialType.Legacy)
|
||||
val recoveryChars = generateRecoveryPhrase().toCharArray()
|
||||
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
var parentVerifier = ByteArray(0)
|
||||
var recoveryVerifier = ByteArray(0)
|
||||
try {
|
||||
parentVerifier = derive(secret, parentSalt, iterations)
|
||||
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
|
||||
val record = PersistedParentAuth(
|
||||
iterations = iterations,
|
||||
parentSalt = encode(parentSalt),
|
||||
parentVerifier = encode(parentVerifier),
|
||||
recoverySalt = encode(recoverySalt),
|
||||
recoveryVerifier = encode(recoveryVerifier),
|
||||
credentialType = credentialType,
|
||||
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
|
||||
)
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
return SupervisedParentEnrollment(recoveryChars.concatToString())
|
||||
} finally {
|
||||
recoveryChars.fill('\u0000')
|
||||
parentSalt.fill(0)
|
||||
recoverySalt.fill(0)
|
||||
parentVerifier.fill(0)
|
||||
recoveryVerifier.fill(0)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun verifyLocked(
|
||||
candidate: CharArray,
|
||||
target: AuthTarget,
|
||||
): SupervisedParentAuthResult {
|
||||
val decoded = decode(dataStore.data.first()[KEY_RECORD])
|
||||
val record = decoded.record ?: return when (decoded.status) {
|
||||
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
|
||||
else -> SupervisedParentAuthResult.Corrupt
|
||||
}
|
||||
val now = nowMillis()
|
||||
if (record.blockedUntilEpochMillis > now) {
|
||||
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
|
||||
}
|
||||
|
||||
val saltText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentSalt
|
||||
AuthTarget.RecoveryCode -> record.recoverySalt
|
||||
}
|
||||
val verifierText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentVerifier
|
||||
AuthTarget.RecoveryCode -> record.recoveryVerifier
|
||||
}
|
||||
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val actual = try {
|
||||
derive(candidate, salt, record.iterations)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to derive supervised parent verifier", error)
|
||||
return SupervisedParentAuthResult.Corrupt
|
||||
} finally {
|
||||
salt.fill(0)
|
||||
}
|
||||
val matches = try {
|
||||
MessageDigest.isEqual(expected, actual)
|
||||
} finally {
|
||||
expected.fill(0)
|
||||
actual.fill(0)
|
||||
}
|
||||
|
||||
if (matches) {
|
||||
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
|
||||
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
|
||||
}
|
||||
return SupervisedParentAuthResult.Success
|
||||
}
|
||||
|
||||
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
|
||||
val delayMillis = backoffMillis(failures)
|
||||
save(
|
||||
record.copy(
|
||||
failedAttempts = failures,
|
||||
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
|
||||
),
|
||||
)
|
||||
return if (delayMillis == 0L) {
|
||||
SupervisedParentAuthResult.Invalid(
|
||||
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
|
||||
)
|
||||
} else {
|
||||
SupervisedParentAuthResult.Throttled(delayMillis)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun save(record: PersistedParentAuth) {
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
}
|
||||
|
||||
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
|
||||
withContext(Dispatchers.Default) {
|
||||
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
|
||||
try {
|
||||
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodedRecord {
|
||||
if (raw.isNullOrBlank()) {
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
|
||||
}
|
||||
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
|
||||
.getOrElse {
|
||||
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
val valid = record.version == RECORD_VERSION &&
|
||||
record.algorithm == KDF_ALGORITHM &&
|
||||
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
|
||||
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
|
||||
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
|
||||
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
|
||||
record.blockedUntilEpochMillis >= 0
|
||||
return if (valid) {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
|
||||
} else {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateRecoveryPhrase(): String {
|
||||
val available = RECOVERY_WORDS.toMutableList()
|
||||
val selected = buildList(RECOVERY_WORD_COUNT) {
|
||||
repeat(RECOVERY_WORD_COUNT) {
|
||||
add(available.removeAt(random.nextInt(available.size)))
|
||||
}
|
||||
}
|
||||
return selected.joinToString("-")
|
||||
}
|
||||
|
||||
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
|
||||
private fun decodeBytes(value: String): ByteArray? =
|
||||
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
|
||||
|
||||
private fun backoffMillis(failures: Int): Long = when (failures) {
|
||||
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
|
||||
FAILURES_BEFORE_BACKOFF -> 30_000L
|
||||
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
|
||||
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
|
||||
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
|
||||
else -> MAX_BACKOFF_MILLIS
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedParentAuth(
|
||||
val version: Int = RECORD_VERSION,
|
||||
val algorithm: String = KDF_ALGORITHM,
|
||||
val iterations: Int,
|
||||
val parentSalt: String,
|
||||
val parentVerifier: String,
|
||||
val recoverySalt: String,
|
||||
val recoveryVerifier: String,
|
||||
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
|
||||
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
|
||||
val failedAttempts: Int = 0,
|
||||
val blockedUntilEpochMillis: Long = 0L,
|
||||
)
|
||||
|
||||
private data class DecodedRecord(
|
||||
val status: SupervisedParentAuthStatus,
|
||||
val record: PersistedParentAuth?,
|
||||
)
|
||||
|
||||
private enum class AuthTarget { ParentSecret, RecoveryCode }
|
||||
|
||||
class ParentAuthenticationException(
|
||||
val authResult: SupervisedParentAuthResult,
|
||||
) : IllegalStateException("Parent authentication failed: $authResult")
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SupervisedParentAuth"
|
||||
private const val RECORD_VERSION = 1
|
||||
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
|
||||
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
|
||||
private const val MIN_ACCEPTED_ITERATIONS = 100_000
|
||||
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
|
||||
private const val SALT_BYTES = 16
|
||||
private const val KEY_BITS = 256
|
||||
private const val FAILURES_BEFORE_BACKOFF = 5
|
||||
private const val MAX_TRACKED_FAILURES = 9
|
||||
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
|
||||
private const val RECOVERY_WORD_COUNT = 6
|
||||
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
|
||||
private val processMutex = Mutex()
|
||||
|
||||
fun validateNewSecret(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentSecretValidation {
|
||||
if (secret.size > 64) {
|
||||
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
|
||||
}
|
||||
if (credentialType == SupervisedParentCredentialType.Pin) {
|
||||
return if (secret.size == 6 && secret.all(Char::isDigit)) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
|
||||
}
|
||||
}
|
||||
return if (
|
||||
credentialType == SupervisedParentCredentialType.Password &&
|
||||
secret.size >= 8 && secret.any { !it.isWhitespace() }
|
||||
) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeRecoveryPhrase(
|
||||
value: CharArray,
|
||||
format: SupervisedRecoveryFormat,
|
||||
): CharArray = when (format) {
|
||||
SupervisedRecoveryFormat.LegacyCode -> value
|
||||
.filterNot { it == '-' || it.isWhitespace() }
|
||||
.joinToString("")
|
||||
.uppercase()
|
||||
.toCharArray()
|
||||
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
|
||||
.trim()
|
||||
.lowercase()
|
||||
.split(Regex("[-\\s]+"))
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("-")
|
||||
.toCharArray()
|
||||
}
|
||||
|
||||
private val RECOVERY_WORDS = listOf(
|
||||
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
|
||||
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
|
||||
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
|
||||
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
|
||||
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
|
||||
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
|
||||
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
|
||||
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
|
||||
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
|
||||
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
|
||||
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
|
||||
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
|
||||
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
|
||||
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
|
||||
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
|
||||
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
|
||||
)
|
||||
|
||||
internal fun forTesting(
|
||||
dataStore: DataStore<Preferences>,
|
||||
iterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
random: SecureRandom = SecureRandom(),
|
||||
nowMillis: () -> Long = System::currentTimeMillis,
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore(
|
||||
dataStore = dataStore,
|
||||
iterations = iterations,
|
||||
minimumAcceptedIterations = minimumAcceptedIterations,
|
||||
random = random,
|
||||
nowMillis = nowMillis,
|
||||
)
|
||||
|
||||
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.MoaReference
|
||||
import com.hermesandroid.relay.data.RealtimeTurnTrace
|
||||
import com.hermesandroid.relay.data.ToolCall
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import com.hermesandroid.relay.data.VoiceIntentTrace
|
||||
import com.hermesandroid.relay.network.shared.LocalDispatchResult
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
@@ -1499,11 +1500,13 @@ class ChatHandler {
|
||||
|
||||
// Run the media marker parser on assistant content; strip matched
|
||||
// lines and queue hits for post-assignment dispatch.
|
||||
val messageMediaHits = mutableListOf<Pair<String, MediaMarkerHit>>()
|
||||
val afterMedia = if (role == MessageRole.ASSISTANT && persistedImages.cleanedText.isNotEmpty()) {
|
||||
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, pendingMediaHits)
|
||||
extractMediaMarkersFromContent(messageId, persistedImages.cleanedText, messageMediaHits)
|
||||
} else {
|
||||
persistedImages.cleanedText
|
||||
}
|
||||
pendingMediaHits += messageMediaHits
|
||||
|
||||
// Cards are synchronous (no async fetch) so we attach them
|
||||
// straight onto the reconstructed ChatMessage and strip their
|
||||
@@ -1537,15 +1540,25 @@ class ChatHandler {
|
||||
val prior = priorById[messageId]
|
||||
// Outbound attachments: prefer an id-match (covers any future
|
||||
// user-message id reconciliation), else fall back to the
|
||||
// content-keyed queue. Inbound attachments are intentionally
|
||||
// excluded — they come back via the marker re-dispatch.
|
||||
// content-keyed queue. Inbound attachments normally come back via
|
||||
// marker re-dispatch. One narrow exception retains a completed
|
||||
// image_generate result when the immediate post-turn history read
|
||||
// still lacks its MEDIA marker; otherwise the rendered image
|
||||
// disappears during the persistence-lag window.
|
||||
val carriedAttachments = run {
|
||||
val persistedImagePaths = persistedImages.paths.toHashSet()
|
||||
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
|
||||
isImageGenerationToolName(tool.name) &&
|
||||
tool.isComplete && tool.success != false
|
||||
}
|
||||
val byId = prior?.attachments.orEmpty().filter { attachment ->
|
||||
attachment.relayToken == null ||
|
||||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
||||
(
|
||||
role == MessageRole.USER &&
|
||||
attachment.relayToken in persistedImagePaths
|
||||
role == MessageRole.ASSISTANT &&
|
||||
priorGeneratedImage &&
|
||||
attachment.isImage &&
|
||||
messageMediaHits.isEmpty()
|
||||
)
|
||||
}
|
||||
when {
|
||||
|
||||
@@ -2436,14 +2436,11 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
if (
|
||||
current is DashboardHttpException &&
|
||||
current.statusCode == 401 &&
|
||||
(
|
||||
current.message.orEmpty().contains("no_cookie", ignoreCase = true) ||
|
||||
current.message.orEmpty().contains("unauthenticated", ignoreCase = true)
|
||||
)
|
||||
) {
|
||||
// Every 401 from an authenticated Dashboard route means the saved
|
||||
// browser/native session can no longer authorize this request. Older
|
||||
// gateways used `no_cookie`/`unauthenticated`; current builds may return
|
||||
// reason codes such as `session_expired`, or no structured body at all.
|
||||
if (current is DashboardHttpException && current.statusCode == 401) {
|
||||
return true
|
||||
}
|
||||
current = current.cause
|
||||
|
||||
@@ -119,6 +119,8 @@ class GatewayChatClient(
|
||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
|
||||
/** Test seam — compaction idle lease. Production keeps [COMPACTING_TIMEOUT_MS]. */
|
||||
private val compactingTimeoutMs: Long = COMPACTING_TIMEOUT_MS,
|
||||
/** Random source for ordinary reconnect full-jitter. */
|
||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||
) : GatewayProfileEditorClient {
|
||||
@@ -159,6 +161,19 @@ class GatewayChatClient(
|
||||
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
||||
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_000L
|
||||
|
||||
/**
|
||||
* Server-side context compaction summarizes the transcript through a
|
||||
* (possibly slow) model with NO deltas or tool events flowing until it
|
||||
* finishes — near the context ceiling that silence routinely exceeds
|
||||
* [TURN_TIMEOUT_MS], so the idle watchdog would `session.interrupt` a
|
||||
* healthy compression, roll back its work, and retrigger on the next
|
||||
* prompt forever. A `status.update` event with kind `compacting`
|
||||
* (emitted at compaction start, and periodically by newer gateways)
|
||||
* arms this longer leash instead; any regular event rearms
|
||||
* [TURN_TIMEOUT_MS].
|
||||
*/
|
||||
private const val COMPACTING_TIMEOUT_MS = 600_000L
|
||||
|
||||
private const val RPC_TIMEOUT_MS = 15_000L
|
||||
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
||||
|
||||
@@ -263,7 +278,7 @@ class GatewayChatClient(
|
||||
.newBuilder()
|
||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
||||
// the WS upgrade. A failed connect drops chat to the SSE fallback and a
|
||||
// the WS upgrade. A failed connect leaves Android on its Gateway owner and a
|
||||
// 5s cooldown, so give the first remote handshake room.
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.pingInterval(30, TimeUnit.SECONDS)
|
||||
@@ -785,7 +800,7 @@ class GatewayChatClient(
|
||||
// Once this turn's own events are flowing (or it already
|
||||
// finished), the prompt provably reached the server — a
|
||||
// slow, lost, or socket-severed ack must NOT preflight-fail
|
||||
// into the SSE fallback, which would resubmit the same
|
||||
// into a second transport, which would resubmit the same
|
||||
// prompt as a duplicate turn. Recovery belongs to the
|
||||
// stream: the watchdog and mid-turn rejoin own it.
|
||||
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
||||
@@ -4307,10 +4322,12 @@ class GatewayChatClient(
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
||||
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
|
||||
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
|
||||
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
eventType == "status.update" &&
|
||||
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
|
||||
else -> turnIdleTimeoutMs
|
||||
}
|
||||
|
||||
@@ -4432,7 +4449,7 @@ class GatewayChatClient(
|
||||
// Reset on every event — long tool runs keep the turn alive.
|
||||
// Ask requests block with no further events, so they arm with
|
||||
// their own (longer) duration via watchdogTimeoutFor.
|
||||
armWatchdog(watchdogTimeoutFor(type))
|
||||
armWatchdog(watchdogTimeoutFor(type, payload))
|
||||
// Queue this immediately before the terminal callbacks. Both are
|
||||
// marshalled through the same dispatcher, preserving callback order
|
||||
// even when the WebSocket reader and reconnect coroutine differ.
|
||||
@@ -4823,7 +4840,7 @@ data class GatewayAttachment(
|
||||
val sizeBytes: Long? = null,
|
||||
)
|
||||
|
||||
/** Connect/auth/submit failed before the turn started — safe to fall back to SSE. */
|
||||
/** Connect/auth/submit failed before the turn started; the caller retains transport ownership. */
|
||||
internal class GatewayPreflightException(message: String) : Exception(message)
|
||||
|
||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||
|
||||
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
|
||||
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
||||
* delegates here with its live state.
|
||||
*
|
||||
* Manual picks pass through untouched (ChatViewModel handles per-turn
|
||||
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
|
||||
* gateway while the dashboard probe is unresolved or ready. A capability-
|
||||
* preferred SSE fallback is selected only after a definitive unavailable,
|
||||
* unsupported, or sign-in-required verdict.
|
||||
* Manual picks pass through untouched. "auto" follows the saved connection's
|
||||
* stable owner: Dashboard/Gateway for a standard connection, or the
|
||||
* capability-preferred SSE surface for a true API-only compatibility record.
|
||||
* Live reachability and sign-in state never change the owner of an open chat.
|
||||
*/
|
||||
fun resolveStreamingEndpointPreference(
|
||||
preference: String,
|
||||
gateway: GatewayAvailability,
|
||||
capabilities: ServerCapabilities,
|
||||
gatewayOwned: Boolean = true,
|
||||
): String = when (preference) {
|
||||
"sessions", "completions", "runs", "gateway" -> preference
|
||||
else -> if (
|
||||
gateway == GatewayAvailability.Ready ||
|
||||
gateway == GatewayAvailability.Unknown
|
||||
) {
|
||||
"gateway"
|
||||
} else {
|
||||
capabilities.preferredChatEndpoint()
|
||||
}
|
||||
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -209,6 +209,7 @@ internal class HermesRuntimeBinder(
|
||||
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
|
||||
connection.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
}
|
||||
chat.setDashboardSignInRequiredHandler(connection::probeNow)
|
||||
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
|
||||
chat.profileSessionDeleter = connection::deleteSession
|
||||
chat.profileSessionRenamer = connection::renameSession
|
||||
@@ -261,6 +262,11 @@ internal class HermesRuntimeBinder(
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.isStreaming.collect(connection::setChatStreaming)
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.conversationBinding.collect { binding ->
|
||||
connection.setActiveConversationTransport(binding.transport)
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.activeConnectionId,
|
||||
|
||||
@@ -136,6 +136,8 @@ import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.CandidateBuild
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
@@ -144,6 +146,7 @@ import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -282,6 +285,8 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
connection: Connection?,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
streamingEndpoint: String = "auto",
|
||||
conversationOwner: SessionTransport? = null,
|
||||
): ChatRuntimeStatus {
|
||||
val capabilities = connection?.capabilities
|
||||
val gateway = when {
|
||||
@@ -297,7 +302,11 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
||||
else -> ChatTransportReadiness.Unavailable
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
|
||||
val owner = when (conversationOwner ?: connection?.chatTransportForPreference(streamingEndpoint)) {
|
||||
SessionTransport.SSE -> ChatTransportPath.ApiSse
|
||||
else -> ChatTransportPath.Gateway
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api, owner = owner)
|
||||
}
|
||||
|
||||
internal fun shouldSettleStartupUnreachable(
|
||||
@@ -359,7 +368,7 @@ internal fun resolveFooterRouteCandidate(
|
||||
*
|
||||
* Endpoint roles are operator and wire metadata, so an internal role such as
|
||||
* `authenticated_dashboard` must never leak into this constrained surface.
|
||||
* Gateway labels describe how the Dashboard is reached; API fallback keeps
|
||||
* Gateway labels describe how the Dashboard is reached; Direct API keeps
|
||||
* the route's ordinary transport label.
|
||||
*/
|
||||
internal fun resolveFooterRouteLabel(
|
||||
@@ -738,6 +747,10 @@ fun RelayApp() {
|
||||
val pendingAddConnectionJobs = remember {
|
||||
mutableMapOf<String, kotlinx.coroutines.Job>()
|
||||
}
|
||||
var pendingAddConnectionTargetId by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val pendingAddConnectionAbortJobs = remember {
|
||||
mutableMapOf<String, kotlinx.coroutines.Job>()
|
||||
}
|
||||
val prepareAddConnection: (String, Boolean) -> Unit = { id, retryRequested ->
|
||||
val existingJob = pendingAddConnectionJobs[id]
|
||||
if (shouldStartPairPreparation(existingJob?.isActive == true, retryRequested)) {
|
||||
@@ -758,6 +771,25 @@ fun RelayApp() {
|
||||
job.start()
|
||||
}
|
||||
}
|
||||
val abortAddConnection: (String) -> kotlinx.coroutines.Job = { id ->
|
||||
pendingAddConnectionAbortJobs[id] ?: connectionSwitchScope.launch {
|
||||
try {
|
||||
pendingAddConnectionJobs.remove(id)?.cancelAndJoin()
|
||||
connectionViewModel.discardPlaceholderConnection(id)
|
||||
} finally {
|
||||
if (pendingAddConnectionTargetId == id) {
|
||||
pendingAddConnectionTargetId = null
|
||||
}
|
||||
}
|
||||
}.also { job ->
|
||||
pendingAddConnectionAbortJobs[id] = job
|
||||
job.invokeOnCompletion {
|
||||
if (pendingAddConnectionAbortJobs[id] === job) {
|
||||
pendingAddConnectionAbortJobs.remove(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One-time init: the terminal channel ViewModel registers with the shared
|
||||
// multiplexer and observes the relay connection state so it can attach/
|
||||
@@ -1351,6 +1383,9 @@ fun RelayApp() {
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
if (redirect) {
|
||||
pendingAddConnectionTargetId?.let { targetId ->
|
||||
abortAddConnection(targetId).join()
|
||||
}
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
@@ -1566,6 +1601,7 @@ fun RelayApp() {
|
||||
// evidence alone left a window where the reveal showed the CTA for
|
||||
// the few hundred ms until the client-based health verdict landed.
|
||||
val chatReady by connectionViewModel.chatReady.collectAsState()
|
||||
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
||||
var startupGateTimedOut by remember { mutableStateOf(false) }
|
||||
var startupGateReleased by remember { mutableStateOf(false) }
|
||||
@@ -1592,6 +1628,8 @@ fun RelayApp() {
|
||||
connection = activeConnection,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
apiHealth = apiHealth,
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
conversationOwner = conversationOwner,
|
||||
)
|
||||
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
||||
// connection. Startup readiness follows the same transport-neutral
|
||||
@@ -2098,7 +2136,9 @@ fun RelayApp() {
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||
streamingEndpoint,
|
||||
),
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
@@ -2113,10 +2153,20 @@ fun RelayApp() {
|
||||
?: AgentDisplay.displayModelName(serverModelName)
|
||||
?: stringResource(R.string.status_model_pending)
|
||||
val footerModelLabel = compactFooterModelLabel(modelLabel)
|
||||
val openConnections = {
|
||||
navController.navigate(Screen.ConnectionsSettings.route) {
|
||||
launchSingleTop = true
|
||||
val openConnections: (() -> Unit)? = if (
|
||||
isSupervisedRouteContentAllowed(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
currentRoute = Screen.ConnectionsSettings.route,
|
||||
)
|
||||
) {
|
||||
{
|
||||
navController.navigate(Screen.ConnectionsSettings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
RelayStatusStrip(
|
||||
leadingBadge = {
|
||||
@@ -2930,7 +2980,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.AdvancedSettings.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
AdvancedSettingsScreen(
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
@@ -2961,7 +3016,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.SupervisedControls.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SupervisedControlsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
@@ -3203,16 +3263,34 @@ fun RelayApp() {
|
||||
addConnectionEnabled = mayStartAddConnection(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
activeTargetId = pendingAddConnectionTargetId,
|
||||
),
|
||||
onAddConnection = {
|
||||
val id = java.util.UUID.randomUUID().toString()
|
||||
onAddConnection = addConnection@{
|
||||
val liveConnectionId = connectionViewModel.activeConnectionId.value
|
||||
val livePolicyState = supervisedPolicyState.value
|
||||
?.takeIf { (ownerId, _) -> ownerId == liveConnectionId }
|
||||
val livePolicy = when {
|
||||
liveConnectionId == null -> SupervisedModePolicy()
|
||||
livePolicyState != null -> livePolicyState.second
|
||||
else -> return@addConnection
|
||||
}
|
||||
val liveRoute = navController.currentDestination?.route
|
||||
val liveParentAccess = parentAccessUnlocked &&
|
||||
!shouldRelockParentAccess(
|
||||
supervisedEnabled = livePolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessUnlocked,
|
||||
route = liveRoute,
|
||||
)
|
||||
runAddConnectionAction(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
navigateToPair = {
|
||||
supervisedEnabled = livePolicy.enabled,
|
||||
parentAccessUnlocked = liveParentAccess,
|
||||
activeTargetId = pendingAddConnectionTargetId,
|
||||
allocateTarget = { java.util.UUID.randomUUID().toString() },
|
||||
recordTarget = { id -> pendingAddConnectionTargetId = id },
|
||||
navigateToPair = { id ->
|
||||
navController.navigate(Screen.Pair.route(connectionId = id))
|
||||
},
|
||||
prepareConnection = { prepareAddConnection(id, false) },
|
||||
prepareConnection = { id -> prepareAddConnection(id, false) },
|
||||
)
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
@@ -3356,9 +3434,15 @@ fun RelayApp() {
|
||||
if (connectionIdArg != null && pairDraftId == connectionIdArg) {
|
||||
connectionSwitchScope.launch {
|
||||
connectionViewModel.commitConnectionDraft(connectionIdArg)
|
||||
if (pendingAddConnectionTargetId == connectionIdArg) {
|
||||
pendingAddConnectionTargetId = null
|
||||
}
|
||||
navController.popBackStack()
|
||||
}
|
||||
} else {
|
||||
if (pendingAddConnectionTargetId == connectionIdArg) {
|
||||
pendingAddConnectionTargetId = null
|
||||
}
|
||||
navController.popBackStack()
|
||||
}
|
||||
},
|
||||
@@ -3378,6 +3462,9 @@ fun RelayApp() {
|
||||
runCatching {
|
||||
connectionViewModel.commitConnectionDraft(targetId)
|
||||
}.onSuccess {
|
||||
if (pendingAddConnectionTargetId == targetId) {
|
||||
pendingAddConnectionTargetId = null
|
||||
}
|
||||
android.util.Log.i(
|
||||
"GatewayPairFlow",
|
||||
"Opening Dashboard sign-in for staged gateway",
|
||||
@@ -3414,14 +3501,12 @@ fun RelayApp() {
|
||||
// never got a pairedAt stamp.
|
||||
if (connectionIdArg != null) {
|
||||
connectionSwitchScope.launch {
|
||||
// If Back wins the race with background
|
||||
// preparation, wait until the placeholder
|
||||
// exists before attempting to discard it.
|
||||
pendingAddConnectionJobs.remove(connectionIdArg)?.join()
|
||||
connectionViewModel.discardPlaceholderConnection(connectionIdArg)
|
||||
abortAddConnection(connectionIdArg).join()
|
||||
navController.popBackStack()
|
||||
}
|
||||
} else {
|
||||
navController.popBackStack()
|
||||
}
|
||||
navController.popBackStack()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -15,18 +15,24 @@ internal fun isSupervisedRouteAllowed(route: String?, parentAccessUnlocked: Bool
|
||||
internal fun mayStartAddConnection(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
): Boolean = !supervisedEnabled || parentAccessUnlocked
|
||||
activeTargetId: String? = null,
|
||||
): Boolean = activeTargetId == null && (!supervisedEnabled || parentAccessUnlocked)
|
||||
|
||||
internal inline fun runAddConnectionAction(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
navigateToPair: () -> Unit,
|
||||
prepareConnection: () -> Unit,
|
||||
): Boolean {
|
||||
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked)) return false
|
||||
navigateToPair()
|
||||
prepareConnection()
|
||||
return true
|
||||
activeTargetId: String?,
|
||||
allocateTarget: () -> String,
|
||||
recordTarget: (String) -> Unit,
|
||||
navigateToPair: (String) -> Unit,
|
||||
prepareConnection: (String) -> Unit,
|
||||
): String? {
|
||||
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked, activeTargetId)) return null
|
||||
val targetId = allocateTarget()
|
||||
recordTarget(targetId)
|
||||
navigateToPair(targetId)
|
||||
prepareConnection(targetId)
|
||||
return targetId
|
||||
}
|
||||
|
||||
/** Do not inspect or mutate a NavController until its first destination exists. */
|
||||
@@ -132,12 +138,10 @@ internal fun sanitizeSupervisedChatRouteArgs(
|
||||
}
|
||||
}
|
||||
|
||||
/** A disabled policy may become active only after an enrolled credential succeeds. */
|
||||
/** A disabled policy may become active only after the app-specific parent credential succeeds. */
|
||||
internal fun mayEnableSupervisedMode(
|
||||
policy: SupervisedModePolicy,
|
||||
deviceSecure: Boolean,
|
||||
deviceCredentialConfirmed: Boolean,
|
||||
parentCredentialConfirmed: Boolean,
|
||||
): Boolean = !policy.enabled &&
|
||||
policy.isConfigured &&
|
||||
deviceSecure &&
|
||||
deviceCredentialConfirmed
|
||||
parentCredentialConfirmed
|
||||
|
||||
+1
-1
@@ -613,7 +613,7 @@ private fun CapabilityRow(
|
||||
|
||||
/**
|
||||
* Advanced compatibility and override content:
|
||||
* - optional direct API fallback URL/key
|
||||
* - optional Direct API URL/key
|
||||
* - explicit direct Relay endpoint override/test
|
||||
* - allow-insecure-connections development toggle
|
||||
*
|
||||
|
||||
+20
-46
@@ -21,9 +21,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
|
||||
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
||||
Gateway("gateway", "⚡ Gateway"),
|
||||
Sessions("sessions", "📡 Sessions"),
|
||||
Completions("completions", "Completions"),
|
||||
Runs("runs", "Runs"),
|
||||
Sessions("sessions", "Direct API"),
|
||||
Completions("completions", "Direct API"),
|
||||
Runs("runs", "Direct API"),
|
||||
Offline("offline", "offline"),
|
||||
}
|
||||
|
||||
@@ -67,18 +67,6 @@ fun resolveChatTransportStatus(
|
||||
detail = "No reachable Hermes chat transport is available.",
|
||||
)
|
||||
|
||||
fun sseFallback(gatewayReason: String): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline(gatewayReason)
|
||||
val tier = preferredAvailableSseTier(serverCapabilities)
|
||||
?: return offline(gatewayReason)
|
||||
return ChatTransportStatus(
|
||||
tier = tier,
|
||||
tone = ChatTransportTone.Fallback,
|
||||
reason = "$gatewayReason → ${tier.plainName()}",
|
||||
detail = "${tier.detailText()} Using this as the fallback while Gateway is unavailable.",
|
||||
)
|
||||
}
|
||||
|
||||
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline()
|
||||
return if (supported) {
|
||||
@@ -94,23 +82,17 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
|
||||
return when (preference) {
|
||||
"auto" -> when {
|
||||
"auto", "gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "auto → Gateway (best)",
|
||||
reason = "Gateway connected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "Gateway selected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
else -> unavailable(
|
||||
ChatTransportTier.Gateway,
|
||||
gatewayFallbackReason(gatewayAvailability),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
||||
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
||||
@@ -119,42 +101,34 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
}
|
||||
|
||||
private fun preferredAvailableSseTier(capabilities: ServerCapabilities): ChatTransportTier? =
|
||||
when {
|
||||
capabilities.sessionsChatStream -> ChatTransportTier.Sessions
|
||||
capabilities.portable -> ChatTransportTier.Completions
|
||||
capabilities.runs -> ChatTransportTier.Runs
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
|
||||
when (availability) {
|
||||
GatewayAvailability.SignInRequired -> "gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "checking gateway"
|
||||
GatewayAvailability.Ready -> "gateway ready"
|
||||
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "Gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "Gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "Checking Gateway"
|
||||
GatewayAvailability.Ready -> "Gateway ready"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.plainName(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway -> "Gateway"
|
||||
ChatTransportTier.Sessions -> "Sessions"
|
||||
ChatTransportTier.Completions -> "Completions"
|
||||
ChatTransportTier.Runs -> "Runs"
|
||||
ChatTransportTier.Sessions -> "Direct API"
|
||||
ChatTransportTier.Completions -> "Direct API"
|
||||
ChatTransportTier.Runs -> "Direct API"
|
||||
ChatTransportTier.Offline -> "offline"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.detailText(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway ->
|
||||
"Gateway uses the dashboard WebSocket /api/ws for live thinking and rich tool events."
|
||||
"Hermes Chat uses the signed-in Dashboard connection."
|
||||
ChatTransportTier.Sessions ->
|
||||
"Sessions uses /api/sessions/{id}/chat/stream with server-side session history."
|
||||
"Direct API compatibility chat with server-side session history."
|
||||
ChatTransportTier.Completions ->
|
||||
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
|
||||
"Direct API compatibility chat."
|
||||
ChatTransportTier.Runs ->
|
||||
"Runs uses /v1/runs plus streamed run events."
|
||||
"Direct API compatibility chat with streamed run events."
|
||||
ChatTransportTier.Offline ->
|
||||
"No chat transport is reachable."
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ import java.net.URI
|
||||
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
||||
* the phone can open, probes public `/api/status`, and lets advertised
|
||||
* capabilities select authentication. A separate public sign-in URL is never
|
||||
* universally required. API fallback, Relay pairing, and extra LAN/Tailscale
|
||||
* universally required. Direct API, Relay pairing, and extra LAN/Tailscale
|
||||
* routes remain explicit advanced paths.
|
||||
*
|
||||
* Steps:
|
||||
|
||||
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
|
||||
val label = when (surface) {
|
||||
EndpointSurface.Standard,
|
||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||
EndpointSurface.Api -> "API fallback"
|
||||
EndpointSurface.Api -> "Direct API"
|
||||
EndpointSurface.Relay -> "Relay tools"
|
||||
}
|
||||
val securityVerdict = classifySurfaceSecurity(
|
||||
|
||||
+4
-4
@@ -57,6 +57,7 @@ import androidx.compose.ui.unit.IntSize
|
||||
import androidx.annotation.RequiresApi
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ToolCall
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import java.util.Locale
|
||||
@@ -65,7 +66,6 @@ import kotlin.math.cos
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.sin
|
||||
|
||||
private const val IMAGE_GENERATION_TOOL = "image_generate"
|
||||
private const val GRID_COLUMNS = 42
|
||||
private const val GRID_ROWS = 24
|
||||
private const val DEFAULT_ANIMATION_DURATION_MS = 4_800
|
||||
@@ -134,11 +134,11 @@ internal fun resolveImageGenerationVisualStyle(
|
||||
}
|
||||
|
||||
internal fun ToolCall.showsImageGenerationPlaceholder(): Boolean =
|
||||
!isComplete && name.trim().lowercase() == IMAGE_GENERATION_TOOL
|
||||
!isComplete && isImageGenerationToolName(name)
|
||||
|
||||
internal fun imageGenerationStartedAt(toolCalls: List<ToolCall>): Long? =
|
||||
toolCalls.lastOrNull {
|
||||
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
|
||||
isImageGenerationToolName(it.name)
|
||||
}?.startedAt
|
||||
|
||||
internal fun formatGenerationDuration(elapsedMillis: Long): String =
|
||||
@@ -155,7 +155,7 @@ internal fun shouldShowImageGenerationPlaceholder(
|
||||
hasMediaResult: Boolean,
|
||||
): Boolean {
|
||||
val imageCalls = toolCalls.filter {
|
||||
it.name.trim().lowercase() == IMAGE_GENERATION_TOOL
|
||||
isImageGenerationToolName(it.name)
|
||||
}
|
||||
if (imageCalls.any { !it.isComplete }) return true
|
||||
return !hasMediaResult &&
|
||||
|
||||
@@ -83,6 +83,7 @@ import com.hermesandroid.relay.data.HermesCardAction
|
||||
import com.hermesandroid.relay.data.MediaSettingsRepository
|
||||
import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import com.hermesandroid.relay.data.parseChatQuotedPrompt
|
||||
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
|
||||
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
|
||||
@@ -292,9 +293,7 @@ fun MessageBubble(
|
||||
append(streamingStatusLabel ?: visibleMessageContent.take(100))
|
||||
}
|
||||
val hasImageGenerationCall = remember(message.toolCalls) {
|
||||
message.toolCalls.any {
|
||||
it.name.trim().lowercase() == "image_generate"
|
||||
}
|
||||
message.toolCalls.any { isImageGenerationToolName(it.name) }
|
||||
}
|
||||
val imageGenerationStartMillis = remember(message.toolCalls) {
|
||||
imageGenerationStartedAt(message.toolCalls)
|
||||
|
||||
@@ -25,6 +25,8 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
@@ -41,7 +43,7 @@ fun RelayStatusStrip(
|
||||
/** Optional security marker rendered just before the route label. */
|
||||
securityGlyph: (@Composable () -> Unit)? = null,
|
||||
/**
|
||||
* When true, the strip shows an amber "Reconnecting…" cue in place of the
|
||||
* When true, the strip shows an amber "Relay reconnecting" cue in place of the
|
||||
* route label. This is where a **routine** in-progress relay reconnect
|
||||
* surfaces — the top chrome stays empty so chat content never shifts.
|
||||
*/
|
||||
@@ -108,7 +110,7 @@ fun RelayStatusStrip(
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber "· Reconnecting…" cue with a softly pulsing dot. This is the *only*
|
||||
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
|
||||
* surface for a routine in-progress relay reconnect — the top of the app stays
|
||||
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
|
||||
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
||||
@@ -132,7 +134,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
||||
.background(RelayRefresh.Amber),
|
||||
)
|
||||
Text(
|
||||
text = "Reconnecting…",
|
||||
text = stringResource(R.string.settings_relay_reconnecting),
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Amber,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -401,7 +401,7 @@ internal fun SessionPathDetails(
|
||||
* Vertical "transport path" ladder, basic → best:
|
||||
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
||||
* highlighted; tiers the server doesn't expose render muted; the resolver's
|
||||
* reason ("auto → Gateway (best)" / "gateway unavailable → Sessions") is shown
|
||||
* owner/readiness reason ("Gateway connected" / "Gateway unavailable") is shown
|
||||
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
|
||||
* the drawer and the badge can never disagree.
|
||||
*/
|
||||
|
||||
@@ -43,6 +43,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ToolCall
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
|
||||
|
||||
private val TOOL_ACTIVITY_PET_ROUTES = setOf("chat")
|
||||
@@ -101,7 +102,8 @@ internal fun ToolCall.requiresStandaloneToolSurface(): Boolean {
|
||||
!error.isNullOrBlank() ||
|
||||
outputRisk != null ||
|
||||
normalized in FILE_EDIT_TOOLS ||
|
||||
normalized in ATTENTION_TOOLS
|
||||
normalized in ATTENTION_TOOLS ||
|
||||
isImageGenerationToolName(name)
|
||||
}
|
||||
|
||||
internal data class ToolActivityCounts(
|
||||
|
||||
@@ -294,7 +294,55 @@ fun VersionNotesBlock(
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
val highlight = entry.highlight
|
||||
if (highlight == null) {
|
||||
if (entry.changes.isNotEmpty()) {
|
||||
if (showVersionLine) {
|
||||
Text(
|
||||
text = entry.versionLine(),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
entry.title?.takeIf { it.isNotBlank() }?.let { title ->
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
entry.summary?.takeIf { it.isNotBlank() }?.let { summary ->
|
||||
Text(
|
||||
text = summary,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
|
||||
val highlights = entry.highlightedChanges()
|
||||
if (highlights.isNotEmpty()) {
|
||||
ReleaseSectionTitle(stringResource(R.string.changelog_highlights))
|
||||
ReleaseChangeList(highlights)
|
||||
}
|
||||
|
||||
listOf(
|
||||
CHANGE_KIND_ADDED to R.string.changelog_added,
|
||||
CHANGE_KIND_IMPROVED to R.string.changelog_improved,
|
||||
CHANGE_KIND_FIXED to R.string.changelog_fixed,
|
||||
).forEach { (kind, label) ->
|
||||
val changes = entry.remainingChangesOfKind(kind)
|
||||
if (changes.isNotEmpty()) {
|
||||
ReleaseSectionTitle(stringResource(label))
|
||||
ReleaseChangeList(changes)
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.compatibility.isNotEmpty()) {
|
||||
ReleaseSectionTitle(stringResource(R.string.changelog_compatibility))
|
||||
VersionNotesBody(
|
||||
listOf(WhatsNewGroup(header = null, bullets = entry.compatibility)),
|
||||
)
|
||||
}
|
||||
} else if (highlight == null) {
|
||||
if (showVersionLine) {
|
||||
Text(
|
||||
text = entry.subtitle(),
|
||||
@@ -340,6 +388,47 @@ fun VersionNotesBlock(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ReleaseSectionTitle(title: String) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.ReleaseChangeList(changes: List<ChangelogChange>) {
|
||||
changes.forEach { change ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "•",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = change.title,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
change.summary?.takeIf { it.isNotBlank() }?.let { summary ->
|
||||
Text(
|
||||
text = summary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Structured changelog model + loader (kotlinx.serialization).
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -363,16 +452,37 @@ data class ChangelogHighlight(
|
||||
@Serializable
|
||||
data class ChangelogToastDigest(
|
||||
val additionalFeatureCount: Int = 0,
|
||||
val improvementCount: Int = 0,
|
||||
val fixCount: Int = 0,
|
||||
val preview: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
const val CHANGE_KIND_ADDED = "added"
|
||||
const val CHANGE_KIND_IMPROVED = "improved"
|
||||
const val CHANGE_KIND_FIXED = "fixed"
|
||||
|
||||
/** One complete, user-visible change in a release. */
|
||||
@Serializable
|
||||
data class ChangelogChange(
|
||||
val id: String,
|
||||
val kind: String,
|
||||
val title: String,
|
||||
val summary: String? = null,
|
||||
val highlight: Boolean = false,
|
||||
) {
|
||||
fun fallbackText(): String =
|
||||
summary?.takeIf { it.isNotBlank() }?.let { "$title — $it" } ?: title
|
||||
}
|
||||
|
||||
/** A single released version's user-facing notes. */
|
||||
@Serializable
|
||||
data class ChangelogVersion(
|
||||
val version: String,
|
||||
val title: String? = null,
|
||||
val date: String? = null,
|
||||
val summary: String? = null,
|
||||
val changes: List<ChangelogChange> = emptyList(),
|
||||
val compatibility: List<String> = emptyList(),
|
||||
val highlight: ChangelogHighlight? = null,
|
||||
val improvements: List<String> = emptyList(),
|
||||
val toastDigest: ChangelogToastDigest? = null,
|
||||
@@ -393,8 +503,48 @@ data class ChangelogVersion(
|
||||
return "v$version$datePart"
|
||||
}
|
||||
|
||||
fun highlightedChanges(): List<ChangelogChange> = changes.filter { it.highlight }
|
||||
|
||||
fun remainingChanges(): List<ChangelogChange> = changes.filterNot { it.highlight }
|
||||
|
||||
fun remainingChangesOfKind(kind: String): List<ChangelogChange> =
|
||||
remainingChanges().filter { it.kind == kind }
|
||||
|
||||
/** Derive compact toast metadata from the same changes the expanded view renders. */
|
||||
fun resolvedToastDigest(): ChangelogToastDigest? {
|
||||
if (changes.isEmpty()) return toastDigest
|
||||
val remaining = remainingChanges()
|
||||
if (remaining.isEmpty()) return null
|
||||
return ChangelogToastDigest(
|
||||
additionalFeatureCount = remaining.count { it.kind == CHANGE_KIND_ADDED },
|
||||
improvementCount = remaining.count { it.kind == CHANGE_KIND_IMPROVED },
|
||||
fixCount = remaining.count { it.kind == CHANGE_KIND_FIXED },
|
||||
preview = remaining.take(2).map { it.title },
|
||||
)
|
||||
}
|
||||
|
||||
fun toGroups(): List<WhatsNewGroup> =
|
||||
highlight?.let { curated ->
|
||||
if (changes.isNotEmpty()) {
|
||||
buildList {
|
||||
val highlights = highlightedChanges()
|
||||
if (highlights.isNotEmpty()) {
|
||||
add(WhatsNewGroup("Highlights", highlights.map { it.fallbackText() }))
|
||||
}
|
||||
listOf(
|
||||
CHANGE_KIND_ADDED to "Added",
|
||||
CHANGE_KIND_IMPROVED to "Improved",
|
||||
CHANGE_KIND_FIXED to "Fixed",
|
||||
).forEach { (kind, label) ->
|
||||
val items = remainingChangesOfKind(kind)
|
||||
if (items.isNotEmpty()) {
|
||||
add(WhatsNewGroup(label, items.map { it.fallbackText() }))
|
||||
}
|
||||
}
|
||||
if (compatibility.isNotEmpty()) {
|
||||
add(WhatsNewGroup("Compatibility", compatibility))
|
||||
}
|
||||
}
|
||||
} else highlight?.let { curated ->
|
||||
buildList {
|
||||
add(WhatsNewGroup(curated.title.takeIf { it.isNotBlank() }, curated.bullets))
|
||||
if (improvements.isNotEmpty()) {
|
||||
|
||||
@@ -185,6 +185,10 @@ internal fun WhatsNewToastContent(
|
||||
) {
|
||||
val title = stringResource(R.string.whats_new_title)
|
||||
val highlight = entry.highlight
|
||||
val digest = entry.resolvedToastDigest()
|
||||
val releaseTitle = entry.title?.takeIf(String::isNotBlank) ?: highlight?.title.orEmpty()
|
||||
val releaseSummary = entry.summary?.takeIf(String::isNotBlank)
|
||||
?: highlight?.summary?.takeIf(String::isNotBlank)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
@@ -220,14 +224,14 @@ internal fun WhatsNewToastContent(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = highlight?.title ?: entry.title.orEmpty(),
|
||||
text = releaseTitle,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
maxLines = 1,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
highlight?.summary?.takeIf(String::isNotBlank)?.let { summary ->
|
||||
releaseSummary?.let { summary ->
|
||||
Text(
|
||||
text = summary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -251,9 +255,9 @@ internal fun WhatsNewToastContent(
|
||||
)
|
||||
}
|
||||
}
|
||||
entry.toastDigest?.takeIf {
|
||||
it.additionalFeatureCount > 0 || it.fixCount > 0
|
||||
}?.let { digest ->
|
||||
digest?.takeIf {
|
||||
it.additionalFeatureCount > 0 || it.improvementCount > 0 || it.fixCount > 0
|
||||
}?.let { resolvedDigest ->
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.32f),
|
||||
@@ -272,21 +276,30 @@ internal fun WhatsNewToastContent(
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
val counts = buildList {
|
||||
if (digest.additionalFeatureCount > 0) {
|
||||
if (resolvedDigest.additionalFeatureCount > 0) {
|
||||
add(
|
||||
pluralStringResource(
|
||||
R.plurals.changelog_additional_feature_count,
|
||||
digest.additionalFeatureCount,
|
||||
digest.additionalFeatureCount,
|
||||
resolvedDigest.additionalFeatureCount,
|
||||
resolvedDigest.additionalFeatureCount,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (digest.fixCount > 0) {
|
||||
if (resolvedDigest.improvementCount > 0) {
|
||||
add(
|
||||
pluralStringResource(
|
||||
R.plurals.changelog_improvement_count,
|
||||
resolvedDigest.improvementCount,
|
||||
resolvedDigest.improvementCount,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (resolvedDigest.fixCount > 0) {
|
||||
add(
|
||||
pluralStringResource(
|
||||
R.plurals.changelog_fix_count,
|
||||
digest.fixCount,
|
||||
digest.fixCount,
|
||||
resolvedDigest.fixCount,
|
||||
resolvedDigest.fixCount,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -298,11 +311,11 @@ internal fun WhatsNewToastContent(
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = digest.preview.joinToString(", ") + "…",
|
||||
text = resolvedDigest.preview.joinToString(", ") + "…",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -265,6 +265,7 @@ import com.hermesandroid.relay.ui.components.ToolTranscriptItem
|
||||
import com.hermesandroid.relay.ui.components.groupTranscriptTools
|
||||
import com.hermesandroid.relay.ui.components.isVisibleForToolDisplay
|
||||
import com.hermesandroid.relay.ui.components.showsImageGenerationPlaceholder
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import com.hermesandroid.relay.ui.components.VoiceModeOverlay
|
||||
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
||||
import com.hermesandroid.relay.ui.showHumanError
|
||||
@@ -1228,7 +1229,7 @@ fun ChatScreen(
|
||||
buildMap {
|
||||
messages.forEach { message ->
|
||||
val generationCount = message.toolCalls.count {
|
||||
it.name.trim().equals("image_generate", ignoreCase = true)
|
||||
isImageGenerationToolName(it.name)
|
||||
}
|
||||
if (generationCount > 0) {
|
||||
put(message.uiKey, nextOrdinal + generationCount - 1)
|
||||
|
||||
@@ -778,7 +778,7 @@ fun ChatSettingsScreen(
|
||||
serverCaps,
|
||||
) {
|
||||
resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = resolvedStreamingEndpoint,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCaps,
|
||||
)
|
||||
|
||||
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
@@ -83,6 +84,7 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -476,12 +478,16 @@ private fun ActiveOverview(
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
)
|
||||
val currentRouteUrl = if (usingApiFallback) {
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
// Observe the binding as well as the saved preference so a restored
|
||||
// conversation immediately presents its actual owner.
|
||||
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
val usingDirectApi = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport,
|
||||
connection = connection,
|
||||
preference = streamingEndpoint,
|
||||
) == SessionTransport.SSE
|
||||
val currentRouteUrl = if (usingDirectApi) {
|
||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||
} else {
|
||||
effectiveDashboardUrl
|
||||
@@ -492,23 +498,29 @@ private fun ActiveOverview(
|
||||
effectiveDashboardUrl = currentRouteUrl,
|
||||
)
|
||||
val routeStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
||||
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
|
||||
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
||||
}
|
||||
val chatStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unreachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
usingDirectApi && !apiReachable && apiHealth != ConnectionViewModel.HealthStatus.Probing ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
|
||||
+22
-7
@@ -62,6 +62,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.data.isDashboardOnlyRoute
|
||||
@@ -386,6 +387,12 @@ private fun ConnectionListCard(
|
||||
} else {
|
||||
connection.resolvedDashboardUrl
|
||||
}
|
||||
val selectedProfile: Profile? = if (activeConnectionViewModel != null) {
|
||||
val profile by activeConnectionViewModel.selectedProfile.collectAsState()
|
||||
profile
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val presentedConnection = activeConnection ?: connection
|
||||
val presentation = resolveGatewayCardPresentation(
|
||||
connection = presentedConnection,
|
||||
@@ -429,13 +436,7 @@ private fun ConnectionListCard(
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(
|
||||
if (presentation.status == GatewayCardStatus.Online) {
|
||||
com.hermesandroid.relay.ui.theme.RelayRefresh.Green
|
||||
} else {
|
||||
MaterialTheme.colorScheme.outline
|
||||
},
|
||||
),
|
||||
.background(gatewayStatusColor(presentation.status)),
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Dns,
|
||||
@@ -484,6 +485,20 @@ private fun ConnectionListCard(
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (isActive) {
|
||||
Text(
|
||||
text = listOfNotNull(
|
||||
stringResource(R.string.conn_info_profile),
|
||||
selectedProfile?.name?.takeIf { it.isNotBlank() }
|
||||
?: stringResource(R.string.settings_server_default),
|
||||
selectedProfile?.model?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onSwitch != null || isSwitching || justSwitched) {
|
||||
OutlinedButton(
|
||||
|
||||
+863
@@ -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 }
|
||||
+240
-54
@@ -1,8 +1,5 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -52,7 +49,9 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -65,6 +64,9 @@ import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStatus
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStore
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.data.SupervisedSessionActions
|
||||
import com.hermesandroid.relay.data.SupervisedVisibilityPreset
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
|
||||
@@ -77,6 +79,7 @@ import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.gradientBorder
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* The settings surface available while supervised mode is locked.
|
||||
@@ -100,28 +103,29 @@ fun SupervisedSettingsScreen(
|
||||
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
|
||||
val profileAlias by connectionViewModel.profileDisplayAlias.collectAsState()
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
var authError by remember { mutableStateOf<String?>(null) }
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var showAbout by remember { mutableStateOf(false) }
|
||||
|
||||
val credentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
}
|
||||
}
|
||||
|
||||
fun requestParentAccess() {
|
||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val intent = keyguard?.createConfirmDeviceCredentialIntent(
|
||||
"Parent access",
|
||||
"Unlock full Hermes settings and supervised-mode controls. Device credentials verify an enrolled device user, not a distinct parent identity.",
|
||||
)
|
||||
if (intent == null) {
|
||||
authError = "Set a device screen lock before using parent access."
|
||||
} else {
|
||||
credentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
authError = "This legacy supervised policy has no app-specific parent credential and stays locked. " +
|
||||
"Reset this app's local data, reconnect, and configure parent access before enabling Supervised Mode again."
|
||||
}
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
authError = "Parent access data is unavailable. Supervised Mode remains locked."
|
||||
}
|
||||
null -> authError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +190,7 @@ fun SupervisedSettingsScreen(
|
||||
SupervisedNavigationRow(
|
||||
icon = Icons.Filled.Lock,
|
||||
title = "Parent access",
|
||||
subtitle = "Unlock full settings with the device screen lock",
|
||||
subtitle = "Unlock full settings with the app parent PIN or password",
|
||||
onClick = ::requestParentAccess,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
@@ -217,6 +221,38 @@ fun SupervisedSettingsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
else -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Restricted appearance editor backed by the supervised policy, not global theme settings. */
|
||||
@@ -293,42 +329,41 @@ fun SupervisedControlsScreen(
|
||||
onReturnToSupervisedView: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val keyguardManager = remember(context) {
|
||||
context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
val deviceSecure = keyguardManager?.isDeviceSecure == true
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
var showProfilePicker by remember { mutableStateOf(false) }
|
||||
var sessionActionsExpanded by remember { mutableStateOf(false) }
|
||||
var enableAuthError by remember { mutableStateOf<String?>(null) }
|
||||
var enableRequested by remember { mutableStateOf(false) }
|
||||
val enableCredentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
val shouldEnable = enableRequested && mayEnableSupervisedMode(
|
||||
policy = policy,
|
||||
deviceSecure = deviceSecure,
|
||||
deviceCredentialConfirmed = result.resultCode == Activity.RESULT_OK,
|
||||
)
|
||||
enableRequested = false
|
||||
if (shouldEnable) {
|
||||
enableAuthError = null
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
}
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var enableAfterEnrollment by remember { mutableStateOf(false) }
|
||||
var showRemoveCredentialConfirm by remember { mutableStateOf(false) }
|
||||
var removeCredentialBusy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun requestFirstEnable() {
|
||||
val intent = keyguardManager?.createConfirmDeviceCredentialIntent(
|
||||
"Enable supervised mode",
|
||||
"Confirm with an enrolled device credential. This does not verify a distinct parent identity.",
|
||||
)
|
||||
if (!deviceSecure || intent == null) {
|
||||
enableAuthError = "Set a secure device screen lock before enabling supervised mode."
|
||||
if (!policy.isConfigured) {
|
||||
enableAuthError = "Choose an agent profile before enabling Supervised Mode."
|
||||
return
|
||||
}
|
||||
enableRequested = true
|
||||
enableCredentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
enableAfterEnrollment = true
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
}
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
enableAuthError = "Parent access data is unavailable. Reset local app data before enabling Supervised Mode."
|
||||
}
|
||||
null -> enableAuthError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
@@ -360,14 +395,18 @@ fun SupervisedControlsScreen(
|
||||
subtitle = when {
|
||||
policy.pinnedProfileName.isNullOrBlank() ->
|
||||
"Choose an agent profile before enabling"
|
||||
!deviceSecure ->
|
||||
"Set a device screen lock before enabling"
|
||||
parentAuthStatus == SupervisedParentAuthStatus.Missing ->
|
||||
"Set an app-specific parent PIN or password"
|
||||
else ->
|
||||
"Show only the approved Android chat surfaces"
|
||||
},
|
||||
checked = policy.enabled,
|
||||
enabled = policy.enabled ||
|
||||
(!policy.pinnedProfileName.isNullOrBlank() && deviceSecure),
|
||||
(!policy.pinnedProfileName.isNullOrBlank() &&
|
||||
parentAuthStatus in setOf(
|
||||
SupervisedParentAuthStatus.Missing,
|
||||
SupervisedParentAuthStatus.Configured,
|
||||
)),
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled) requestFirstEnable()
|
||||
else onPolicyChange(policy.copy(enabled = false))
|
||||
@@ -404,7 +443,7 @@ fun SupervisedControlsScreen(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"Android device credentials authenticate an enrolled device user; they do not establish a separate parent identity. Use a parent-only device credential or managed-device policy where that distinction matters.",
|
||||
"Parent access uses an app-specific PIN or password, separate from the supervised user's Android screen lock and biometrics.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -713,14 +752,42 @@ fun SupervisedControlsScreen(
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Column(Modifier.padding(start = 12.dp)) {
|
||||
Text("Device authentication", style = MaterialTheme.typography.titleSmall)
|
||||
Text("App parent credential", style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
"Full features require the device screen lock. This verifies an enrolled device user, not a distinct parent identity.",
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> "A parent PIN or password is configured for this app."
|
||||
SupervisedParentAuthStatus.Missing -> "Set a parent PIN or password before enabling Supervised Mode."
|
||||
SupervisedParentAuthStatus.Corrupt -> "Parent access data is unavailable and fails closed."
|
||||
null -> "Loading parent access…"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> OutlinedButton(
|
||||
onClick = {
|
||||
enableAfterEnrollment = false
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
},
|
||||
) { Text("Set parent PIN or password") }
|
||||
SupervisedParentAuthStatus.Configured -> {
|
||||
OutlinedButton(onClick = { parentAuthDialog = ParentAuthDialog.Change }) {
|
||||
Text("Change parent PIN or password")
|
||||
}
|
||||
TextButton(onClick = { parentAuthDialog = ParentAuthDialog.Recovery }) {
|
||||
Text("Reset with recovery phrase")
|
||||
}
|
||||
TextButton(onClick = { showRemoveCredentialConfirm = true }) {
|
||||
Text(
|
||||
"Remove parent credential",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
HorizontalDivider()
|
||||
SupervisedSwitchRow(
|
||||
title = "Relock when the app leaves the screen",
|
||||
@@ -794,6 +861,118 @@ fun SupervisedControlsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showRemoveCredentialConfirm) {
|
||||
RemoveParentCredentialDialog(
|
||||
busy = removeCredentialBusy,
|
||||
onDismiss = { showRemoveCredentialConfirm = false },
|
||||
onConfirm = {
|
||||
removeCredentialBusy = true
|
||||
scope.launch {
|
||||
val result = parentAuthStore.clearCredentialAndDisablePolicies()
|
||||
removeCredentialBusy = false
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
showRemoveCredentialConfirm = false
|
||||
enableAuthError = null
|
||||
onBack()
|
||||
},
|
||||
onFailure = {
|
||||
enableAuthError = "Parent access could not be removed. Try again."
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
enableAuthError = null
|
||||
if (mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Setup -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = false,
|
||||
onDismiss = {
|
||||
parentAuthDialog = null
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Change -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = true,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
null -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
enableAuthError = null
|
||||
if (enableAfterEnrollment && mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun RemoveParentCredentialDialog(
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
title = { Text("Remove parent credential?") },
|
||||
text = {
|
||||
Text(
|
||||
"This disables Supervised Mode on every connection and removes the app-wide " +
|
||||
"PIN or password and recovery phrase. Your supervised settings and toggles are kept. " +
|
||||
"Hermes sessions and server history are not deleted.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = !busy, onClick = onConfirm) {
|
||||
Text(
|
||||
if (busy) "Removing…" else "Remove",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(enabled = !busy, onClick = onDismiss) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -984,6 +1163,13 @@ private fun sessionActionsSummary(actions: SupervisedSessionActions): String = w
|
||||
else -> "${actions.enabledCount} of ${SupervisedSessionActions.TOTAL} allowed"
|
||||
}
|
||||
|
||||
private enum class ParentAuthDialog {
|
||||
Verify,
|
||||
Setup,
|
||||
Change,
|
||||
Recovery,
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SessionActionSwitch(
|
||||
title: String,
|
||||
|
||||
@@ -28,25 +28,26 @@ sealed interface ChatRuntimeStatus {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve chat health in product priority order:
|
||||
* Gateway primary, API/SSE fallback, pending connection, then unavailable.
|
||||
* Resolve chat health for the active conversation owner only. A reachable
|
||||
* sibling endpoint cannot make a signed-out or unreachable conversation look
|
||||
* connected.
|
||||
*/
|
||||
fun resolveChatRuntimeStatus(
|
||||
gateway: ChatTransportReadiness,
|
||||
apiSse: ChatTransportReadiness,
|
||||
): ChatRuntimeStatus = when {
|
||||
gateway == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.Gateway,
|
||||
fallback = false,
|
||||
)
|
||||
|
||||
apiSse == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.ApiSse,
|
||||
fallback = true,
|
||||
)
|
||||
|
||||
gateway == ChatTransportReadiness.Connecting ||
|
||||
apiSse == ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
|
||||
else -> ChatRuntimeStatus.Unavailable
|
||||
owner: ChatTransportPath = ChatTransportPath.Gateway,
|
||||
): ChatRuntimeStatus {
|
||||
val readiness = when (owner) {
|
||||
ChatTransportPath.Gateway -> gateway
|
||||
ChatTransportPath.ApiSse -> apiSse
|
||||
}
|
||||
return when (readiness) {
|
||||
ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = owner,
|
||||
fallback = false,
|
||||
)
|
||||
ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
ChatTransportReadiness.NotConfigured,
|
||||
ChatTransportReadiness.Unavailable -> ChatRuntimeStatus.Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,7 @@ import com.hermesandroid.relay.notifications.InteractionRequestNotifier
|
||||
import com.hermesandroid.relay.reliability.ReliabilityCenter
|
||||
import com.hermesandroid.relay.reliability.SessionResetEvidence
|
||||
import com.hermesandroid.relay.ui.components.ServerImageResult
|
||||
import com.hermesandroid.relay.data.isImageGenerationToolName
|
||||
import com.hermesandroid.relay.ui.components.SlashCommand
|
||||
import com.hermesandroid.relay.voice.RealtimeTurnSyncBuilder
|
||||
import com.hermesandroid.relay.voice.VoiceIntentSyncBuilder
|
||||
@@ -290,7 +291,7 @@ internal data class ResolvedGatewayActiveSessions(
|
||||
val ambiguousForCurrent: Boolean,
|
||||
)
|
||||
|
||||
/** Resolve process-wide runtime rows without ever inventing a profile owner. */
|
||||
/** Resolve process-wide runtime rows without ever inventing an ambiguous profile owner. */
|
||||
internal fun resolveGatewayActiveSessions(
|
||||
sessions: List<GatewayActiveSession>,
|
||||
directory: Set<SessionActivityOwner>,
|
||||
@@ -315,6 +316,8 @@ internal fun resolveGatewayActiveSessions(
|
||||
currentRuntimeId == row.runtimeSessionId &&
|
||||
currentOwner.storedSessionId == row.storedSessionId -> currentOwner
|
||||
explicitProfile != null && candidates.size == 1 -> candidates.single()
|
||||
explicitProfile == null && currentOwner != null && candidates.singleOrNull() == currentOwner ->
|
||||
currentOwner
|
||||
else -> null
|
||||
}
|
||||
if (owner == null) {
|
||||
@@ -2120,9 +2123,12 @@ class ChatViewModel : ViewModel() {
|
||||
* RelayApp pushes the resolved value) prefers an EventSource-compatible
|
||||
* OpenAI chat path instead of assuming `/v1/runs` is an SSE stream.
|
||||
*/
|
||||
private var resolvedStreamingEndpoint: String = "completions"
|
||||
|
||||
var streamingEndpoint: String = "completions"
|
||||
set(value) {
|
||||
field = value
|
||||
resolvedStreamingEndpoint = value
|
||||
field = endpointForConversationOwner(value)
|
||||
// Only the gateway transport auto-names sessions server-side
|
||||
// (tui_gateway runs the turn in a HermesCLI child that calls
|
||||
// agent.title_generator.maybe_auto_title). The api_server SSE/runs/
|
||||
@@ -2137,12 +2143,19 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE endpoint used when a "gateway" turn can't run (gateway unreachable,
|
||||
* sign-in expired, attachments present). Wired from RelayApp alongside
|
||||
* [streamingEndpoint] as the capability-resolved SSE preference; never
|
||||
* "auto" or "gateway".
|
||||
* Capability-resolved endpoint for an explicitly API-owned compatibility
|
||||
* conversation. It never acts as a fallback for a Gateway-owned chat.
|
||||
*/
|
||||
var sseFallbackEndpoint: String = "completions"
|
||||
set(value) {
|
||||
field = value
|
||||
if (
|
||||
conversationBinding.value.transport == SessionTransport.SSE &&
|
||||
resolvedStreamingEndpoint == "gateway"
|
||||
) {
|
||||
streamingEndpoint = resolvedStreamingEndpoint
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway chat transport (dashboard `/api/ws` — live thinking). Owned and
|
||||
@@ -3183,6 +3196,7 @@ class ChatViewModel : ViewModel() {
|
||||
) {
|
||||
val handler = chatHandler ?: return
|
||||
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) return
|
||||
val contextKey = activeProfileContextKey
|
||||
gatewayHistoryReconcileJob?.cancel()
|
||||
gatewayHistoryReconcileJob = viewModelScope.launch {
|
||||
val expected = expectedAssistantText?.trim()?.takeIf { it.isNotEmpty() }
|
||||
@@ -3215,7 +3229,28 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
val transcriptSnapshot = handler.messages.value
|
||||
val serverMessages = loadGatewaySessionHistory(storedSessionId)
|
||||
val serverMessages = try {
|
||||
loadGatewaySessionHistory(
|
||||
sessionId = storedSessionId,
|
||||
requireProfileScope = true,
|
||||
)
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// A live completion is already visible and settled locally.
|
||||
// History auth loss must retain that transcript and promote
|
||||
// the existing sign-in recovery instead of escaping this
|
||||
// Main-scope coroutine and crashing the app.
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == contextKey &&
|
||||
handler.currentSessionId.value == storedSessionId
|
||||
) {
|
||||
publishHistoryLoadFailure(storedSessionId, e)
|
||||
}
|
||||
gatewayHistoryReconcileJob = null
|
||||
return@launch
|
||||
}
|
||||
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) {
|
||||
return@launch
|
||||
}
|
||||
@@ -3727,6 +3762,17 @@ class ChatViewModel : ViewModel() {
|
||||
private val bindingDisplayProfile: Profile?
|
||||
get() = conversationBinding.value.displayProfile
|
||||
|
||||
private fun endpointForConversationOwner(candidate: String): String =
|
||||
when (conversationBinding.value.transport) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> if (candidate == "gateway") sseFallbackEndpoint else candidate
|
||||
null -> candidate
|
||||
}
|
||||
|
||||
private fun reapplyConversationTransportAffinity() {
|
||||
streamingEndpoint = resolvedStreamingEndpoint
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile namespace owned by the conversation currently on screen. Opening a
|
||||
* row from the global All Profiles browser binds this state first; the UI
|
||||
@@ -3739,6 +3785,7 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
private fun clearOpenedSessionOwner() {
|
||||
conversationBindingController.releaseExplicitOwner()
|
||||
reapplyConversationTransportAffinity()
|
||||
}
|
||||
|
||||
/** Process ownership is profile+session scoped; stored IDs alone are not globally unique. */
|
||||
@@ -3848,6 +3895,12 @@ class ChatViewModel : ViewModel() {
|
||||
profileSessionPageLister = lister
|
||||
}
|
||||
|
||||
private var dashboardSignInRequiredHandler: (() -> Unit)? = null
|
||||
|
||||
fun setDashboardSignInRequiredHandler(handler: () -> Unit) {
|
||||
dashboardSignInRequiredHandler = handler
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a session scoped to the active profile on gateway connections
|
||||
* (dashboard `DELETE /api/sessions/{id}?profile=`). The write twin of
|
||||
@@ -4236,7 +4289,19 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
private fun publishHistoryLoadFailure(sessionId: String, error: Throwable) {
|
||||
if (error.isDashboardSignInRequiredFailure()) return
|
||||
if (error.isDashboardSignInRequiredFailure()) {
|
||||
dashboardSignInRequiredHandler?.invoke()
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Auth,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = "Dashboard sign-in required for chat history",
|
||||
detail = "stored_session=$sessionId; dashboard_auth=required",
|
||||
operation = "load chat history",
|
||||
endpointRole = "gateway",
|
||||
suggestion = "Sign in to Dashboard on the active route, then retry this conversation.",
|
||||
)
|
||||
return
|
||||
}
|
||||
val rawError = error.message?.takeIf { it.isNotBlank() }
|
||||
?: "The active profile's conversation history could not be reached."
|
||||
_chatFailure.value = ChatFailureNotice(
|
||||
@@ -4637,6 +4702,7 @@ class ChatViewModel : ViewModel() {
|
||||
lastSessionRefreshSuccessNanos = 0L
|
||||
_sessionListUnavailable.value = false
|
||||
conversationBindingController.reset()
|
||||
reapplyConversationTransportAffinity()
|
||||
exitProvisionalThread()
|
||||
relayCapabilityGeneration.incrementAndGet()
|
||||
relayReasoningCapabilities.value = emptyMap()
|
||||
@@ -4799,6 +4865,8 @@ class ChatViewModel : ViewModel() {
|
||||
} else {
|
||||
sessionProfileNameProvider()
|
||||
}
|
||||
val targetTransport = sessionId?.let(SessionTransport::forSessionId)
|
||||
?: SessionTransport.forEndpoint(resolvedStreamingEndpoint)
|
||||
if (explicitBinding) {
|
||||
val accepted = conversationBindingController.openExplicit(
|
||||
contextKey = contextKey,
|
||||
@@ -4806,6 +4874,7 @@ class ChatViewModel : ViewModel() {
|
||||
sessionId = sessionId,
|
||||
displayProfile = explicitDisplayProfile,
|
||||
lockedProfileToken = lockedProfileNameProvider(),
|
||||
transport = targetTransport,
|
||||
)
|
||||
if (!accepted) return
|
||||
} else if (reconciliation) {
|
||||
@@ -4813,6 +4882,7 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = contextKey,
|
||||
profileName = targetProfileName,
|
||||
sessionId = sessionId,
|
||||
transport = targetTransport,
|
||||
)
|
||||
if (!accepted) {
|
||||
_initialChatSettled.value = true
|
||||
@@ -4823,8 +4893,10 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = contextKey,
|
||||
profileName = targetProfileName,
|
||||
sessionId = sessionId,
|
||||
transport = targetTransport,
|
||||
)
|
||||
}
|
||||
reapplyConversationTransportAffinity()
|
||||
activateSessionActivityScope()
|
||||
handler.activeAgentName = currentAgentDisplayName()
|
||||
if (
|
||||
@@ -5382,6 +5454,7 @@ class ChatViewModel : ViewModel() {
|
||||
// recovery state. Preserve cached history and
|
||||
// mark the directory unavailable without also
|
||||
// emitting a generic turn/error toast.
|
||||
dashboardSignInRequiredHandler?.invoke()
|
||||
} else if (scoped != null) {
|
||||
// The shared API list belongs to the launch/default
|
||||
// database. Preserve the current profile's rows and
|
||||
@@ -5404,7 +5477,9 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
retryUnavailable = true
|
||||
retryReadiness = retryReadiness || !e.isSessionReadTimeout()
|
||||
if (!e.isDashboardSignInRequiredFailure()) {
|
||||
if (e.isDashboardSignInRequiredFailure()) {
|
||||
dashboardSignInRequiredHandler?.invoke()
|
||||
} else {
|
||||
emitError(
|
||||
e,
|
||||
context = if (profileSessionLister != null) {
|
||||
@@ -5581,7 +5656,10 @@ class ChatViewModel : ViewModel() {
|
||||
// profile/context so an All Profiles conversation becomes a fresh
|
||||
// draft for that same owner instead of falling back to the globally
|
||||
// restored default profile.
|
||||
conversationBindingController.startFreshDraft()
|
||||
conversationBindingController.startFreshDraft(
|
||||
SessionTransport.forEndpoint(resolvedStreamingEndpoint),
|
||||
)
|
||||
reapplyConversationTransportAffinity()
|
||||
exitProvisionalThread()
|
||||
|
||||
// Gateway turns continue as detached siblings; SSE remains exclusive.
|
||||
@@ -5840,6 +5918,7 @@ class ChatViewModel : ViewModel() {
|
||||
val contextKey = activeProfileContextKey
|
||||
val profileName = currentSessionProfileName()
|
||||
conversationBindingController.switchSession(sessionId)
|
||||
reapplyConversationTransportAffinity()
|
||||
|
||||
handler.setSessionId(sessionId)
|
||||
publishQueuedMessages()
|
||||
@@ -5956,6 +6035,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
if (handler.currentSessionId.value == null) {
|
||||
conversationBindingController.switchSession(null)
|
||||
reapplyConversationTransportAffinity()
|
||||
onSessionChanged?.invoke(null)
|
||||
}
|
||||
|
||||
@@ -6182,10 +6262,10 @@ class ChatViewModel : ViewModel() {
|
||||
val client = apiClient
|
||||
if (
|
||||
(streamingEndpoint != "gateway" && client == null) ||
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null)
|
||||
) {
|
||||
val message = if (streamingEndpoint == "gateway") {
|
||||
"Gateway is unavailable and no API fallback is configured for this connection."
|
||||
"This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry."
|
||||
} else {
|
||||
"API fallback is not configured for this connection."
|
||||
}
|
||||
@@ -6293,9 +6373,15 @@ class ChatViewModel : ViewModel() {
|
||||
?: return VoiceMessageSubmissionResult.Rejected("Hermes chat is not ready.")
|
||||
val client = apiClient
|
||||
if ((streamingEndpoint != "gateway" && client == null) ||
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null)
|
||||
) {
|
||||
return VoiceMessageSubmissionResult.Rejected("Hermes is not connected.")
|
||||
return VoiceMessageSubmissionResult.Rejected(
|
||||
if (streamingEndpoint == "gateway") {
|
||||
"This chat needs the Hermes Dashboard. Sign in or reconnect, then retry."
|
||||
} else {
|
||||
"The direct API connection is unavailable."
|
||||
},
|
||||
)
|
||||
}
|
||||
if (activeStream != null || streamRecovery != null || handler.isStreaming.value) {
|
||||
return VoiceMessageSubmissionResult.Rejected(
|
||||
@@ -7823,13 +7909,39 @@ class ChatViewModel : ViewModel() {
|
||||
if (!queuedSuccessorPending.get()) {
|
||||
val expectedSessionId = checkpoint.sessionId
|
||||
viewModelScope.launch {
|
||||
val history = loadSessionHistory(expectedSessionId)
|
||||
if (handler.currentSessionId.value == expectedSessionId && history.isNotEmpty()) {
|
||||
handler.loadMessageHistory(history)
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(expectedSessionId)
|
||||
try {
|
||||
val history = loadSessionHistory(expectedSessionId)
|
||||
if (
|
||||
handler.currentSessionId.value == expectedSessionId &&
|
||||
history.isNotEmpty()
|
||||
) {
|
||||
handler.loadMessageHistory(history)
|
||||
clearMatchingHistoryLoadFailure(expectedSessionId)
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// Recovery completion has already settled the
|
||||
// local turn. Keep it visible and route an
|
||||
// expired Dashboard session to sign-in.
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == checkpoint.contextKey &&
|
||||
handler.currentSessionId.value == expectedSessionId
|
||||
) {
|
||||
publishHistoryLoadFailure(expectedSessionId, e)
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == checkpoint.contextKey &&
|
||||
handler.currentSessionId.value == expectedSessionId
|
||||
) {
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(expectedSessionId)
|
||||
}
|
||||
drainQueue()
|
||||
}
|
||||
drainQueue()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9566,7 +9678,7 @@ class ChatViewModel : ViewModel() {
|
||||
ensurePostInterimMessage()
|
||||
streamDeltas.flushNow()
|
||||
val alreadyObserved =
|
||||
toolName == "image_generate" &&
|
||||
isImageGenerationToolName(toolName) &&
|
||||
observedImageToolStates.putIfAbsent(toolCallId, "running") != null
|
||||
if (!alreadyObserved) {
|
||||
handler.onToolCallStart(currentMessageId, toolCallId, toolName, argsPreview)
|
||||
@@ -9693,6 +9805,7 @@ class ChatViewModel : ViewModel() {
|
||||
// tool.complete. The structured reload recovers those calls without ever
|
||||
// parsing assistant prose and retains the profile-aware history boundary.
|
||||
val sid = handler.currentSessionId.value
|
||||
val historyContextKey = activeProfileContextKey
|
||||
// A turn that ended in an error (gateway ❌ lifecycle → "Error" badge)
|
||||
// has NO assistant message persisted server-side, so reconciling the
|
||||
// server transcript would WIPE the just-shown error bubble (the user
|
||||
@@ -9711,34 +9824,54 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
if (!turnErrored && !gatewayHistoryReconcileRequired) {
|
||||
// Profile-aware read: a gateway turn on a non-default profile
|
||||
// persists into THAT profile's own state.db, so the bare
|
||||
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
|
||||
// → a silent wipe of the just-finished turn. loadSessionHistory
|
||||
// prefers the `?profile=` dashboard loader on gateway connections.
|
||||
val serverMessages = loadSessionHistory(sid)
|
||||
val missingPersistedToolActivity =
|
||||
completedTransport == "gateway" &&
|
||||
handler.hasMissingPersistedToolActivity(serverMessages)
|
||||
if (shouldReloadHistoryAfterSuccessfulTurn(
|
||||
actualTransport = completedTransport,
|
||||
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
|
||||
missingPersistedToolActivity = missingPersistedToolActivity,
|
||||
)
|
||||
) {
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
try {
|
||||
if (!turnErrored && !gatewayHistoryReconcileRequired) {
|
||||
// Profile-aware read: a gateway turn on a non-default profile
|
||||
// persists into THAT profile's own state.db, so the bare
|
||||
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
|
||||
// → a silent wipe of the just-finished turn. loadSessionHistory
|
||||
// prefers the `?profile=` dashboard loader on gateway connections.
|
||||
val serverMessages = loadSessionHistory(sid)
|
||||
val missingPersistedToolActivity =
|
||||
completedTransport == "gateway" &&
|
||||
handler.hasMissingPersistedToolActivity(serverMessages)
|
||||
if (shouldReloadHistoryAfterSuccessfulTurn(
|
||||
actualTransport = completedTransport,
|
||||
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
|
||||
missingPersistedToolActivity = missingPersistedToolActivity,
|
||||
)
|
||||
) {
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
clearMatchingHistoryLoadFailure(sid)
|
||||
}
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == historyContextKey &&
|
||||
handler.currentSessionId.value == sid
|
||||
) {
|
||||
publishHistoryLoadFailure(sid, e)
|
||||
}
|
||||
} finally {
|
||||
// Re-sync the drawer now that the turn is persisted server-side.
|
||||
// The only other auto-refresh fires ~160ms after session creation
|
||||
// (RelayApp) — mid-stream, BEFORE the new session's first message
|
||||
// is persisted, so a brand-new chat would otherwise stay missing
|
||||
// from the drawer (carried only by the optimistic row) until a
|
||||
// manual reload. By message.complete the dashboard list includes it.
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == historyContextKey &&
|
||||
handler.currentSessionId.value == sid
|
||||
) {
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(sid)
|
||||
}
|
||||
drainQueue()
|
||||
}
|
||||
// Re-sync the drawer now that the turn is persisted server-side.
|
||||
// The only other auto-refresh fires ~160ms after session creation
|
||||
// (RelayApp) — mid-stream, BEFORE the new session's first message
|
||||
// is persisted, so a brand-new chat would otherwise stay missing
|
||||
// from the drawer (carried only by the optimistic row) until a
|
||||
// manual reload. By message.complete the dashboard list includes it.
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(sid)
|
||||
drainQueue()
|
||||
}
|
||||
Unit
|
||||
} else {
|
||||
@@ -10015,12 +10148,11 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
}
|
||||
|
||||
// SSE dispatch shared by the three HTTP endpoints AND the gateway
|
||||
// branch's per-turn fallback (gateway unreachable / not the resolved
|
||||
// transport). Warns once per dispatch about any attachment it can't carry.
|
||||
// SSE dispatch shared by the three explicit API compatibility endpoints.
|
||||
// Warns once per dispatch about any attachment it can't carry.
|
||||
fun dispatchSse(endpoint: String): ActiveTurnHandle? {
|
||||
val sseClient = client ?: run {
|
||||
onErrorCb("Gateway unavailable and no API fallback is configured.")
|
||||
onErrorCb("The direct API connection is unavailable.")
|
||||
return null
|
||||
}
|
||||
val prepared = prepareTextTransportAttachments(message, attachments.orEmpty())
|
||||
@@ -10165,13 +10297,13 @@ class ChatViewModel : ViewModel() {
|
||||
activeStream = when {
|
||||
effectiveEndpoint != "gateway" -> dispatchSse(effectiveEndpoint)
|
||||
|
||||
// Gateway turns upload ALL attachments via their typed upstream
|
||||
// RPC (image.attach_bytes / pdf.attach / file.attach), matching the
|
||||
// desktop client. Only a missing gateway client forces the per-turn
|
||||
// SSE fallback (where non-image attachments are not upstream-
|
||||
// recognized and would be dropped — graceful degradation).
|
||||
gateway == null ->
|
||||
dispatchSse(resolveSseFallback(handler))
|
||||
// The conversation owner is immutable. Losing Gateway preserves
|
||||
// the local transcript/draft and exposes Retry; it never dispatches
|
||||
// the turn into the API server's different session database.
|
||||
gateway == null -> {
|
||||
onErrorCb("This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry.")
|
||||
null
|
||||
}
|
||||
|
||||
else -> {
|
||||
startImageActivityBridge()
|
||||
@@ -10343,11 +10475,14 @@ class ChatViewModel : ViewModel() {
|
||||
activeStream = null
|
||||
settleSessionActivity(handler.currentSessionId.value)
|
||||
} else {
|
||||
// Nothing started server-side — rerun this turn on
|
||||
// the SSE fallback. Callbacks land on the main
|
||||
// thread, so swapping activeStream here is safe.
|
||||
// The fallback turn is not steerable.
|
||||
activeStream = dispatchSse(resolveSseFallback(handler))
|
||||
// Nothing started server-side. Keep this turn bound
|
||||
// to Gateway and settle it as retryable local state;
|
||||
// API sessions are a different owner/database.
|
||||
onPreflightErrorCb(
|
||||
IllegalStateException(
|
||||
"Hermes Dashboard chat is unavailable. Sign in or reconnect, then retry.",
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -10371,8 +10506,8 @@ class ChatViewModel : ViewModel() {
|
||||
// configured transport: a gateway-configured turn forced onto SSE
|
||||
// (voice interface context, trace drain) did carry the synthetic
|
||||
// messages, and skipping the mark there re-sent them every turn.
|
||||
// The async gateway preflight-failure fallback stays conservative:
|
||||
// its traces are marked on the NEXT turn (at-least-once delivery).
|
||||
// A failed Gateway preflight leaves these traces unsynced; retrying the
|
||||
// same owner retains at-least-once delivery without crossing stores.
|
||||
if (voiceIntentMessages != null && effectiveEndpoint != "gateway") {
|
||||
if (hasVoiceIntents) handler.markVoiceIntentsSynced()
|
||||
if (hasCardDispatches) handler.markCardDispatchesSynced()
|
||||
@@ -10384,18 +10519,6 @@ class ChatViewModel : ViewModel() {
|
||||
private fun EventSource.asTurnHandle(): ActiveTurnHandle =
|
||||
ActiveTurnHandle { this.cancel() }
|
||||
|
||||
/**
|
||||
* SSE endpoint for a turn that was meant for the gateway. The sessions
|
||||
* endpoint needs an existing server session — without one, use the
|
||||
* stateless completions path instead of failing the turn.
|
||||
*/
|
||||
private fun resolveSseFallback(handler: ChatHandler): String =
|
||||
if (sseFallbackEndpoint == "sessions" && handler.currentSessionId.value == null) {
|
||||
"completions"
|
||||
} else {
|
||||
sseFallbackEndpoint
|
||||
}
|
||||
|
||||
private fun currentAgentDisplayName(
|
||||
effectiveProfileOverride: Profile? = null,
|
||||
): String? {
|
||||
|
||||
@@ -55,6 +55,8 @@ import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.automaticChatTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.ConnectionSecurity
|
||||
import com.hermesandroid.relay.data.ConnectionStore
|
||||
import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
|
||||
@@ -348,16 +350,16 @@ internal fun resolveChatConnectState(
|
||||
ready: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
chatOwner: SessionTransport = connection?.automaticChatTransport ?: SessionTransport.GATEWAY,
|
||||
): ChatConnectState {
|
||||
if (ready) return ChatConnectState.Ready
|
||||
if (!hydrated) return ChatConnectState.Connecting
|
||||
val active = connection ?: return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = active.capabilities.dashboardGatewayConfigured &&
|
||||
if (connection == null) return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability in setOf(
|
||||
GatewayAvailability.Unknown,
|
||||
GatewayAvailability.SignInRequired,
|
||||
)
|
||||
val apiStillSettling = active.capabilities.apiServerConfigured &&
|
||||
val apiStillSettling = chatOwner == SessionTransport.SSE &&
|
||||
apiHealth in setOf(
|
||||
ConnectionViewModel.HealthStatus.Unknown,
|
||||
ConnectionViewModel.HealthStatus.Probing,
|
||||
@@ -374,9 +376,20 @@ internal fun isChatTransportReady(
|
||||
apiClientPresent: Boolean,
|
||||
apiReachable: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
chatOwner: SessionTransport = SessionTransport.GATEWAY,
|
||||
): Boolean =
|
||||
gatewayAvailability == GatewayAvailability.Ready ||
|
||||
(apiClientPresent && apiReachable)
|
||||
when (chatOwner) {
|
||||
SessionTransport.GATEWAY -> gatewayAvailability == GatewayAvailability.Ready
|
||||
SessionTransport.SSE -> apiClientPresent && apiReachable
|
||||
}
|
||||
|
||||
internal fun resolveActiveChatTransport(
|
||||
boundOwner: SessionTransport?,
|
||||
connection: Connection?,
|
||||
preference: String,
|
||||
): SessionTransport = boundOwner
|
||||
?: connection?.chatTransportForPreference(preference)
|
||||
?: SessionTransport.GATEWAY
|
||||
|
||||
/** Startup transport timeouts are retryable evidence, not an offline verdict. */
|
||||
internal fun isTransientDashboardTransportFailure(error: Throwable?): Boolean =
|
||||
@@ -1325,7 +1338,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
upstreamTransport.dashboardSessionClientFor(cid, url)
|
||||
},
|
||||
streamingEndpointProvider = { streamingEndpoint.value },
|
||||
gatewayAvailabilityProvider = { upstreamTransport.gatewayAvailability.value },
|
||||
automaticTransportProvider = {
|
||||
activeConnection.value?.automaticChatTransport ?: SessionTransport.GATEWAY
|
||||
},
|
||||
setLastSessionId = { _lastSessionId.value = it },
|
||||
legacyDefaultSessionId = {
|
||||
getApplication<Application>().relayDataStore.data.first()[KEY_LAST_SESSION_ID]
|
||||
@@ -1667,10 +1682,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val _chatApiClient = MutableStateFlow<HermesApiClient?>(null)
|
||||
val chatApiClient: StateFlow<HermesApiClient?> = _chatApiClient.asStateFlow()
|
||||
private val _activeConversationTransport = MutableStateFlow<SessionTransport?>(null)
|
||||
val activeConversationTransport: StateFlow<SessionTransport?> =
|
||||
_activeConversationTransport.asStateFlow()
|
||||
private var profileChatApiClient: HermesApiClient? = null
|
||||
private var profileChatApiClientUrl: String? = null
|
||||
private var profileChatApiClientKey: String? = null
|
||||
|
||||
fun setActiveConversationTransport(transport: SessionTransport?) {
|
||||
_activeConversationTransport.value = transport
|
||||
}
|
||||
|
||||
// Chat mode + per-endpoint capability snapshot — owned by
|
||||
// [upstreamTransport]; getters delegate. `rebuildApiClient()` pushes the
|
||||
// freshly-probed snapshot via `setCapabilitiesAndMode`.
|
||||
@@ -1863,16 +1885,24 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return upstreamTransport.dashboardClientFor(connectionId, dashboardUrl).getConfig()
|
||||
}
|
||||
|
||||
// Gateway/Dashboard is the standard path; API remains an optional fallback.
|
||||
private val streamingEndpointPreference: StateFlow<String> =
|
||||
application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
// Readiness follows the active conversation owner, not any reachable sibling route.
|
||||
val chatReady: StateFlow<Boolean> = combine(
|
||||
_chatApiClient,
|
||||
_apiServerReachable,
|
||||
combine(_chatApiClient, _apiServerReachable) { client, reachable -> client to reachable },
|
||||
upstreamTransport.gatewayAvailability,
|
||||
) { client, apiReachable, gateway ->
|
||||
activeConnection,
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (client, apiReachable), gateway, connection, preference, boundOwner ->
|
||||
isChatTransportReady(
|
||||
apiClientPresent = client != null,
|
||||
apiReachable = apiReachable,
|
||||
gatewayAvailability = gateway,
|
||||
chatOwner = resolveActiveChatTransport(boundOwner, connection, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
|
||||
@@ -1892,13 +1922,22 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* before any flow emits — is the neutral state, not the CTA.
|
||||
*/
|
||||
val chatConnectState: StateFlow<ChatConnectState> = combine(
|
||||
connectionStore.isHydrated,
|
||||
activeConnection,
|
||||
chatReady,
|
||||
combine(connectionStore.isHydrated, activeConnection, chatReady) { hydrated, active, ready ->
|
||||
Triple(hydrated, active, ready)
|
||||
},
|
||||
upstreamTransport.gatewayAvailability,
|
||||
_apiServerHealth,
|
||||
) { hydrated, active, ready, gateway, apiHealth ->
|
||||
resolveChatConnectState(hydrated, active, ready, gateway, apiHealth)
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (hydrated, active, ready), gateway, apiHealth, preference, boundOwner ->
|
||||
resolveChatConnectState(
|
||||
hydrated,
|
||||
active,
|
||||
ready,
|
||||
gateway,
|
||||
apiHealth,
|
||||
resolveActiveChatTransport(boundOwner, active, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, ChatConnectState.Connecting)
|
||||
// NOTE: [relayReady] / [voiceReady] are declared below the [_relayUrl]
|
||||
// MutableStateFlow,
|
||||
@@ -2749,9 +2788,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
//
|
||||
// Existing users keep whatever they previously chose. Only fresh installs
|
||||
// (no value persisted yet) get the new "auto" default.
|
||||
val streamingEndpoint: StateFlow<String> = application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
val streamingEndpoint: StateFlow<String> = streamingEndpointPreference
|
||||
|
||||
fun setStreamingEndpoint(endpoint: String) {
|
||||
viewModelScope.launch {
|
||||
@@ -2833,14 +2870,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
upstreamTransport.resolveStreamingEndpoint(preference)
|
||||
upstreamTransport.resolveStreamingEndpoint(
|
||||
preference = preference,
|
||||
gatewayOwned = activeConnection.value
|
||||
?.chatTransportForPreference(preference) == SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [ChatViewModel.sseFallbackEndpoint] for per-turn gateway fallbacks.
|
||||
* [ChatViewModel.sseFallbackEndpoint] only for an API-owned compatibility
|
||||
* binding.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String = upstreamTransport.resolveSseStreamingEndpoint()
|
||||
|
||||
fun resolveActiveStreamingEndpoint(preference: String): String =
|
||||
when (activeConversationTransport.value) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> resolveStreamingEndpoint(preference)
|
||||
.takeUnless { it == "gateway" }
|
||||
?: resolveSseStreamingEndpoint()
|
||||
null -> resolveStreamingEndpoint(preference)
|
||||
}
|
||||
|
||||
// Parse tool annotations from text markers toggle
|
||||
val parseToolAnnotations: StateFlow<Boolean> = application.relayDataStore.data
|
||||
.map { it[KEY_PARSE_TOOL_ANNOTATIONS] ?: false }
|
||||
@@ -3674,11 +3725,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
val dashboardConfigured = activeConnection?.capabilities?.dashboardGatewayConfigured == true
|
||||
val apiConfigured = activeConnection?.capabilities?.apiServerConfigured == true
|
||||
// This helper runs from an eager StateFlow during construction. Read
|
||||
// the earlier-declared backing preference, not its later public alias.
|
||||
val chatOwner = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport.value,
|
||||
connection = activeConnection,
|
||||
preference = streamingEndpointPreference.value,
|
||||
)
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_sign_in_required),
|
||||
@@ -3695,8 +3753,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_not_reachable),
|
||||
@@ -3712,7 +3770,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
return when {
|
||||
apiConfigured &&
|
||||
chatOwner == SessionTransport.SSE &&
|
||||
apiConfigured &&
|
||||
apiHealth == HealthStatus.Unreachable &&
|
||||
gatewayAvailability != GatewayAvailability.Ready -> {
|
||||
// Diagnose, don't just report: for a single-route connection
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -23,6 +24,7 @@ internal data class ConversationBinding(
|
||||
val contextKey: String? = null,
|
||||
val profileName: String? = null,
|
||||
val sessionId: String? = null,
|
||||
val transport: SessionTransport? = null,
|
||||
val displayProfile: Profile? = null,
|
||||
val origin: ConversationBindingOrigin = ConversationBindingOrigin.GlobalSelection,
|
||||
val revision: Long = 0L,
|
||||
@@ -46,6 +48,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
lockedProfileToken: String?,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
if (!profileAllowed(profileName, lockedProfileToken)) return false
|
||||
reduce(
|
||||
@@ -54,6 +57,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
transport = transport,
|
||||
)
|
||||
return true
|
||||
}
|
||||
@@ -63,6 +67,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
) {
|
||||
reduce(
|
||||
contextKey = contextKey,
|
||||
@@ -70,6 +75,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.GlobalSelection,
|
||||
transport = transport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,6 +85,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
val current = _state.value
|
||||
if (
|
||||
@@ -89,7 +96,7 @@ internal class ConversationBindingController {
|
||||
current.sessionId != sessionId
|
||||
)
|
||||
) return false
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile)
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile, transport)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,17 +105,19 @@ internal class ConversationBindingController {
|
||||
if (current.sessionId == sessionId) return
|
||||
_state.value = current.copy(
|
||||
sessionId = sessionId,
|
||||
transport = sessionId?.let(SessionTransport::forSessionId) ?: current.transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
}
|
||||
|
||||
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
|
||||
fun startFreshDraft() {
|
||||
fun startFreshDraft(transport: SessionTransport? = _state.value.transport) {
|
||||
val current = _state.value
|
||||
if (!current.isBound) return
|
||||
if (current.sessionId == null && current.hasExplicitOwner) return
|
||||
_state.value = current.copy(
|
||||
sessionId = null,
|
||||
transport = transport,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
@@ -130,6 +139,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
origin: ConversationBindingOrigin,
|
||||
transport: SessionTransport?,
|
||||
) {
|
||||
val current = _state.value
|
||||
val next = ConversationBinding(
|
||||
@@ -138,6 +148,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = origin,
|
||||
transport = transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
if (current.copy(revision = next.revision) != next) {
|
||||
|
||||
+6
-11
@@ -130,8 +130,8 @@ class ProfileController(
|
||||
private val dashboardClientFactory: (connectionId: String, dashboardUrl: String) -> DashboardApiClient,
|
||||
/** Current `streamingEndpoint` preference (for [activeSessionTransport]). */
|
||||
private val streamingEndpointProvider: () -> String,
|
||||
/** Current gateway availability tier (for [activeSessionTransport]). */
|
||||
private val gatewayAvailabilityProvider: () -> GatewayAvailability,
|
||||
/** Stable Auto owner for the active saved connection. */
|
||||
private val automaticTransportProvider: () -> SessionTransport,
|
||||
/** Writes `ConnectionViewModel._lastSessionId`. */
|
||||
private val setLastSessionId: (String?) -> Unit,
|
||||
/** Legacy default (untransported) session id for the server-default profile. */
|
||||
@@ -1517,19 +1517,14 @@ class ProfileController(
|
||||
|
||||
/**
|
||||
* Which transport's session slot to restore right now — or `null` when the
|
||||
* decision is still pending (the gateway probe hasn't landed). A manual
|
||||
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
|
||||
* remains Gateway-owned because the transport resolver also chooses Gateway
|
||||
* until a definitive fallback verdict exists.
|
||||
* decision is still pending. A manual streaming-endpoint override resolves
|
||||
* immediately; under `"auto"`, the saved connection contract owns the
|
||||
* choice, never a transient reachability or authentication verdict.
|
||||
*/
|
||||
fun activeSessionTransport(): SessionTransport? {
|
||||
val preference = streamingEndpointProvider()
|
||||
if (preference != "auto") return SessionTransport.forEndpoint(preference)
|
||||
return when (gatewayAvailabilityProvider()) {
|
||||
GatewayAvailability.Ready -> SessionTransport.GATEWAY
|
||||
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
|
||||
else -> SessionTransport.SSE
|
||||
}
|
||||
return automaticTransportProvider()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -667,17 +667,21 @@ class UpstreamTransportController(
|
||||
* - "sessions" / "completions" / "runs" pass through unchanged (manual override wins).
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
fun resolveStreamingEndpoint(
|
||||
preference: String,
|
||||
gatewayOwned: Boolean,
|
||||
): String =
|
||||
resolveStreamingEndpointPreference(
|
||||
preference = preference,
|
||||
gateway = _gatewayAvailability.value,
|
||||
capabilities = _serverCapabilities.value,
|
||||
gatewayOwned = gatewayOwned,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.sseFallbackEndpoint] for
|
||||
* per-turn gateway fallbacks.
|
||||
* explicit API-owned compatibility conversations.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String =
|
||||
_serverCapabilities.value.preferredChatEndpoint()
|
||||
|
||||
@@ -288,7 +288,7 @@
|
||||
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Informe o endereço do Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e fallback da API são opcionais.</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e API direta são opcionais.</string>
|
||||
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
|
||||
<string name="cw_cloud_agent_name">Endereço do agente</string>
|
||||
@@ -373,7 +373,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 ou http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API do Hermes usada pelo Chat e pelas sessões — a porta 8642 da API e http:// são presumidos para hosts sem esquema (a porta 9119 do painel é determinada separadamente)</string>
|
||||
<string name="cw_scan_message">Procurando o painel/a API do Hermes nesta LAN…</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas no fallback opcional pela API direta.</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas em conexões explícitas pela API direta.</string>
|
||||
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
|
||||
<string name="cw_pair_relay_section_desc">O plugin do Relay já está em execução? Faça o pareamento aqui para ativar Terminal, Bridge e permissões de canais.</string>
|
||||
<string name="cw_pair_relay_url_label">URL do Relay</string>
|
||||
@@ -584,6 +584,11 @@
|
||||
<string name="changelog_state_collapsed">Recolhido</string>
|
||||
<string name="changelog_installed">Instalado</string>
|
||||
<string name="changelog_also_improved">Também melhorado</string>
|
||||
<string name="changelog_highlights">Destaques</string>
|
||||
<string name="changelog_added">Adicionado</string>
|
||||
<string name="changelog_improved">Melhorado</string>
|
||||
<string name="changelog_fixed">Corrigido</string>
|
||||
<string name="changelog_compatibility">Compatibilidade</string>
|
||||
<string name="changelog_toast_also">Também: %1$s</string>
|
||||
<string name="changelog_view_all">Ver tudo</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -594,6 +599,10 @@
|
||||
<item quantity="one">%1$d correção</item>
|
||||
<item quantity="other">%1$d correções</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="one">%1$d melhoria</item>
|
||||
<item quantity="other">%1$d melhorias</item>
|
||||
</plurals>
|
||||
<!-- DiagnosticsScreen -->
|
||||
<string name="diag_title">Diagnóstico</string>
|
||||
<string name="diag_back">Voltar</string>
|
||||
@@ -656,7 +665,7 @@
|
||||
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
|
||||
<string name="settings_hermes_management_desc">Recursos do painel: habilidades, cron, MCP, perfis e modelos</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, fallback da API, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, API direta, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Voz do painel, opções de relay em tempo real e provedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -766,11 +775,11 @@
|
||||
<string name="chat_settings_debug">Depuração</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostre os marcadores ocultos \"[System: …]\" do servidor (alterações de modelo/personalidade). Desativado corresponde ao desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Endpoint de streaming</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: escolhe o melhor caminho com base no que seu servidor oferece. Em uso no momento: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: conexões padrão usam o Gateway; conexões somente API usam a API direta. Em uso no momento: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamento ao vivo pelo WebSocket do painel)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat por /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat transmitido explicitamente por /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, usa SSE como alternativa em cada turno.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, este chat permanece no Gateway e oferece login ou nova tentativa.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessões: fluxo nativo do Hermes em /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatível com OpenAI por /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use somente quando seu servidor transmitir /v1/runs diretamente.</string>
|
||||
@@ -3239,7 +3248,7 @@
|
||||
<string name="whats_new_full_history">Ver histórico completo</string>
|
||||
<string name="whats_new_no_notes">Nenhuma nota de versão disponível</string>
|
||||
<string name="whats_new_title">Novidades</string>
|
||||
<string name="whats_new_subtitle">Destaques da versão mais recente</string>
|
||||
<string name="whats_new_subtitle">Destaques e detalhes completos da versão</string>
|
||||
<!-- Localization guardrail additions for current dev surfaces -->
|
||||
<string name="bridge_notification_auto_disabled_title">Acesso temporário à tela expirou</string>
|
||||
<string name="bridge_notification_auto_disabled_body">Inspeção e controle da tela foram desativados após ociosidade. As outras permissões não mudaram.</string>
|
||||
@@ -3330,7 +3339,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Inacessível</string>
|
||||
<string name="active_section_no_fallback_routes">Ainda não há rotas alternativas</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Adicione uma rota de API opcional para chat direto alternativo e troca de rede.</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota alternativa</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota de API direta</string>
|
||||
<string name="active_section_security_authentication">Autenticação</string>
|
||||
<string name="active_section_dashboard_session">Sessão do Dashboard</string>
|
||||
<string name="active_section_credential_storage">Armazenamento de credenciais</string>
|
||||
@@ -3355,7 +3364,7 @@
|
||||
<string name="cw_timeline_authenticated">Autenticação verificada</string>
|
||||
<string name="cw_timeline_ready">Conexão pronta</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage e Voice podem usar este Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">Fallback opcional pela API direta</string>
|
||||
<string name="active_section_optional_api_fallback">API direta opcional</string>
|
||||
<string name="active_section_api_not_required">Não é necessário quando esta conexão usa o Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Onde obtenho essa chave?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY é criada no seu servidor Hermes; este aplicativo não fornece a chave. Configure-a somente ao ativar o servidor de API opcional, que exige uma chave utilizável, e insira aqui o mesmo valor.</string>
|
||||
@@ -4369,7 +4378,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API direta</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Defina o endereço do Dashboard e do Gateway que este telefone deve usar. Rotas privadas de LAN e Tailscale podem usar HTTP ou HTTPS; rotas públicas exigem HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Endereço do gateway</string>
|
||||
@@ -4386,7 +4395,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. O fallback da API e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. A API direta e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
|
||||
<string name="chat_failure_copy_details">复制详情</string>
|
||||
<string name="chat_failure_route_gateway">网关</string>
|
||||
<string name="chat_failure_route_api">API 回退</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">打开设置</string>
|
||||
<string name="chat_connect_hermes">连接 Hermes</string>
|
||||
<string name="chat_try_demo">体验演示</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 或 http://你的服务器:8642</string>
|
||||
<string name="cw_api_url_supporting">聊天和会话使用的 Hermes API——裸主机名默认使用 API 端口 8642 和 http://(仪表盘的 9119 端口单独推导)</string>
|
||||
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于可选的直接 API 回退。</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
|
||||
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
|
||||
<string name="cw_pair_relay_for">为 %1$s 配对 Relay</string>
|
||||
<string name="cw_pair_relay_scoped_desc">为这个已保存的 Hermes 连接添加可选的 Relay 扩展。这不会添加或替换服务器。</string>
|
||||
@@ -621,6 +621,11 @@
|
||||
<string name="changelog_state_collapsed">已收起</string>
|
||||
<string name="changelog_installed">已安装</string>
|
||||
<string name="changelog_also_improved">其他改进</string>
|
||||
<string name="changelog_highlights">亮点</string>
|
||||
<string name="changelog_added">新增</string>
|
||||
<string name="changelog_improved">改进</string>
|
||||
<string name="changelog_fixed">修复</string>
|
||||
<string name="changelog_compatibility">兼容性</string>
|
||||
<string name="changelog_toast_also">另外:%1$s</string>
|
||||
<string name="changelog_view_all">查看全部</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -629,6 +634,9 @@
|
||||
<plurals name="changelog_fix_count">
|
||||
<item quantity="other">%1$d 项修复</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="other">%1$d 项改进</item>
|
||||
</plurals>
|
||||
|
||||
<!-- DiagnosticsScreen -->
|
||||
<string name="diag_title">诊断</string>
|
||||
@@ -695,7 +703,7 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">仪表盘功能:技能、定时任务、MCP、配置文件、模型</string>
|
||||
<string name="settings_chat">聊天</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、API 回退、工具显示、消息长度</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、Direct API、工具显示、消息长度</string>
|
||||
<string name="settings_voice_mode">语音模式</string>
|
||||
<string name="settings_voice_mode_desc">仪表盘语音、实时 Relay 选项、提供商</string>
|
||||
<string name="settings_threads">话题</string>
|
||||
@@ -806,11 +814,11 @@
|
||||
<string name="chat_settings_debug">调试</string>
|
||||
<string name="chat_settings_show_system_messages_desc">显示服务器隐藏的 \"[System: …]\" 标记(模型/人格更改)。关闭则与桌面/TUI 一致。</string>
|
||||
<string name="chat_settings_streaming_endpoint">流式端点</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:根据服务器暴露的内容选择最佳路径。当前使用:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:标准连接使用网关;仅 API 连接使用直接 API。当前使用:</string>
|
||||
<string name="chat_settings_gateway_suffix">(通过仪表盘 WebSocket 实时思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(通过 /v1/chat/completions 聊天)</string>
|
||||
<string name="chat_settings_runs_suffix">(通过显式流式 /v1/runs 聊天)</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)实时思考+丰富工具事件——桌面应用使用的方式。需要管理登录;不可用时每轮回退到 SSE。</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)提供实时思考和丰富工具事件——桌面应用也使用此路径。需要“管理”登录;不可用时,此聊天仍保留在网关,并提示登录或重试。</string>
|
||||
<string name="chat_settings_sessions_desc">会话:Hermes 原生 /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">聊天:通过 /v1/chat/completions 的 OpenAI 兼容 SSE。</string>
|
||||
<string name="chat_settings_runs_desc">Runs:仅在服务器直接流式传输 /v1/runs 时使用。</string>
|
||||
@@ -3339,7 +3347,7 @@
|
||||
<string name="whats_new_full_history">查看完整历史记录</string>
|
||||
<string name="whats_new_no_notes">无可用的发布说明</string>
|
||||
<string name="whats_new_title">更新内容</string>
|
||||
<string name="whats_new_subtitle">最新版本亮点</string>
|
||||
<string name="whats_new_subtitle">亮点和完整版本详情</string>
|
||||
<!-- Localization guardrail additions for current dev surfaces -->
|
||||
<string name="bridge_notification_auto_disabled_title">限时屏幕访问已到期</string>
|
||||
<string name="bridge_notification_auto_disabled_body">空闲后,屏幕检查和控制已关闭。其他授权保持不变。</string>
|
||||
@@ -3442,7 +3450,7 @@
|
||||
<string name="active_section_dashboard_unreachable">无法访问</string>
|
||||
<string name="active_section_no_fallback_routes">尚无备用路由</string>
|
||||
<string name="active_section_no_fallback_routes_desc">可添加 API 路由,用于直接聊天回退和网络切换。</string>
|
||||
<string name="active_section_add_api_fallback">添加备用路由</string>
|
||||
<string name="active_section_add_api_fallback">添加 Direct API 路由</string>
|
||||
<string name="active_section_security_authentication">身份验证</string>
|
||||
<string name="active_section_dashboard_session">Dashboard 会话</string>
|
||||
<string name="active_section_credential_storage">凭据存储</string>
|
||||
@@ -3508,7 +3516,7 @@
|
||||
<string name="cw_timeline_authenticated">身份验证已确认</string>
|
||||
<string name="cw_timeline_ready">连接已就绪</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage 和 Voice 可以使用此 Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">可选的直接 API 回退</string>
|
||||
<string name="active_section_optional_api_fallback">可选 Direct API</string>
|
||||
<string name="active_section_api_not_required">此连接使用 Hermes Dashboard 时不需要配置。</string>
|
||||
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
|
||||
@@ -4451,7 +4459,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">直接 API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">设置此手机使用的 Dashboard 和 Gateway 地址。私有 LAN 与 Tailscale 路由可使用 HTTP 或 HTTPS;公共路由必须使用 HTTPS。</string>
|
||||
<string name="dashboard_address_editor_title">网关地址</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes hat diesen Fehler gemeldet. Die App wechselt Routen oder Modelle nicht automatisch.</string>
|
||||
<string name="chat_failure_copy_details">Details kopieren</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API-Fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Einstellungen öffnen</string>
|
||||
<string name="chat_connect_hermes">Hermes verbinden</string>
|
||||
<string name="chat_try_demo">Demo ausprobieren</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">Mit deinem gehosteten Agenten verbinden</string>
|
||||
<string name="cw_server_vps_title">Remote-Gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard-Adresse eingeben</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und API-Fallback sind optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und Direct API sind optional.</string>
|
||||
<string name="cw_cloud_entry_title">Mit von Nous gehostetem Hermes verbinden</string>
|
||||
<string name="cw_cloud_entry_description">Gib die im Nous Portal angezeigte Agentenadresse ein. Nach dem Auffinden von Hermes meldest du dich sicher an.</string>
|
||||
<string name="cw_cloud_agent_name">Agentenadresse</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 oder http://dein-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Von Chat und Sitzungen verwendete Hermes-API — bei reinen Hosts werden API-Port 8642 und http:// angenommen (Dashboard-Port 9119 wird separat abgeleitet)</string>
|
||||
<string name="cw_scan_message">Dieses LAN wird nach Hermes-Dashboard/API durchsucht…</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für den optionalen direkten API-Fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für eine explizite Direct-API-Verbindung.</string>
|
||||
<string name="cw_pair_relay_section">Relay koppeln (optional)</string>
|
||||
<string name="cw_pair_relay_for">Relay mit %1$s koppeln</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Füge dieser gespeicherten Hermes-Verbindung die optionale Relay-Erweiterung hinzu. Dadurch wird kein Server hinzugefügt oder ersetzt.</string>
|
||||
@@ -621,6 +621,11 @@
|
||||
<string name="changelog_state_collapsed">Eingeklappt</string>
|
||||
<string name="changelog_installed">Installiert</string>
|
||||
<string name="changelog_also_improved">Außerdem verbessert</string>
|
||||
<string name="changelog_highlights">Highlights</string>
|
||||
<string name="changelog_added">Hinzugefügt</string>
|
||||
<string name="changelog_improved">Verbessert</string>
|
||||
<string name="changelog_fixed">Behoben</string>
|
||||
<string name="changelog_compatibility">Kompatibilität</string>
|
||||
<string name="changelog_toast_also">Außerdem: %1$s</string>
|
||||
<string name="changelog_view_all">Alle anzeigen</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -631,6 +636,10 @@
|
||||
<item quantity="one">%1$d Fehlerbehebung</item>
|
||||
<item quantity="other">%1$d Fehlerbehebungen</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="one">%1$d Verbesserung</item>
|
||||
<item quantity="other">%1$d Verbesserungen</item>
|
||||
</plurals>
|
||||
|
||||
<!-- DiagnosticsScreen -->
|
||||
<string name="diag_title">Diagnose</string>
|
||||
@@ -697,7 +706,7 @@
|
||||
<string name="settings_hermes_management">Hermes-Verwaltung</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard-Funktionen: Skills, Cron, MCP, Profile, Modelle</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, API-Fallback, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, Direct API, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_voice_mode">Sprachmodus</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard-Sprache, Echtzeit-Relay-Optionen, Anbieter</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -808,11 +817,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Verborgene \"[System: …]\"-Markierungen des Servers anzeigen (Modell-/Personawechsel). Aus entspricht Desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming-Endpunkt</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: wählt anhand der Serverfunktionen den besten Pfad. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: Standardverbindungen verwenden Gateway; reine API-Verbindungen verwenden Direct API. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (Live-Denken über den Dashboard-WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (Chat über /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (Chat über ausdrücklich gestreamte /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; weicht bei Nichtverfügbarkeit pro Durchlauf auf SSE aus.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; bei Nichtverfügbarkeit bleibt dieser Chat auf Gateway und bietet Anmeldung oder Wiederholen an.</string>
|
||||
<string name="chat_settings_sessions_desc">Sitzungen: Hermes-eigener Endpunkt /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-kompatibles SSE über /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Durchläufe: nur verwenden, wenn dein Server /v1/runs direkt streamt.</string>
|
||||
@@ -3407,7 +3416,7 @@
|
||||
<string name="whats_new_full_history">Vollständigen Verlauf anzeigen</string>
|
||||
<string name="whats_new_no_notes">Keine Versionshinweise verfügbar</string>
|
||||
<string name="whats_new_title">Neuigkeiten</string>
|
||||
<string name="whats_new_subtitle">Highlights der neuesten Version</string>
|
||||
<string name="whats_new_subtitle">Highlights und vollständige Versionsdetails</string>
|
||||
<!-- Localization guardrail additions for current dev surfaces -->
|
||||
<string name="bridge_notification_auto_disabled_title">Zeitgesteuerter Bildschirmzugriff abgelaufen</string>
|
||||
<string name="bridge_notification_auto_disabled_body">Bildschirmprüfung und -steuerung sind nach Inaktivität aus. Andere Berechtigungen bleiben unverändert.</string>
|
||||
@@ -3511,7 +3520,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Nicht erreichbar</string>
|
||||
<string name="active_section_no_fallback_routes">Noch keine Ausweichrouten</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Füge optional eine API-Route für direkten Chat-Ausweichbetrieb und Netzwerkwechsel hinzu.</string>
|
||||
<string name="active_section_add_api_fallback">Ausweichroute hinzufügen</string>
|
||||
<string name="active_section_add_api_fallback">Direct-API-Route hinzufügen</string>
|
||||
<string name="active_section_security_authentication">Authentifizierung</string>
|
||||
<string name="active_section_dashboard_session">Dashboard-Sitzung</string>
|
||||
<string name="active_section_credential_storage">Anmeldedatenspeicher</string>
|
||||
@@ -3575,7 +3584,7 @@
|
||||
<string name="cw_timeline_authenticated">Authentifizierung bestätigt</string>
|
||||
<string name="cw_timeline_ready">Verbindung bereit</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage und Voice können dieses Dashboard verwenden</string>
|
||||
<string name="active_section_optional_api_fallback">Optionaler direkter API-Fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optionale Direct API</string>
|
||||
<string name="active_section_api_not_required">Nicht erforderlich, wenn diese Verbindung das Hermes Dashboard verwendet.</string>
|
||||
<string name="active_section_where_api_key">Wo erhalte ich diesen Schlüssel?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY wird auf deinem Hermes-Server erstellt und nicht von dieser App bereitgestellt. Konfiguriere ihn nur für den optionalen API-Server, der einen verwendbaren Schlüssel verlangt, und gib hier denselben Wert ein.</string>
|
||||
@@ -4526,7 +4535,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Lege die Dashboard- und Gateway-Adresse für dieses Telefon fest. Private LAN- und Tailscale-Routen dürfen HTTP oder HTTPS verwenden; öffentliche Routen erfordern HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Gateway-Adresse</string>
|
||||
@@ -4543,7 +4552,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. API-Fallback und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. Direct API und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -556,6 +556,11 @@
|
||||
<string name="changelog_state_collapsed">Contraído</string>
|
||||
<string name="changelog_installed">Instalada</string>
|
||||
<string name="changelog_also_improved">También mejorado</string>
|
||||
<string name="changelog_highlights">Destacados</string>
|
||||
<string name="changelog_added">Añadido</string>
|
||||
<string name="changelog_improved">Mejorado</string>
|
||||
<string name="changelog_fixed">Corregido</string>
|
||||
<string name="changelog_compatibility">Compatibilidad</string>
|
||||
<string name="changelog_toast_also">También: %1$s</string>
|
||||
<string name="changelog_view_all">Ver todo</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -566,6 +571,10 @@
|
||||
<item quantity="one">%1$d corrección</item>
|
||||
<item quantity="other">%1$d correcciones</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="one">%1$d mejora</item>
|
||||
<item quantity="other">%1$d mejoras</item>
|
||||
</plurals>
|
||||
<string name="diag_title">Diagnóstico</string>
|
||||
<string name="diag_back">Atrás</string>
|
||||
<string name="diag_status">Estado</string>
|
||||
@@ -733,11 +742,11 @@
|
||||
<string name="chat_settings_debug">Depurar</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostrar los marcadores \" ocultos del servidor [Sistema: …]\" (cambios de modelo / personalidad). Off coincide con el escritorio/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Punto final de transmisión</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: elige la mejor ruta según lo que expone su servidor. Actualmente usando: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: las conexiones estándar usan Gateway; las conexiones solo API usan API directa. En uso: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamiento en vivo a través del tablero WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chatear vía /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chatear a través de /v1/runs transmitido explícitamente)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos en el panel WebSocket (/api/ws): lo que utiliza la aplicación de escritorio. Requiere el inicio de sesión en Administrar; vuelve a SSE por turno cuando no está disponible.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos por el WebSocket del panel (/api/ws), como en la aplicación de escritorio. Requiere iniciar sesión en Administrar; si no está disponible, este chat permanece en Gateway y ofrece iniciar sesión o reintentar.</string>
|
||||
<string name="chat_settings_sessions_desc">Sesiones: Hermes-nativo /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatible con OpenAI a través de /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Ejecuciones: utilícelo solo cuando su servidor transmita /v1/runs directamente.</string>
|
||||
@@ -3071,7 +3080,7 @@
|
||||
<string name="whats_new_full_history">Ver historial completo</string>
|
||||
<string name="whats_new_no_notes">No hay notas de versión disponibles</string>
|
||||
<string name="whats_new_title">¿Qué hay de nuevo?</string>
|
||||
<string name="whats_new_subtitle">Novedades de la última versión</string>
|
||||
<string name="whats_new_subtitle">Destacados y detalles completos de la versión</string>
|
||||
<string name="bridge_notification_auto_disabled_title">Acceso de pantalla temporizado vencido</string>
|
||||
<string name="bridge_notification_auto_disabled_body">La inspección y el control de pantalla están desactivados tras la inactividad. Los demás permisos no cambian.</string>
|
||||
<string name="bridge_notification_control_title">El agente Hermes tiene control del dispositivo.</string>
|
||||
@@ -4217,7 +4226,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API directa</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Define la dirección del Dashboard y Gateway que usará este teléfono. Las rutas privadas LAN y Tailscale pueden usar HTTP o HTTPS; las rutas públicas requieren HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Dirección del gateway</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes からこのエラーが報告されました。アプリがルートやモデルを自動的に切り替えることはありません。</string>
|
||||
<string name="chat_failure_copy_details">詳細をコピー</string>
|
||||
<string name="chat_failure_route_gateway">ゲートウェイ</string>
|
||||
<string name="chat_failure_route_api">API フォールバック</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">設定を開く</string>
|
||||
<string name="chat_connect_hermes">Hermesを接続してください</string>
|
||||
<string name="chat_try_demo">デモを試してみる</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">ホスト済みエージェントに接続します</string>
|
||||
<string name="cw_server_vps_title">リモートゲートウェイ</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard アドレスを入力</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と API フォールバックは任意です。</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と Direct API は任意です。</string>
|
||||
<string name="cw_cloud_entry_title">Nous ホスト版 Hermes に接続</string>
|
||||
<string name="cw_cloud_entry_description">Nous Portal に表示されるエージェントのアドレスを入力してください。Hermes が見つかった後、安全にサインインします。</string>
|
||||
<string name="cw_cloud_agent_name">エージェントのアドレス</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 または http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API チャットとセッションで使用されます — API ポート 8642 および http:// はベア ホストとして想定されます (ダッシュボードの 9119 は個別に派生します)</string>
|
||||
<string name="cw_scan_message">この LAN をスキャンして Hermes ダッシュボード/API を探しています…</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは任意の直接 API フォールバックでのみ使います。</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは明示的な Direct API 接続でのみ使います。</string>
|
||||
<string name="cw_pair_relay_section">Relay のペア (オプション)</string>
|
||||
<string name="cw_pair_relay_section_desc">すでに Relay プラグインを実行していますか?ここでペアリングすると、ターミナル、Bridge、およびチャネル許可が有効になります。</string>
|
||||
<string name="cw_pair_relay_url_label">Relay URL</string>
|
||||
@@ -621,6 +621,11 @@
|
||||
<string name="changelog_state_collapsed">折りたたみ済み</string>
|
||||
<string name="changelog_installed">インストール済み</string>
|
||||
<string name="changelog_also_improved">その他の改善</string>
|
||||
<string name="changelog_highlights">ハイライト</string>
|
||||
<string name="changelog_added">追加</string>
|
||||
<string name="changelog_improved">改善</string>
|
||||
<string name="changelog_fixed">修正</string>
|
||||
<string name="changelog_compatibility">互換性</string>
|
||||
<string name="changelog_toast_also">その他: %1$s</string>
|
||||
<string name="changelog_view_all">すべて表示</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -629,6 +634,9 @@
|
||||
<plurals name="changelog_fix_count">
|
||||
<item quantity="other">%1$d 件の修正</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="other">%1$d 件の改善</item>
|
||||
</plurals>
|
||||
|
||||
<!-- DiagnosticsScreen -->
|
||||
<string name="diag_title">診断</string>
|
||||
@@ -695,7 +703,7 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">ダッシュボードの機能: スキル、cron、MCP、プロファイル、モデル</string>
|
||||
<string name="settings_chat">チャット</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、API フォールバック、ツール表示、メッセージ長</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、Direct API、ツール表示、メッセージ長</string>
|
||||
<string name="settings_voice_mode">ボイスモード</string>
|
||||
<string name="settings_voice_mode_desc">ダッシュボード音声、リアルタイムRelayオプション、プロバイダー</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -806,11 +814,11 @@
|
||||
<string name="chat_settings_debug">デバッグ</string>
|
||||
<string name="chat_settings_show_system_messages_desc">サーバーの非表示の「[システム: …]」マーカーを表示します (モデル/パーソナリティの変更)。 Off はデスクトップ/TUI に一致します。</string>
|
||||
<string name="chat_settings_streaming_endpoint">ストリーミングエンドポイント</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: サーバーが公開しているものに基づいて最適なパスを選択します。現在使用しているもの:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: 標準接続は Gateway、API 専用接続は Direct API を使用します。現在使用中: </string>
|
||||
<string name="chat_settings_gateway_suffix">(ダッシュボード WebSocket を介したライブ思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(/v1/chat/completions 経由でチャット)</string>
|
||||
<string name="chat_settings_runs_suffix">(明示的にストリーミングされた /v1/runs を介してチャットします)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード上のライブ思考 + 豊富なツール イベント WebSocket (/api/ws) — デスクトップ アプリが使用するもの。管理サインインが必要です。利用できない場合はターンごとに SSE に戻ります。</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード WebSocket(/api/ws)経由のライブ思考と豊富なツールイベント — デスクトップアプリと同じ経路です。管理へのサインインが必要です。利用できない場合もこのチャットは Gateway のまま、サインインまたは再試行を案内します。</string>
|
||||
<string name="chat_settings_sessions_desc">セッション: Hermes-native /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">チャット: /v1/chat/completions 経由の OpenAI 互換の SSE。</string>
|
||||
<string name="chat_settings_runs_desc">実行: サーバーが /v1/runs を直接ストリーミングする場合にのみ使用します。</string>
|
||||
@@ -3415,7 +3423,7 @@
|
||||
<string name="whats_new_full_history">全履歴を表示</string>
|
||||
<string name="whats_new_no_notes">リリースノートはありません</string>
|
||||
<string name="whats_new_title">新機能</string>
|
||||
<string name="whats_new_subtitle">最新リリースのハイライト</string>
|
||||
<string name="whats_new_subtitle">ハイライトと完全なリリース詳細</string>
|
||||
<!-- Localization guardrail additions for current dev surfaces -->
|
||||
<string name="bridge_notification_auto_disabled_title">時間制限付き画面アクセスの期限切れ</string>
|
||||
<string name="bridge_notification_auto_disabled_body">操作がなかったため、画面の検査と操作をオフにしました。他の許可は変更されません。</string>
|
||||
@@ -3506,7 +3514,7 @@
|
||||
<string name="active_section_dashboard_unreachable">接続できません</string>
|
||||
<string name="active_section_no_fallback_routes">フォールバックルートはまだありません</string>
|
||||
<string name="active_section_no_fallback_routes_desc">直接チャットのフォールバックやネットワーク切り替え用に、任意の API ルートを追加できます。</string>
|
||||
<string name="active_section_add_api_fallback">フォールバックルートを追加</string>
|
||||
<string name="active_section_add_api_fallback">Direct API ルートを追加</string>
|
||||
<string name="active_section_security_authentication">認証</string>
|
||||
<string name="active_section_dashboard_session">Dashboard セッション</string>
|
||||
<string name="active_section_credential_storage">認証情報ストレージ</string>
|
||||
@@ -3572,7 +3580,7 @@
|
||||
<string name="cw_timeline_authenticated">認証を確認済み</string>
|
||||
<string name="cw_timeline_ready">接続準備完了</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage、Voice でこの Dashboard を使用できます</string>
|
||||
<string name="active_section_optional_api_fallback">任意の直接 API フォールバック</string>
|
||||
<string name="active_section_optional_api_fallback">任意の Direct API</string>
|
||||
<string name="active_section_api_not_required">この接続が Hermes Dashboard を使用する場合は必要ありません。</string>
|
||||
<string name="active_section_where_api_key">このキーはどこで入手しますか?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY は Hermes サーバー上で作成します。このアプリからは発行されません。任意の API サーバーを有効にする場合のみ設定します。このサーバーには使用可能なキーが必要です。同じ値をここに入力してください。</string>
|
||||
@@ -4522,7 +4530,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">この端末で使う Dashboard と Gateway のアドレスを設定します。プライベート LAN と Tailscale ルートは HTTP または HTTPS を使用でき、公開ルートには HTTPS が必要です。</string>
|
||||
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
|
||||
@@ -4539,7 +4547,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。API フォールバックと Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。Direct API と Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -292,7 +292,7 @@
|
||||
<string name="cw_cloud_subtitle">Подключитесь к своему размещённому агенту</string>
|
||||
<string name="cw_server_vps_title">Удалённый шлюз</string>
|
||||
<string name="cw_server_vps_subtitle">Введите адрес Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и резервный API необязательны.</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и Direct API необязательны.</string>
|
||||
<string name="cw_cloud_entry_title">Подключиться к Hermes на хостинге Nous</string>
|
||||
<string name="cw_cloud_entry_description">Введите адрес агента, указанный в Nous Portal. После обнаружения Hermes вы безопасно войдёте в систему.</string>
|
||||
<string name="cw_cloud_agent_name">Адрес агента</string>
|
||||
@@ -392,7 +392,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 или http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API Гермеса, используемый Чатом и сеансами — порт API 8642 и http:// предполагаются для голых хостов (порт 9119 панели управления выводится отдельно)</string>
|
||||
<string name="cw_scan_message">Сканирование этой локальной сети на предмет панели управления/API Гермеса…</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для необязательного резервного копирования прямого API.</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для явно настроенного Direct API.</string>
|
||||
<string name="cw_pair_relay_section">Сопряжение Relay (необязательно)</string>
|
||||
<string name="cw_pair_relay_for">Сопряжение Relay с %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Добавьте необязательное расширение Relay к этому сохранённому подключению Гермеса. Это не добавляет и не заменяет сервер.</string>
|
||||
@@ -599,6 +599,11 @@
|
||||
<string name="changelog_state_collapsed">Свернуто</string>
|
||||
<string name="changelog_installed">Установлено</string>
|
||||
<string name="changelog_also_improved">Также улучшено</string>
|
||||
<string name="changelog_highlights">Основное</string>
|
||||
<string name="changelog_added">Добавлено</string>
|
||||
<string name="changelog_improved">Улучшено</string>
|
||||
<string name="changelog_fixed">Исправлено</string>
|
||||
<string name="changelog_compatibility">Совместимость</string>
|
||||
<string name="changelog_toast_also">Также: %1$s</string>
|
||||
<string name="changelog_view_all">Показать все</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -613,6 +618,12 @@
|
||||
<item quantity="many">%1$d исправлений</item>
|
||||
<item quantity="other">%1$d исправления</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="one">%1$d улучшение</item>
|
||||
<item quantity="few">%1$d улучшения</item>
|
||||
<item quantity="many">%1$d улучшений</item>
|
||||
<item quantity="other">%1$d улучшения</item>
|
||||
</plurals>
|
||||
<string name="diag_title">Диагностика</string>
|
||||
<string name="diag_back">Назад</string>
|
||||
<string name="diag_status">Статус</string>
|
||||
@@ -671,7 +682,7 @@
|
||||
<string name="settings_hermes_management">Управление Гермесом</string>
|
||||
<string name="settings_hermes_management_desc">Функции панели управления: навыки, cron, MCP, профили, модели</string>
|
||||
<string name="settings_chat">Чат</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, резервный API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, Direct API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_voice_mode">Режим голоса</string>
|
||||
<string name="settings_voice_mode_desc">Голос панели управления, опции Relay в реальном времени, поставщики</string>
|
||||
<string name="settings_threads">Потоки</string>
|
||||
@@ -780,11 +791,11 @@
|
||||
<string name="chat_settings_debug">Отладка</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Показывать скрытые сервером маркеры \"[Система: …]\" (изменения модели / личности). Выключено соответствует рабочему столу/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Потоковая конечная точка</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: выбирает лучший путь на основе того, что ваш сервер предоставляет. В настоящее время используется:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: стандартные подключения используют Gateway; подключения только к API используют Direct API. Сейчас используется: </string>
|
||||
<string name="chat_settings_gateway_suffix">(живое мышление через WebSocket панели управления)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(чат через /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix">(чат через явно потоковые /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Шлюз: живое мышление + богатые события инструментов через WebSocket панели управления (/api/ws) — что использует настольное приложение. Требует входа в систему Manage; возвращается к SSE на каждый ход, когда недоступен.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: живое мышление и расширенные события инструментов через WebSocket панели управления (/api/ws), как в настольном приложении. Требует входа в Manage; если Gateway недоступен, чат остается на нем и предлагает войти или повторить попытку.</string>
|
||||
<string name="chat_settings_sessions_desc">Сессии: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Чат: совместимый с OpenAI SSE через /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Запуски: используйте только когда ваш сервер напрямую потоковые /v1/runs.</string>
|
||||
@@ -916,7 +927,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Недоступно</string>
|
||||
<string name="active_section_no_fallback_routes">Нет резервных маршрутов</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Добавьте локальный адрес, Tailscale или публичный адрес, чтобы сохранить это соединение доступным при изменении сетей.</string>
|
||||
<string name="active_section_add_api_fallback">Добавить резервный маршрут</string>
|
||||
<string name="active_section_add_api_fallback">Добавить маршрут Direct API</string>
|
||||
<string name="active_section_security_authentication">Аутентификация</string>
|
||||
<string name="active_section_dashboard_session">Сессия панели управления</string>
|
||||
<string name="active_section_credential_storage">Хранение учетных данных</string>
|
||||
@@ -931,7 +942,7 @@
|
||||
<string name="active_section_route_selection">Выбор маршрута</string>
|
||||
<string name="active_section_automatic">Автоматически</string>
|
||||
<string name="active_section_api_access">Доступ к API</string>
|
||||
<string name="active_section_optional_api_fallback">Дополнительный прямой резерв API</string>
|
||||
<string name="active_section_optional_api_fallback">Необязательный Direct API</string>
|
||||
<string name="active_section_api_not_required">Не требуется, если это соединение использует панель управления Гермесом.</string>
|
||||
<string name="active_section_where_api_key">Где взять это?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY создается на вашем сервере Гермеса; он не предоставляется этим приложением. Настройте его только при включении дополнительного сервера API, который требует рабочего ключа, затем введите то же значение здесь.</string>
|
||||
@@ -3275,7 +3286,7 @@
|
||||
<string name="whats_new_full_history">Просмотреть полную историю</string>
|
||||
<string name="whats_new_no_notes">Примечания к выпуску недоступны</string>
|
||||
<string name="whats_new_title">Что нового</string>
|
||||
<string name="whats_new_subtitle">Последние обновления</string>
|
||||
<string name="whats_new_subtitle">Основное и полный список изменений</string>
|
||||
<string name="bridge_notification_auto_disabled_title">Временный доступ к экрану истек</string>
|
||||
<string name="bridge_notification_auto_disabled_body">Просмотр и управление экраном отключены после бездействия. Другие разрешения не изменены.</string>
|
||||
<string name="bridge_notification_control_title">Агент Гермес имеет управление устройством</string>
|
||||
@@ -4263,7 +4274,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Укажите адрес Dashboard и Gateway для этого телефона. Частные маршруты LAN и Tailscale могут использовать HTTP или HTTPS; публичным маршрутам требуется HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Адрес шлюза</string>
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes reported this error. The app won’t switch routes or models automatically.</string>
|
||||
<string name="chat_failure_copy_details">Copy details</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Open Settings</string>
|
||||
<string name="chat_connect_hermes">Connect Hermes</string>
|
||||
<string name="chat_try_demo">Try the demo</string>
|
||||
@@ -315,7 +315,7 @@
|
||||
<string name="cw_cloud_subtitle">Connect to your hosted agent</string>
|
||||
<string name="cw_server_vps_title">Remote gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Enter its Dashboard address</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and API fallback are optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and Direct API are optional.</string>
|
||||
<string name="cw_cloud_entry_title">Connect to Nous-hosted Hermes</string>
|
||||
<string name="cw_cloud_entry_description">Enter the agent address shown in Nous Portal. You’ll sign in securely after Hermes is found.</string>
|
||||
<string name="cw_cloud_agent_name">Agent address</string>
|
||||
@@ -387,7 +387,7 @@
|
||||
<string name="cw_back">Back</string>
|
||||
<string name="cw_connect_button">Connect</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the preferred upstream auth path; the API key remains the Android Chat fallback.</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the standard upstream auth path; an API key is only for explicit Direct API connections.</string>
|
||||
<string name="cw_api_url_label">API server URL or host</string>
|
||||
<string name="cw_api_key_label">API key</string>
|
||||
<string name="cw_api_key_placeholder">Value from API_SERVER_KEY</string>
|
||||
@@ -419,7 +419,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 or http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API used by Chat and sessions — API port 8642 and http:// assumed for bare hosts (the dashboard\'s 9119 is derived separately)</string>
|
||||
<string name="cw_scan_message">Scanning this LAN for Hermes dashboard/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for the optional direct API fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for optional Direct API compatibility.</string>
|
||||
<string name="cw_pair_relay_section">Pair Relay (optional)</string>
|
||||
<string name="cw_pair_relay_for">Pair Relay with %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Add the optional Relay extension to this saved Hermes connection. This does not add or replace a server.</string>
|
||||
@@ -666,6 +666,11 @@
|
||||
<string name="changelog_state_collapsed">Collapsed</string>
|
||||
<string name="changelog_installed">Installed</string>
|
||||
<string name="changelog_also_improved">Also improved</string>
|
||||
<string name="changelog_highlights">Highlights</string>
|
||||
<string name="changelog_added">Added</string>
|
||||
<string name="changelog_improved">Improved</string>
|
||||
<string name="changelog_fixed">Fixed</string>
|
||||
<string name="changelog_compatibility">Compatibility</string>
|
||||
<string name="changelog_toast_also">Also: %1$s</string>
|
||||
<string name="changelog_view_all">View all</string>
|
||||
<plurals name="changelog_additional_feature_count">
|
||||
@@ -676,6 +681,10 @@
|
||||
<item quantity="one">%1$d fix</item>
|
||||
<item quantity="other">%1$d fixes</item>
|
||||
</plurals>
|
||||
<plurals name="changelog_improvement_count">
|
||||
<item quantity="one">%1$d improvement</item>
|
||||
<item quantity="other">%1$d improvements</item>
|
||||
</plurals>
|
||||
|
||||
<!-- DiagnosticsScreen -->
|
||||
<string name="diag_title">Diagnostics</string>
|
||||
@@ -742,7 +751,7 @@
|
||||
<string name="settings_hermes_management">Hermes management</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard features: skills, cron, MCP, profiles, models</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, API fallback, tool display, message length</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, Direct API, tool display, message length</string>
|
||||
<string name="settings_voice_mode">Voice mode</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard voice, realtime relay options, providers</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -863,11 +872,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Show the server\'s hidden \"[System: …]\" markers (model / personality changes). Off matches the desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming endpoint</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: picks the best path based on what your server exposes. Currently using: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: standard connections use Gateway; API-only connections use Direct API. Currently using: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (live thinking via the dashboard WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat via /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat via explicitly streamed /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; falls back to SSE per turn when unavailable.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; when unavailable, this chat stays on Gateway and offers sign-in or retry.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessions: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-compatible SSE via /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use only when your server streams /v1/runs directly.</string>
|
||||
@@ -1018,14 +1027,14 @@
|
||||
<string name="active_section_primary_dashboard">Primary Dashboard</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
<string name="dashboard_gateway_secure_origin">Authenticated Dashboard address</string>
|
||||
<string name="dashboard_gateway_oidc_explainer">The configured route may be LAN, Tailscale, or public. Hermes owns the OIDC callback; Android does not require a second sign-in address.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. API fallback and Relay extensions are optional.</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. Direct API and Relay extensions are optional.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
@@ -1045,7 +1054,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Not reachable</string>
|
||||
<string name="active_section_no_fallback_routes">No fallback routes yet</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Add a LAN, Tailscale, or public address to keep this connection available when networks change.</string>
|
||||
<string name="active_section_add_api_fallback">Add fallback route</string>
|
||||
<string name="active_section_add_api_fallback">Add Direct API route</string>
|
||||
<string name="active_section_security_authentication">Authentication</string>
|
||||
<string name="active_section_dashboard_session">Dashboard session</string>
|
||||
<string name="active_section_credential_storage">Credential storage</string>
|
||||
@@ -1060,7 +1069,7 @@
|
||||
<string name="active_section_route_selection">Route selection</string>
|
||||
<string name="active_section_automatic">Automatic</string>
|
||||
<string name="active_section_api_access">API access</string>
|
||||
<string name="active_section_optional_api_fallback">Optional direct API fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optional Direct API</string>
|
||||
<string name="active_section_api_not_required">Not required when this connection uses the Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Where do I get this?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY is created on your Hermes server; it is not supplied by this app. Configure it only when you enable the optional API server, which requires a usable key, then enter the same value here.</string>
|
||||
@@ -3781,7 +3790,7 @@
|
||||
<string name="whats_new_full_history">View full history</string>
|
||||
<string name="whats_new_no_notes">No release notes available</string>
|
||||
<string name="whats_new_title">What\u0027s new</string>
|
||||
<string name="whats_new_subtitle">Latest release highlights</string>
|
||||
<string name="whats_new_subtitle">Highlights and complete release details</string>
|
||||
<!-- Localization guardrail additions for current dev surfaces -->
|
||||
<string name="bridge_notification_auto_disabled_title">Timed screen access expired</string>
|
||||
<string name="bridge_notification_auto_disabled_body">Screen inspection and control are off after being idle. Other grants are unchanged.</string>
|
||||
@@ -4246,7 +4255,7 @@
|
||||
<string name="voice_overlay_notification_body">Microphone access remains available while Hermes is over another app.</string>
|
||||
<string name="voice_overlay_notification_stop">Stop voice</string>
|
||||
<string name="conn_info_profile_api_key_title">Profile API key</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex API fallback. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex Direct API route. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_stored">A key is stored</string>
|
||||
<string name="conn_info_profile_api_key_not_stored">No key stored</string>
|
||||
<string name="conn_info_profile_api_key_save">Save key</string>
|
||||
|
||||
@@ -38,6 +38,7 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiServerConfigured)
|
||||
assertTrue(connection.capabilities.relayConfigured)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,6 +54,20 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiChatFallbackAvailable)
|
||||
assertFalse(connection.capabilities.relayFeaturesAvailable)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedDashboardOwnsAutoChatEvenWhenApiIsAlsoConfigured() {
|
||||
val connection = connection(
|
||||
dashboardUrl = "https://hermes.example.com",
|
||||
apiServerUrl = "https://api.example.com",
|
||||
relayUrl = "",
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, connection.automaticChatTransport)
|
||||
assertEquals(SessionTransport.GATEWAY, connection.chatTransportForPreference("auto"))
|
||||
assertEquals(SessionTransport.SSE, connection.chatTransportForPreference("sessions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -184,7 +184,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Tls, result.level)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -203,7 +203,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Plain, result.level)
|
||||
assertEquals(SurfaceUseState.Unavailable, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedParentAuthStoreTest {
|
||||
@Test
|
||||
fun `new credential policy accepts strong pins and passwords`() {
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("12345".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("123456".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("1234567".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("short".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("long passphrase".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret(" ".repeat(8).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("x".repeat(65).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enrollment stores only salted PBKDF2 verifiers and returns six word recovery phrase`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
|
||||
val enrollment = store.enroll(
|
||||
"correct horse".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').size)
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').distinct().size)
|
||||
assertTrue(raw.contains("PBKDF2WithHmacSHA256"))
|
||||
assertTrue(raw.contains("\"iterations\":1"))
|
||||
assertFalse(raw.contains("correct horse"))
|
||||
assertFalse(raw.contains(enrollment.recoveryPhrase))
|
||||
assertTrue(raw.contains("\"credentialType\":\"Password\""))
|
||||
assertTrue(raw.contains("\"recoveryFormat\":\"WordPhrase\""))
|
||||
val salts = Regex("\"(?:parentSalt|recoverySalt)\":\"([^\"]+)\"")
|
||||
.findAll(raw).map { it.groupValues[1] }.toList()
|
||||
assertEquals(2, salts.size)
|
||||
assertNotEquals(salts[0], salts[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `production enrollment records 310000 rounds`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 310_000,
|
||||
)
|
||||
|
||||
store.enroll("production-strength".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(
|
||||
dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting]
|
||||
.orEmpty().contains("\"iterations\":310000"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `verification is fail closed when missing or corrupt`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Missing, store.verify("anything".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "not-json" }
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Corrupt, store.verify("anything".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unsupported or weakened records fail closed`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"version\":1", "\"version\":2")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"iterations\":1", "\"iterations\":0")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `records created before credential type selection remain verifiable`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val current = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
val legacy = current
|
||||
.replace(Regex(",\"credentialType\":\"Password\""), "")
|
||||
.replace(Regex(",\"recoveryFormat\":\"WordPhrase\""), "")
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = legacy }
|
||||
|
||||
assertEquals(SupervisedParentCredentialType.Legacy, store.credentialTypeFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enroll cannot replace an existing or corrupt credential`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("first password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("first password".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "corrupt" }
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `authenticated clear removes credential and disables policies without losing settings`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val authStore = fastStore(dataStore)
|
||||
val policyStore = SupervisedModeStore.forTesting(dataStore)
|
||||
authStore.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
policyStore.setPolicy(
|
||||
"connection-a",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(attachments = false, voice = true),
|
||||
),
|
||||
)
|
||||
policyStore.setPolicy(
|
||||
"connection-b",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "coder",
|
||||
visibility = SupervisedVisibility(showTimestamps = true),
|
||||
),
|
||||
)
|
||||
val beforeA = policyStore.policyFlow("connection-a").first()
|
||||
val beforeB = policyStore.policyFlow("connection-b").first()
|
||||
|
||||
authStore.clearCredentialAndDisablePolicies().getOrThrow()
|
||||
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, authStore.statusFlow.first())
|
||||
assertEquals(beforeA.copy(enabled = false), policyStore.policyFlow("connection-a").first())
|
||||
assertEquals(beforeB.copy(enabled = false), policyStore.policyFlow("connection-b").first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed attempts persist across store recreation and backoff expires by clock`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val clock = AtomicLong(1_000L)
|
||||
var store = fastStore(dataStore, clock)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
repeat(4) {
|
||||
assertTrue(store.verify("wrong password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
}
|
||||
val fifth = store.verify("wrong password".toCharArray())
|
||||
assertEquals(SupervisedParentAuthResult.Throttled(30_000L), fifth)
|
||||
|
||||
store = fastStore(dataStore, clock)
|
||||
assertEquals(
|
||||
SupervisedParentAuthResult.Throttled(30_000L),
|
||||
store.verify("parent password".toCharArray()),
|
||||
)
|
||||
clock.addAndGet(30_001L)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `concurrent store instances preserve the capped failure sequence`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val stores = List(5) { fastStore(dataStore) }
|
||||
stores.first().enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
val results = stores.map { store -> async { store.verify("wrong password".toCharArray()) } }.awaitAll()
|
||||
|
||||
assertEquals(4, results.count { it is SupervisedParentAuthResult.Invalid })
|
||||
assertEquals(1, results.count { it == SupervisedParentAuthResult.Throttled(30_000L) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `change requires the current credential and rotates recovery`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.change("wrong".toCharArray(), "new password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("old password".toCharArray()))
|
||||
|
||||
val replacement = store.change(
|
||||
"old password".toCharArray(),
|
||||
"654321".toCharArray(),
|
||||
SupervisedParentCredentialType.Pin,
|
||||
).getOrThrow()
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertTrue(store.verify("old password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("654321".toCharArray()))
|
||||
assertEquals(SupervisedParentCredentialType.Pin, store.credentialTypeFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery is normalized one time and rotates both secrets`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val lowerSpaced = original.recoveryPhrase.uppercase().replace("-", " ").toCharArray()
|
||||
|
||||
val replacement = store.resetWithRecoveryPhrase(
|
||||
lowerSpaced,
|
||||
"new password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("new password".toCharArray()))
|
||||
assertTrue(
|
||||
store.resetWithRecoveryPhrase(
|
||||
original.recoveryPhrase.toCharArray(),
|
||||
"another password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
)
|
||||
.isFailure,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fastStore(
|
||||
dataStore: DataStore<Preferences>,
|
||||
clock: AtomicLong = AtomicLong(1_000L),
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 1,
|
||||
minimumAcceptedIterations = 1,
|
||||
nowMillis = clock::get,
|
||||
)
|
||||
}
|
||||
|
||||
private class InMemoryParentAuthDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow(emptyPreferences())
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
|
||||
val updated = transform(state.value)
|
||||
state.value = updated
|
||||
return updated
|
||||
}
|
||||
}
|
||||
@@ -1530,6 +1530,86 @@ class ChatHandlerTest {
|
||||
assertTrue(handler.messages.value.single().attachments.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_preservesCompletedGeneratedImageUntilMarkerPersists() {
|
||||
handler.addPlaceholderMessage(
|
||||
ChatMessage(
|
||||
id = "assistant-live-image",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "Here is the generated image.",
|
||||
timestamp = 1L,
|
||||
attachments = listOf(
|
||||
Attachment(
|
||||
contentType = "image/png",
|
||||
content = "",
|
||||
fileName = "generated.png",
|
||||
relayToken = "/tmp/generated.png",
|
||||
state = AttachmentState.LOADED,
|
||||
),
|
||||
),
|
||||
toolCalls = listOf(
|
||||
ToolCall(
|
||||
id = "image-call",
|
||||
name = "willow_create_image",
|
||||
args = null,
|
||||
result = "success",
|
||||
success = true,
|
||||
isComplete = true,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-server-image",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Here is the generated image."),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val message = handler.messages.value.single()
|
||||
assertEquals("assistant-server-image", message.id)
|
||||
assertEquals("assistant-live-image", message.uiKey)
|
||||
assertEquals(1, message.attachments.size)
|
||||
assertEquals("generated.png", message.attachments.single().fileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_doesNotCarryUnownedAssistantInboundImage() {
|
||||
handler.addPlaceholderMessage(
|
||||
ChatMessage(
|
||||
id = "assistant-live-generic",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "A generic fetched image.",
|
||||
timestamp = 1L,
|
||||
attachments = listOf(
|
||||
Attachment(
|
||||
contentType = "image/png",
|
||||
content = "",
|
||||
fileName = "generic.png",
|
||||
relayToken = "generic-token",
|
||||
state = AttachmentState.LOADED,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-server-generic",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("A generic fetched image."),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue(handler.messages.value.single().attachments.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_consumesOutboundAttachmentOncePerDuplicateContent() {
|
||||
// Two identical-text sends, only the first with an attachment: the
|
||||
|
||||
+8
-1
@@ -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())
|
||||
}
|
||||
|
||||
|
||||
@@ -804,6 +804,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
callbackDispatcher: (block: () -> Unit) -> Unit = { it() },
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) = GatewayChatClient(
|
||||
@@ -825,6 +826,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
)
|
||||
|
||||
private fun awaitCondition(
|
||||
@@ -862,6 +864,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) {
|
||||
client.shutdown()
|
||||
@@ -870,6 +873,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
ticketTimeoutMs = ticketTimeoutMs,
|
||||
)
|
||||
}
|
||||
@@ -4928,6 +4932,85 @@ class GatewayChatClientTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting status extends watchdog until a later completion`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 1_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact once", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(500)
|
||||
|
||||
assertTrue("normal idle watchdog fired during compaction: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting heartbeats rearm watchdog beyond one compaction lease`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 200L, compactingTimeoutMs = 500L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact with heartbeats", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
repeat(3) {
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(300)
|
||||
}
|
||||
|
||||
assertTrue("compaction lease was not rearmed: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non compacting status keeps the ordinary watchdog`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 2_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "ordinary status", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "process") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue("ordinary watchdog never fired", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue("expected a stream error from the watchdog", r.errors.isNotEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
harness.awaitRpc("session.interrupt")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog fires when events stop flowing`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 500L)
|
||||
|
||||
+41
-7
@@ -5,9 +5,8 @@ import org.junit.Test
|
||||
|
||||
/**
|
||||
* Resolution matrix for [resolveStreamingEndpointPreference] — the gateway
|
||||
* tier sits above the capability-preferred SSE endpoint for "auto". An
|
||||
* unresolved cold-start probe remains on Gateway until it produces a
|
||||
* definitive fallback verdict.
|
||||
* tier is a stable owner for standard "auto" conversations. API capability
|
||||
* ordering applies only to true API-only compatibility connections.
|
||||
*/
|
||||
class GatewayEndpointResolutionTest {
|
||||
|
||||
@@ -44,28 +43,63 @@ class GatewayEndpointResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto falls back after a definitive non-ready verdict`() {
|
||||
fun `standard auto remains gateway owned after auth expiry or outage`() {
|
||||
listOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
).forEach { availability ->
|
||||
assertEquals(
|
||||
"expected SSE fallback for $availability",
|
||||
"sessions",
|
||||
"expected Gateway affinity for $availability",
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference("auto", availability, fullCaps),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto fallback respects capability ordering`() {
|
||||
fun `API-only auto respects capability ordering`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"completions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
portableOnlyCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `standard auto does not consult API health when gateway is unavailable`() {
|
||||
assertEquals(
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.Unreachable,
|
||||
ServerCapabilities.DISCONNECTED,
|
||||
gatewayOwned = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `manual API selection remains explicit compatibility mode`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"sessions",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+6
-2
@@ -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("Reliable routes").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")
|
||||
}
|
||||
|
||||
+75
@@ -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)
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -61,9 +61,11 @@ class WhatsNewToastScreenshotTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Reliable routes").assertExists()
|
||||
compose.onNodeWithText("Also: 2 features · 10 fixes").assertExists()
|
||||
compose.onNodeWithText("delegated-agent previews, safer voice and sessions…").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("Reliable routes").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("Reliable routes").performTouchInput { swipeLeft(durationMillis = 300L) }
|
||||
compose.onNodeWithText("Connections, delegated work, Git, and voice")
|
||||
.performTouchInput { swipeLeft(durationMillis = 300L) }
|
||||
compose.mainClock.advanceTimeBy(300L)
|
||||
|
||||
assertTrue(dismissed)
|
||||
|
||||
@@ -196,6 +196,39 @@ class RelayAppStatusTest {
|
||||
assertEquals(ChatRuntimeStatus.Connecting, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard sign-out is not masked by a reachable sibling API`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = "https://host.ts.net:9119",
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
streamingEndpoint = "sessions",
|
||||
conversationOwner = com.hermesandroid.relay.data.SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(ChatRuntimeStatus.Unavailable, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy API-only connection remains connected compatibility chat`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = null,
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `committed pair target stays ready while public inventory catches up`() {
|
||||
assertTrue(
|
||||
@@ -392,7 +425,7 @@ class RelayAppStatusTest {
|
||||
}
|
||||
|
||||
private fun connected(path: ChatTransportPath) =
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = path == ChatTransportPath.ApiSse)
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = false)
|
||||
|
||||
private fun connection(
|
||||
dashboardUrl: String? = null,
|
||||
|
||||
@@ -40,32 +40,50 @@ class SupervisedNavigationPolicyTest {
|
||||
@Test fun `parent access or ordinary mode permits add gateway`() {
|
||||
assertTrue(mayStartAddConnection(supervisedEnabled = true, parentAccessUnlocked = true))
|
||||
assertTrue(mayStartAddConnection(supervisedEnabled = false, parentAccessUnlocked = false))
|
||||
assertFalse(
|
||||
mayStartAddConnection(
|
||||
supervisedEnabled = false,
|
||||
parentAccessUnlocked = true,
|
||||
activeTargetId = "already-started",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `locked add gateway action has no side effects`() {
|
||||
var navigated = false
|
||||
var prepared = false
|
||||
val started = runAddConnectionAction(
|
||||
@Test fun `locked add gateway action performs no allocation or side effects`() {
|
||||
val actions = mutableListOf<String>()
|
||||
val target = runAddConnectionAction(
|
||||
supervisedEnabled = true,
|
||||
parentAccessUnlocked = false,
|
||||
navigateToPair = { navigated = true },
|
||||
prepareConnection = { prepared = true },
|
||||
)
|
||||
assertFalse(started)
|
||||
assertFalse(navigated)
|
||||
assertFalse(prepared)
|
||||
}
|
||||
|
||||
@Test fun `allowed add gateway action navigates before preparation`() {
|
||||
val actions = mutableListOf<String>()
|
||||
val started = runAddConnectionAction(
|
||||
supervisedEnabled = true,
|
||||
parentAccessUnlocked = true,
|
||||
activeTargetId = null,
|
||||
allocateTarget = { actions += "allocate"; "target" },
|
||||
recordTarget = { actions += "record" },
|
||||
navigateToPair = { actions += "navigate" },
|
||||
prepareConnection = { actions += "prepare" },
|
||||
)
|
||||
assertTrue(started)
|
||||
assertTrue(actions == listOf("navigate", "prepare"))
|
||||
assertTrue(target == null)
|
||||
assertTrue(actions.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun `allowed add gateway action records target before navigation and preparation`() {
|
||||
val actions = mutableListOf<String>()
|
||||
val target = runAddConnectionAction(
|
||||
supervisedEnabled = true,
|
||||
parentAccessUnlocked = true,
|
||||
activeTargetId = null,
|
||||
allocateTarget = { actions += "allocate"; "target" },
|
||||
recordTarget = { actions += "record:$it" },
|
||||
navigateToPair = { actions += "navigate:$it" },
|
||||
prepareConnection = { actions += "prepare:$it" },
|
||||
)
|
||||
assertTrue(target == "target")
|
||||
assertTrue(
|
||||
actions == listOf(
|
||||
"allocate",
|
||||
"record:target",
|
||||
"navigate:target",
|
||||
"prepare:target",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `supervised redirect waits until the navigation graph has a route`() {
|
||||
@@ -75,6 +93,7 @@ class SupervisedNavigationPolicyTest {
|
||||
assertTrue(isSupervisedRouteContentAllowed(true, false, Screen.Chat.route))
|
||||
assertTrue(shouldRedirectSupervisedRoute(true, false, Screen.AdvancedSettings.route))
|
||||
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.AdvancedSettings.route))
|
||||
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.ConnectionsSettings.route))
|
||||
assertFalse(shouldRedirectSupervisedRoute(true, true, Screen.AdvancedSettings.route))
|
||||
assertTrue(isSupervisedRouteContentAllowed(true, true, Screen.AdvancedSettings.route))
|
||||
}
|
||||
@@ -153,25 +172,23 @@ class SupervisedNavigationPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
|
||||
@Test fun `first enable requires configured policy and successful app parent credential`() {
|
||||
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
|
||||
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = false,
|
||||
deviceCredentialConfirmed = true,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = true,
|
||||
deviceCredentialConfirmed = false,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,26 +37,25 @@ class ChangelogParserTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parsesCuratedHighlightAndImprovements() {
|
||||
fun parsesCompleteReleaseAndDerivesToastDigest() {
|
||||
val raw = """
|
||||
{
|
||||
"schema": 2,
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.2.0",
|
||||
"title": "A useful release",
|
||||
"date": "2026-06-20",
|
||||
"highlight": {
|
||||
"title": "The main reason to care",
|
||||
"summary": "A plain-language explanation.",
|
||||
"bullets": ["a", "b", "c"]
|
||||
},
|
||||
"improvements": ["d", "e"],
|
||||
"toastDigest": {
|
||||
"additionalFeatureCount": 1,
|
||||
"fixCount": 2,
|
||||
"preview": ["Secondary feature", "Important fix"]
|
||||
},
|
||||
"summary": "A plain-language explanation.",
|
||||
"changes": [
|
||||
{"id": "new-one", "kind": "added", "title": "New one",
|
||||
"summary": "Use the new thing.", "highlight": true},
|
||||
{"id": "better-one", "kind": "improved", "title": "Better one",
|
||||
"summary": "The old thing is easier."},
|
||||
{"id": "fixed-one", "kind": "fixed", "title": "Fixed one",
|
||||
"summary": "The broken thing works."}
|
||||
],
|
||||
"compatibility": ["Existing connections keep working."],
|
||||
"playNotes": "Concise Play copy."
|
||||
}
|
||||
]
|
||||
@@ -64,17 +63,41 @@ class ChangelogParserTest {
|
||||
""".trimIndent()
|
||||
|
||||
val entry = ChangelogStore.parse(raw).versions.single()
|
||||
val digest = entry.resolvedToastDigest()
|
||||
|
||||
assertEquals("The main reason to care", entry.highlight?.title)
|
||||
assertEquals("A plain-language explanation.", entry.highlight?.summary)
|
||||
assertEquals(listOf("a", "b", "c"), entry.highlight?.bullets)
|
||||
assertEquals(listOf("d", "e"), entry.improvements)
|
||||
assertEquals(1, entry.toastDigest?.additionalFeatureCount)
|
||||
assertEquals(2, entry.toastDigest?.fixCount)
|
||||
assertEquals(listOf("Secondary feature", "Important fix"), entry.toastDigest?.preview)
|
||||
assertEquals("A plain-language explanation.", entry.summary)
|
||||
assertEquals(listOf("New one"), entry.highlightedChanges().map { it.title })
|
||||
assertEquals(0, digest?.additionalFeatureCount)
|
||||
assertEquals(1, digest?.improvementCount)
|
||||
assertEquals(1, digest?.fixCount)
|
||||
assertEquals(listOf("Better one", "Fixed one"), digest?.preview)
|
||||
assertEquals(listOf("Existing connections keep working."), entry.compatibility)
|
||||
assertEquals("Concise Play copy.", entry.playNotes)
|
||||
assertEquals("v1.2.0 · 2026-06-20", entry.versionLine())
|
||||
assertEquals(listOf("The main reason to care", "Also improved"), entry.toGroups().map { it.header })
|
||||
assertEquals(
|
||||
listOf("Highlights", "Improved", "Fixed", "Compatibility"),
|
||||
entry.toGroups().map { it.header },
|
||||
)
|
||||
assertEquals(3, entry.toGroups().sumOf { it.bullets.size } - entry.compatibility.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeReleaseRendersEveryChangeOnce() {
|
||||
val entry = ChangelogVersion(
|
||||
version = "1.2.0",
|
||||
title = "Complete notes",
|
||||
summary = "Everything users need to know.",
|
||||
changes = listOf(
|
||||
ChangelogChange("a", CHANGE_KIND_ADDED, "First", "First detail", highlight = true),
|
||||
ChangelogChange("b", CHANGE_KIND_FIXED, "Second", "Second detail"),
|
||||
),
|
||||
)
|
||||
|
||||
val rendered = entry.toGroups().flatMap { it.bullets }
|
||||
|
||||
assertEquals(2, rendered.size)
|
||||
assertEquals(1, rendered.count { it.startsWith("First") })
|
||||
assertEquals(1, rendered.count { it.startsWith("Second") })
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
@@ -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"),
|
||||
)
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.SupervisedParentCredentialType
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@Config(qualifiers = "w400dp-h900dp-432dpi")
|
||||
class SupervisedParentAuthDialogsTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `choice presents mutually exclusive pin and password routes`() {
|
||||
var selected: SupervisedParentCredentialType? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
CredentialChoiceScreen("Choose parent access", "Pick one.") { selected = it }
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Use a PIN").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Pin, selected) }
|
||||
compose.onNodeWithText("Use a password").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Password, selected) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pin auth uses six positions and a dedicated numeric keypad`() {
|
||||
var submitted: String? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
PinEntryScreen("Parent PIN", "Enter your 6-digit PIN.", false, null, { submitted = it })
|
||||
}
|
||||
}
|
||||
|
||||
(0..9).forEach { compose.onNodeWithText(it.toString()).assertIsDisplayed() }
|
||||
compose.onNodeWithContentDescription("Delete digit").assertIsDisplayed()
|
||||
(1..6).forEach { compose.onNodeWithText(it.toString()).performClick() }
|
||||
compose.runOnIdle { assertEquals("123456", submitted) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password setup uses distinct password fields and visibility controls`() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme { PasswordSetupScreen(false, null, {}) }
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Create a parent password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Confirm password").assertIsDisplayed()
|
||||
compose.onAllNodesWithContentDescription("Show password").assertCountEquals(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery phrase handoff exposes sharing copy and cleanup guidance`() {
|
||||
var shares = 0
|
||||
var copies = 0
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
SupervisedParentEnrollment("maple-river-lantern-copper-sparrow-moon"),
|
||||
onShare = { shares += 1 },
|
||||
onCopy = { copies += 1 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("maple-river-lantern", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("copper-sparrow-moon", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").assertIsDisplayed()
|
||||
compose.onNodeWithText("Copy phrase").assertIsDisplayed()
|
||||
compose.onNodeWithText("delete the message or saved copy", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").performClick()
|
||||
compose.onNodeWithText("Copy phrase").performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, shares)
|
||||
assertEquals(1, copies)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -38,12 +40,54 @@ class ChatReadinessTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready with reachable API when Gateway is unavailable`() {
|
||||
fun `ready with reachable API for API-only owner`() {
|
||||
assertTrue(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
chatOwner = SessionTransport.SSE,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reachable API cannot make a Gateway-owned chat ready`() {
|
||||
assertFalse(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
chatOwner = SessionTransport.GATEWAY,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `eager status owner resolves from backing preference before public alias`() {
|
||||
val connection = Connection(
|
||||
id = "dashboard-owner",
|
||||
label = "Dashboard",
|
||||
apiServerUrl = "https://hermes.example.com:8642",
|
||||
relayUrl = "",
|
||||
tokenStoreKey = "test-key",
|
||||
dashboardUrl = "https://hermes.example.com:9119",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
SessionTransport.GATEWAY,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = null,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SessionTransport.SSE,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = SessionTransport.SSE,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,23 +28,25 @@ class ChatRuntimeStatusTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `API SSE ready is healthy fallback when gateway is unavailable`() {
|
||||
fun `API SSE ready is healthy only for an API-owned conversation`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready API fallback wins while gateway is still connecting`() {
|
||||
fun `ready sibling API cannot mask gateway auth expiry`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Unavailable,
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Connecting,
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.Gateway,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -63,6 +65,7 @@ class ChatRuntimeStatusTest {
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Connecting,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+187
-1
@@ -195,7 +195,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(STORED_SESSION_ID, failure?.sessionId)
|
||||
assertEquals(ChatFailureRoute.GATEWAY, failure?.route)
|
||||
assertTrue(failure?.recoverable == true)
|
||||
assertTrue(failure?.rawError.orEmpty().contains("no API fallback"))
|
||||
assertTrue(failure?.rawError.orEmpty().contains("belongs to the Hermes Dashboard"))
|
||||
assertEquals("Retry this after reconnect", handler.lastSentMessage.value)
|
||||
assertTrue(handler.messages.value.isEmpty())
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Session), 1).single()
|
||||
@@ -238,6 +238,63 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals("gateway", diagnostic.endpointRole)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
|
||||
DiagnosticsLog.clear()
|
||||
apiMessageRequestCount.set(0)
|
||||
val owner = Profile(name = "owner", model = "model-a", description = "Owner")
|
||||
val requestedProfiles = mutableListOf<String?>()
|
||||
val sessionRefreshes = AtomicInteger(0)
|
||||
val signInRequests = AtomicInteger(0)
|
||||
viewModel.setSelectedProfileProvider { owner }
|
||||
viewModel.setSessionProfileNameProvider { owner.name }
|
||||
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
|
||||
requestedProfiles += profileName
|
||||
assertEquals(STORED_SESSION_ID, sessionId)
|
||||
Result.failure(
|
||||
DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized"),
|
||||
)
|
||||
}
|
||||
viewModel.setProfileSessionLister { profileName ->
|
||||
assertEquals(owner.name, profileName)
|
||||
sessionRefreshes.incrementAndGet()
|
||||
Result.success(emptyList())
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
|
||||
|
||||
viewModel.sendMessage("Keep this local prompt")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "Keep this local answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "Keep this local answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition {
|
||||
!handler.isStreaming.value &&
|
||||
signInRequests.get() == 1 &&
|
||||
sessionRefreshes.get() >= 1
|
||||
}
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local prompt" })
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local answer" })
|
||||
assertEquals(listOf(owner.name), requestedProfiles)
|
||||
assertEquals(0, apiMessageRequestCount.get())
|
||||
assertFalse(viewModel.steerableTurn.value)
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
|
||||
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
|
||||
assertTrue(diagnostic.suggestion.orEmpty().contains("Sign in to Dashboard"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingRequiredProfileHistoryLoaderFailsClosedWithoutApiRead() {
|
||||
DiagnosticsLog.clear()
|
||||
@@ -1593,6 +1650,39 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(gatewayClient.hasActiveTurn())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnedConversationDoesNotDispatchToReachableApiWhenGatewayIsMissing() {
|
||||
viewModel.streamingEndpoint = "gateway"
|
||||
viewModel.updateGatewayClient(null)
|
||||
val apiRequestsBefore = apiCompletionsRequestCount.get()
|
||||
|
||||
viewModel.sendMessage("Keep this turn on Victor")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
assertEquals(apiRequestsBefore, apiCompletionsRequestCount.get())
|
||||
assertTrue(handler.messages.value.none { it.role == MessageRole.ASSISTANT })
|
||||
assertEquals(
|
||||
ChatFailureRoute.GATEWAY,
|
||||
viewModel.chatFailure.value?.route,
|
||||
)
|
||||
assertEquals(STORED_SESSION_ID, handler.currentSessionId.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun boundGatewaySessionRejectsAResolverTransportFlipUntilExplicitNewChat() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
|
||||
viewModel.streamingEndpoint = "sessions"
|
||||
|
||||
assertEquals("gateway", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.GATEWAY, viewModel.conversationBinding.value.transport)
|
||||
|
||||
viewModel.createNewChat()
|
||||
|
||||
assertEquals("sessions", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.SSE, viewModel.conversationBinding.value.transport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayRichCardActionStaysOnGatewayInsteadOfDrainingThroughSessionsApi() {
|
||||
viewModel.sseFallbackEndpoint = "sessions"
|
||||
@@ -2746,6 +2836,92 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveredCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
|
||||
DiagnosticsLog.clear()
|
||||
apiMessageRequestCount.set(0)
|
||||
val checkpointStore = MemoryCheckpointStore(
|
||||
ChatTurnCheckpoint(
|
||||
contextKey = PROFILE_CONTEXT,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
liveSessionId = "live-resumed",
|
||||
transport = "gateway",
|
||||
user = ChatTurnUserCheckpoint("prior-user", "Recovered prompt", 1L),
|
||||
assistant = ChatTurnAssistantCheckpoint(
|
||||
id = "prior-assistant",
|
||||
content = "Recovered partial",
|
||||
timestamp = 2L,
|
||||
),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
startedAt = 2L,
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
val requestedProfiles = mutableListOf<String?>()
|
||||
val sessionRefreshes = AtomicInteger(0)
|
||||
val signInRequests = AtomicInteger(0)
|
||||
var failHistory = false
|
||||
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
|
||||
requestedProfiles += profileName
|
||||
assertEquals(STORED_SESSION_ID, sessionId)
|
||||
if (failHistory) {
|
||||
Result.failure(
|
||||
DashboardHttpException(
|
||||
401,
|
||||
"Session failed - HTTP 401: {\"reason\":\"session_expired\"}",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
Result.success(emptyList())
|
||||
}
|
||||
}
|
||||
viewModel.setProfileSessionLister { profileName ->
|
||||
assertNull(profileName)
|
||||
sessionRefreshes.incrementAndGet()
|
||||
Result.success(emptyList())
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
|
||||
gatewayHarness.recoveryRunning = true
|
||||
gatewayHarness.recoveryAssistant = "Recovered partial"
|
||||
viewModel.setChatTurnCheckpointStore(checkpointStore)
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
|
||||
viewModel.prewarmGateway()
|
||||
gatewayHarness.awaitRpc("session.activate")
|
||||
awaitCondition {
|
||||
handler.messages.value.any { it.id == "prior-assistant" && it.isStreaming }
|
||||
}
|
||||
failHistory = true
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "Recovered answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition {
|
||||
!handler.isStreaming.value &&
|
||||
signInRequests.get() == 1 &&
|
||||
sessionRefreshes.get() >= 1
|
||||
}
|
||||
assertTrue(handler.messages.value.any {
|
||||
it.id == "prior-assistant" &&
|
||||
it.content.contains("Recovered answer") &&
|
||||
!it.isStreaming
|
||||
})
|
||||
assertTrue(requestedProfiles.isNotEmpty())
|
||||
assertTrue(requestedProfiles.all { it == null })
|
||||
assertEquals(0, apiMessageRequestCount.get())
|
||||
assertFalse(viewModel.steerableTurn.value)
|
||||
awaitCondition { checkpointStore.checkpoint == null }
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
|
||||
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lateCanceledCompletionDrainsBeforeImmediateNextTurn() {
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
@@ -3641,6 +3817,16 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { it.first == "session.active_list" } > baselineActiveList
|
||||
}
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.Working
|
||||
}
|
||||
gatewayHarness.activeSessionListPayload = activeSessionPayload("waiting")
|
||||
viewModel.requestSessionActivityRefresh()
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.NeedsInput
|
||||
}
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = "desktop-answer",
|
||||
|
||||
+37
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -112,4 +113,40 @@ class ConversationBindingControllerTest {
|
||||
assertEquals("alpha", controller.state.value.profileName)
|
||||
assertEquals("a1", controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnerSurvivesSessionClearAndLifecycleReconciliation() {
|
||||
controller.forceGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = "20260831_120000_deadbeef",
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
controller.startFreshDraft()
|
||||
controller.reconcileGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = null,
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.state.value.transport)
|
||||
assertNull(controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitApiSessionKeepsItsCompatibilityOwner() {
|
||||
controller.openExplicit(
|
||||
contextKey = "c::default",
|
||||
profileName = null,
|
||||
sessionId = "api_1788192000_deadbeef",
|
||||
displayProfile = null,
|
||||
lockedProfileToken = null,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
controller.switchSession(null)
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
}
|
||||
}
|
||||
|
||||
+24
-2
@@ -5,6 +5,7 @@ import com.hermesandroid.relay.data.SessionLiveStatus
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSession
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSessionStatus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -40,14 +41,35 @@ class SessionActivityResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unscoped stored id stays unresolved even when bounded directory looks unique`() {
|
||||
fun `unique selected passive owner resolves without a runtime binding`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Starting,
|
||||
status = GatewayActiveSessionStatus.Waiting,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
directory = setOf(alpha, unique),
|
||||
currentOwner = unique,
|
||||
)
|
||||
|
||||
assertEquals(unique, result.runtimes.single().owner)
|
||||
assertEquals(SessionLiveStatus.Waiting, result.runtimes.single().status)
|
||||
assertFalse(result.ambiguous)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unique passive owner for a nonselected session stays unresolved`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Working,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
|
||||
+5
-2
@@ -118,7 +118,7 @@ class ProfileControllerLockTest {
|
||||
// (no gateway probe gating) — keeps refreshLastSessionForProfile from
|
||||
// bailing early on Unknown.
|
||||
streamingEndpointProvider = { streamingEndpoint },
|
||||
gatewayAvailabilityProvider = { gatewayAvailability },
|
||||
automaticTransportProvider = { SessionTransport.GATEWAY },
|
||||
setLastSessionId = { lastSessionIds += it },
|
||||
legacyDefaultSessionId = { null },
|
||||
rebuildChatApiClient = { },
|
||||
@@ -208,13 +208,16 @@ class ProfileControllerLockTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoUnknownRestoresGatewayBucketUntilDefinitiveFallback() {
|
||||
fun autoGatewayOwnerDoesNotChangeRestoreBucketAfterOutage() {
|
||||
streamingEndpoint = "auto"
|
||||
gatewayAvailability = GatewayAvailability.Unknown
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
gatewayAvailability = GatewayAvailability.Unreachable
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
streamingEndpoint = "sessions"
|
||||
assertEquals(SessionTransport.SSE, controller.activeSessionTransport())
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+121
-22
@@ -59,8 +59,9 @@
|
||||
### 3. Chat via Direct API, Not Relay Proxy
|
||||
|
||||
**Status:** Superseded as the standard route by ADR 38 (2026-07-18). Direct API
|
||||
chat remains the automatic fallback and an advanced headless compatibility
|
||||
mode; the upstream Dashboard/Gateway is now the primary connection surface.
|
||||
chat remains an explicit API-only/headless compatibility mode; the upstream
|
||||
Dashboard/Gateway is now the primary connection surface. ADR 71 removes
|
||||
availability-driven fallback between their non-interchangeable session stores.
|
||||
|
||||
**Decision:** ~~Chat channel proxies through the relay to the WebAPI.~~ **Updated:** Chat now connects directly from the Android app to the Hermes API Server via HTTP/SSE. The relay server is only used for bridge and terminal channels.
|
||||
|
||||
@@ -2210,7 +2211,7 @@ starting connectivity does not itself require or imply a tool grant.
|
||||
|
||||
## ADR 38 — Dashboard/Gateway is the primary Android connection surface
|
||||
|
||||
**Status:** Accepted (2026-07-18).
|
||||
**Status:** Superseded by ADR 71 for chat fallback semantics (2026-08-31).
|
||||
|
||||
**Context.** Android originally treated the API server URL and bearer key as the
|
||||
identity and prerequisite for every saved connection. The app later gained the
|
||||
@@ -2226,7 +2227,7 @@ stable identity independent of endpoint URLs.
|
||||
- **Dashboard/Gateway is standard.** It owns primary chat, dashboard auth,
|
||||
sessions, Manage, and Vanilla Hermes voice against unmodified upstream Hermes.
|
||||
- **API server is optional.** When discovered or explicitly configured, it is an
|
||||
automatic chat fallback and an advanced headless compatibility surface. Its
|
||||
API-only chat and advanced headless compatibility surface. Its
|
||||
bearer is requested and validated only when that endpoint is configured.
|
||||
- **Relay is optional.** It adds pairing, terminal, bridge/device control,
|
||||
media, notification companion, enhanced voice, and desktop tooling. It never
|
||||
@@ -2238,15 +2239,14 @@ stable identity independent of endpoint URLs.
|
||||
profile's authoritative Hermes session database without proxying chat.
|
||||
Native Gateway lifecycle events take precedence, and absence of the optional
|
||||
route silently restores the vanilla behavior.
|
||||
- **Readiness is capability-based.** Chat, Manage, Voice, API fallback, and
|
||||
- **Readiness is capability-based.** Chat, Manage, Voice, Direct API, and
|
||||
Relay extensions report their own state. A missing optional endpoint does not
|
||||
mark the whole connection unhealthy.
|
||||
- **Routing is automatic.** Chat prefers Dashboard/Gateway and falls back to the
|
||||
API server only when configured and usable. Users choose a transport only in
|
||||
advanced diagnostics or compatibility settings, not during normal setup.
|
||||
Endpoint discovery may advertise a conventional API route, but does not enable
|
||||
that optional fallback unless the connection has persisted API configuration;
|
||||
cold-start state remains unconfigured until that persisted value is hydrated.
|
||||
- **Routing is owner-bound.** Standard Chat uses Dashboard/Gateway. Legacy
|
||||
API-only records and explicit advanced compatibility selections use the API
|
||||
server. Live authentication or reachability never changes an open chat's
|
||||
owner. Endpoint discovery may advertise a conventional API route, but does
|
||||
not enable it for a Dashboard-owned conversation.
|
||||
|
||||
**Product flow.** Normal onboarding asks for one Hermes address, discovers the
|
||||
Dashboard/Gateway, authenticates through its supported provider, and finishes
|
||||
@@ -2260,8 +2260,8 @@ An API endpoint or Relay can be added later without recreating the connection.
|
||||
|
||||
- Dashboard-only Hermes connections can chat, manage, use sessions, and use
|
||||
Vanilla Hermes voice without fake API credentials.
|
||||
- API outages do not degrade a healthy Gateway session; they remove only the
|
||||
fallback capability.
|
||||
- API outages do not degrade a healthy Gateway session; they affect only an
|
||||
explicit Direct API compatibility conversation.
|
||||
- Connection storage, diagnostics, backup/restore, route discovery, pairing,
|
||||
and profile/session scoping must tolerate independently absent endpoints.
|
||||
- Legacy API-only users keep working, but public documentation no longer teaches
|
||||
@@ -3777,7 +3777,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
|
||||
@@ -3789,9 +3789,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
|
||||
@@ -3805,6 +3806,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,
|
||||
@@ -3877,8 +3909,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
|
||||
@@ -4039,9 +4091,10 @@ The precedence is:
|
||||
revalidated. A failed or unsupported live refresh is **Unavailable**.
|
||||
|
||||
Android resolves each active-list row through exact foreground or detached
|
||||
ownership already held by that client, or explicit profile metadata if a
|
||||
future upstream sends it. A bounded REST directory never proves that a durable
|
||||
`session_key` is globally unique. Ambiguous or unresolved rows apply no status.
|
||||
ownership already held by that client, explicit profile metadata if a future
|
||||
upstream sends it, or the currently selected passive session when its durable
|
||||
`session_key` has exactly one owner in the current connection directory.
|
||||
Duplicate same-id owners across profiles remain ambiguous and apply no status.
|
||||
Resolved rows from a partial snapshot may update their exact owners, but they
|
||||
cannot infer absence. A missing row clears stale live state for a scope only
|
||||
when the successful process-wide snapshot was complete and every relevant row
|
||||
@@ -4081,7 +4134,10 @@ paths, which concern exact Android-owned checkpoints.
|
||||
and saved-session selection establish only the shared Gateway socket. They use
|
||||
profile-scoped REST history plus process-wide `session.active_list`; while an
|
||||
unowned row with the selected durable id is live, Android performs bounded
|
||||
history refreshes and one final read after settlement. These observer paths send
|
||||
history refreshes and one final read after settlement. When that durable id has
|
||||
exactly one owner in the current connection directory, the same read-only row
|
||||
also projects Working or Waiting for the selected session; duplicate cross-profile
|
||||
owners remain neutral. These observer paths send
|
||||
no `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`.
|
||||
Exact Android-owned checkpoints retain `session.activate` with durable-resume
|
||||
fallback, and explicit send or session-config actions may resume because the user
|
||||
@@ -4197,3 +4253,46 @@ large profile database remains a separate certification gate.
|
||||
`apps/desktop/src/app/session/hooks/use-session-list-actions.ts`. Android wiring
|
||||
lives in `DashboardApiClient`, `HermesRuntimeBinder`, `ChatScreen`, and
|
||||
`ChatViewModel`.
|
||||
|
||||
---
|
||||
|
||||
## ADR 71 — Android conversations are transport-affine
|
||||
|
||||
**Status:** Accepted (2026-08-31).
|
||||
|
||||
**Context.** Standard Android Chat now follows the upstream Dashboard/Gateway
|
||||
model, but Auto resolution still changed a live conversation to API-server
|
||||
sessions, completions, or runs when Dashboard sign-in expired or Gateway became
|
||||
unavailable. The optional API server could therefore make Chat appear connected
|
||||
and even complete a local turn while Dashboard session/history reads returned
|
||||
401. Gateway and API-server session ids belong to different databases and are
|
||||
not interchangeable, especially for named profile homes. Reachability of one
|
||||
surface is not authority to mutate a conversation owned by the other.
|
||||
|
||||
**Decision.** Every Android conversation binding includes its transport owner
|
||||
alongside connection, profile, and session identity.
|
||||
|
||||
- A standard saved connection's Auto owner is Gateway and does not change with
|
||||
Gateway availability. `SignInRequired` requests Dashboard sign-in; a temporary
|
||||
failure preserves transcript, draft, attachments, queued destination, and
|
||||
retry state.
|
||||
- Missing Gateway clients and failed Gateway preflight never dispatch the turn
|
||||
through API-server SSE. Attachments, voice sends, slash commands, queued
|
||||
turns, session restore, and profile switches all use the same bound owner.
|
||||
- A legacy connection with API configuration but no persisted Dashboard route
|
||||
remains API-only. Existing `api_…` records retain their API session slot.
|
||||
Advanced manual Direct API selection is explicit and takes effect for a new
|
||||
chat; it does not migrate an existing Gateway transcript or session.
|
||||
- Cold-start restoration selects the persisted session slot from the saved
|
||||
connection/manual preference, not a transient auth or health verdict.
|
||||
Dashboard history remains authoritative for Gateway bindings; API session
|
||||
history remains authoritative only for API-owned bindings.
|
||||
- User-facing Connected and ordinary route labels describe the active binding
|
||||
owner. A reachable sibling endpoint cannot mask sign-out or failure. Exact
|
||||
endpoint names remain available in advanced diagnostics/compatibility UI.
|
||||
|
||||
**Consequences.** Sessions, runs, and completions remain useful for legitimate
|
||||
API-only/headless clients, compatibility testing, and existing API records, but
|
||||
they are no longer automatic recovery for standard Chat. Users retry or sign in
|
||||
without losing local work, named profiles cannot cross databases silently, and
|
||||
readiness reflects the conversation that will actually receive the next turn.
|
||||
|
||||
+1
-1
@@ -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 |
|
||||
|
||||
@@ -68,6 +68,7 @@ the upstream contract identifiers it depends on.
|
||||
|---|---|
|
||||
| `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 |
|
||||
| `compaction_status` | Compaction status is client-visible before terminal completion and may repeat as a heartbeat |
|
||||
| `rapid_tools_interims` | Rapid chunks, reasoning, tool activity, and interim assistant boundaries |
|
||||
| `queued_follow_up` | Two explicitly owned turns and ordered queue drainage |
|
||||
| `scope_rejection_inputs` | Exact, foreign, and unscoped event inputs |
|
||||
@@ -112,8 +113,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
|
||||
@@ -127,7 +128,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> `
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -26,9 +26,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -48,7 +48,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -61,9 +61,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -85,9 +85,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -96,7 +96,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -109,9 +109,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -120,7 +120,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -135,7 +135,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8c6660316b05c0ae69e9f4fbdb468e52c2c011bfafe24f090fcdb6862c2f836b",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -148,9 +148,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
}
|
||||
|
||||
+24
-39
@@ -637,22 +637,22 @@
|
||||
<span class="branch-label yes">Yes — manual</span>
|
||||
<div class="fnode term">
|
||||
<div class="t">Use it verbatim</div>
|
||||
<div class="s">Manual pick wins. Per-turn fallback still applies if it can't serve.</div>
|
||||
<div class="s">Manual selection owns a new chat; existing bindings do not migrate.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No — "auto"</span>
|
||||
<div class="fnode dec" style="width:100%">
|
||||
<div class="t">gateway == Ready?</div>
|
||||
<div class="t">Saved connection owner?</div>
|
||||
</div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">Yes</span>
|
||||
<span class="branch-label yes">Standard</span>
|
||||
<div class="fnode gateway"><div class="t">→ "gateway"</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No</span>
|
||||
<span class="branch-label no">API-only</span>
|
||||
<div class="fnode sse">
|
||||
<div class="t">capabilities<br>.preferredChatEndpoint()</div>
|
||||
<div class="s">sessions › completions › runs</div>
|
||||
@@ -672,40 +672,26 @@
|
||||
</div>
|
||||
<div class="conn arrow"></div>
|
||||
<div class="fnode dec">
|
||||
<div class="t">Voice interface-context present AND endpoint == gateway?</div>
|
||||
<div class="t">Bound owner == "gateway"?</div>
|
||||
</div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">Yes</span>
|
||||
<div class="fnode sse">
|
||||
<div class="t">Force SSE fallback</div>
|
||||
<div class="s">gateway can't carry system_message</div>
|
||||
</div>
|
||||
<span class="branch-label no">Direct API owner</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(endpoint)</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">effectiveEndpoint == "gateway"?</div></div>
|
||||
<span class="branch-label yes">Gateway owner</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">gateway client live?</div></div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">SSE pick</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(endpoint)</div></div>
|
||||
<span class="branch-label no">null</span>
|
||||
<div class="fnode term"><div class="t">Preserve + Retry</div><div class="s">sign in or reconnect; no owner change</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">gateway</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">gateway client live?</div></div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">null</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(fallback)</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">yes</span>
|
||||
<div class="fnode gateway"><div class="t">gateway.sendTurn()</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<span class="branch-label yes">yes</span>
|
||||
<div class="fnode gateway"><div class="t">gateway.sendTurn()</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -725,26 +711,25 @@
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">onPreflightFailure</span>
|
||||
<div class="fnode sse term">
|
||||
<div class="t">dispatchSse(fallback)</div>
|
||||
<div class="s">nothing started server-side → safe to retry on SSE</div>
|
||||
<div class="fnode term">
|
||||
<div class="t">Preserve + Retry</div>
|
||||
<div class="s">nothing started server-side; conversation stays Gateway-owned</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="callout std">
|
||||
<strong>SSE fallback resolution.</strong> When the chosen SSE endpoint is
|
||||
<code>sessions</code> but there's no session yet, it downgrades to stateless
|
||||
<code>completions</code> for that first turn — there's nothing to stream against
|
||||
otherwise. <span class="ref">resolveSseFallback()</span>
|
||||
<strong>Transport affinity.</strong> Gateway and Direct API sessions live in
|
||||
different stores. Sign-in expiry or route loss never authorizes Android to
|
||||
resubmit the turn through another owner.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ───────────────────────── 5 ───────────────────────── -->
|
||||
<section id="inputs">
|
||||
<div class="section-head"><span class="num">05</span><h2>Decision inputs: availability + capabilities</h2></div>
|
||||
<p>The two flowcharts above read two pieces of probed state. Both are computed at connect time and refreshed on resume.</p>
|
||||
<div class="section-head"><span class="num">05</span><h2>Owner, readiness, and capabilities</h2></div>
|
||||
<p>Saved connection state chooses the owner. Availability reports whether that owner is ready; Direct API capabilities choose an endpoint only inside an API-owned conversation.</p>
|
||||
|
||||
<div class="paths" style="margin-top:16px">
|
||||
<div class="panel">
|
||||
@@ -752,7 +737,7 @@
|
||||
<p class="ref">GatewayModels.kt:22 · set by the dashboard <code>/api/status</code> + <code>/api/auth/me</code> probe</p>
|
||||
<ul style="padding-left:18px;margin-top:10px">
|
||||
<li><span class="dot neutral"></span><strong>Unknown</strong> — no probe yet (startup / connection switch)</li>
|
||||
<li><span class="dot ok"></span><strong>Ready</strong> — reachable + authenticated (or no auth) → gateway preferred</li>
|
||||
<li><span class="dot ok"></span><strong>Ready</strong> — reachable + authenticated (or no auth) → Gateway can send</li>
|
||||
<li><span class="dot warn"></span><strong>SignInRequired</strong> — reachable but gated; Manage sign-in unlocks it</li>
|
||||
<li><span class="dot bad"></span><strong>Unreachable</strong> — <code>/api/status</code> didn't answer</li>
|
||||
<li><span class="dot bad"></span><strong>Unsupported</strong> — <em>sticky</em>: WS upgrade/ticket got 404/403 (build predates embedded chat)</li>
|
||||
@@ -788,8 +773,8 @@
|
||||
<tr><th>Feature</th><th>Path</th><th>Surface</th><th>Degrades to</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><strong>Chat (live thinking)</strong></td><td class="std-c">Vanilla Hermes</td><td>Gateway WS</td><td>Sessions → Completions → Runs SSE</td></tr>
|
||||
<tr><td><strong>Chat (fallback)</strong></td><td class="std-c">Vanilla Hermes</td><td>API-server SSE</td><td>Inline-annotation parser</td></tr>
|
||||
<tr><td><strong>Chat (live thinking)</strong></td><td class="std-c">Vanilla Hermes</td><td>Gateway WS</td><td>Sign in or retry on the same owner</td></tr>
|
||||
<tr><td><strong>Direct API chat</strong></td><td class="std-c">Vanilla Hermes</td><td>API-server SSE</td><td>Inline-annotation parser</td></tr>
|
||||
<tr><td><strong>Session history / CRUD</strong></td><td class="std-c">Vanilla Hermes</td><td><code>/api/sessions</code></td><td>Stateless completions (no persistence)</td></tr>
|
||||
<tr><td><strong>Manage</strong> (config/profiles/model/env/MCP)</td><td class="std-c">Vanilla Hermes</td><td>Dashboard <code>/api/*</code></td><td>— (hidden if dashboard down)</td></tr>
|
||||
<tr><td><strong>Vanilla Hermes voice</strong> (STT/TTS)</td><td class="std-c">Vanilla Hermes</td><td>Dashboard <code>/api/audio/*</code></td><td>Relay voice if paired (Auto route)</td></tr>
|
||||
|
||||
@@ -24,7 +24,7 @@ A plain Hermes install is enough. Chat, management, and voice all work with no p
|
||||
|
||||
HOW IT WORKS
|
||||
|
||||
Chat, sessions, Manage, and voice use the Hermes Dashboard/Gateway with one sign-in. A headless API server remains an automatic compatibility fallback. Run the optional relay service and the app can pair by QR code to add power tools: remote terminal, notification companion, media handoff, relay-session management, and more voice engines.
|
||||
Chat, sessions, Manage, and voice use the Hermes Dashboard/Gateway with one sign-in. Existing API-only and headless connections remain supported as an explicit compatibility mode. Run the optional relay service and the app can pair by QR code to add power tools: remote terminal, notification companion, media handoff, relay-session management, and more voice engines.
|
||||
|
||||
GOOGLE PLAY BUILD
|
||||
|
||||
@@ -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.
|
||||
```
|
||||
|
||||
+46
-20
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -19,7 +19,7 @@ Current capabilities are split between vanilla upstream Hermes and optional Rela
|
||||
|
||||
| Surface | Requires Relay | What |
|
||||
|---------|----------------|------|
|
||||
| **Chat** | No | Talk to any Hermes agent profile with dashboard `/api/ws` live thinking when signed in, or API-server SSE fallback |
|
||||
| **Chat** | No | Talk to any Hermes agent profile with dashboard `/api/ws` live thinking when signed in, or an explicit API-only compatibility connection |
|
||||
| **Manage** | No | Dashboard-backed config, profiles, model/provider keys, skills, MCP, and diagnostics |
|
||||
| **Vanilla Hermes voice** | No | Dashboard `/api/audio/transcribe`, streaming `/api/audio/speak-stream`, and compatible `/api/audio/speak` fallback with the Manage session |
|
||||
| **Terminal** | Yes | Secure remote shell access to the Hermes server via tmux |
|
||||
@@ -27,8 +27,9 @@ Current capabilities are split between vanilla upstream Hermes and optional Rela
|
||||
| **Relay power features** | Yes | Remote access, notification companion, provider-native voice, desktop tooling, media relay |
|
||||
|
||||
The standard Vanilla Hermes connection needs only the Dashboard/Gateway surface.
|
||||
An API-server endpoint can be discovered or added as an automatic fallback for
|
||||
chat and advanced headless compatibility. Pairing adds the Relay URL, session
|
||||
An API-server endpoint can be retained or added for explicit API-only chat and
|
||||
advanced headless compatibility. It never takes over a Dashboard-owned
|
||||
conversation after sign-out or a route failure. Pairing adds the Relay URL, session
|
||||
token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
**What it is not:**
|
||||
@@ -42,7 +43,7 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
1. **Vanilla Hermes first** — chat, Manage, and voice must work against unmodified upstream Hermes before any Relay power path is considered.
|
||||
2. **Secure by default** — WSS/HTTPS for remote paths; dashboard, API, and Relay auth stay on their native surfaces.
|
||||
3. **Realtime where the surface supports it** — gateway chat can stream live thinking; API-server SSE remains the fallback; terminal and bridge stay realtime through Relay.
|
||||
3. **Realtime where the surface supports it** — gateway chat can stream live thinking; API-server SSE remains an explicit compatibility mode; terminal and bridge stay realtime through Relay.
|
||||
4. **Clean UX** — Material 3, minimal setup, and clear route identity for Vanilla Hermes vs Relay.
|
||||
5. **Offline-aware** — graceful degradation when connection drops. Auto-reconnect with exponential backoff.
|
||||
6. **Server-side state** — the app is a thin client. Sessions, history, memory, profiles, and dashboard state live on the Hermes server.
|
||||
@@ -51,6 +52,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
|
||||
@@ -59,7 +81,8 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
```
|
||||
Android app
|
||||
|-- Vanilla Hermes chat -> dashboard /api/ws, then API-server SSE fallback
|
||||
|-- Vanilla Hermes chat -> dashboard /api/ws (transport-affine)
|
||||
|-- API-only chat -> API-server SSE compatibility routes
|
||||
|-- Vanilla Hermes Manage -> dashboard /api/*
|
||||
|-- Vanilla Hermes voice -> dashboard /api/audio/*
|
||||
|-- Relay terminal -> Tailscale Serve WSS, or opt-in Hermes Secure Link :9443/relay/ws
|
||||
@@ -90,7 +113,7 @@ A saved **Connection** represents one Hermes installation, not one transport.
|
||||
Its stable identity is independent of endpoint URLs. Dashboard/Gateway is the
|
||||
standard upstream surface; API server and Relay endpoints are optional
|
||||
capabilities that can be discovered, added, removed, and diagnosed separately.
|
||||
The normal UI reports outcomes such as Chat, Manage, Voice, API fallback, and
|
||||
The normal UI reports outcomes such as Chat, Manage, Voice, Direct API, and
|
||||
Relay extensions instead of treating a missing optional endpoint as a broken
|
||||
connection.
|
||||
|
||||
@@ -196,8 +219,9 @@ to attach the PR a coding session created, then the repo-scoped read-only
|
||||
this metadata is optional; older Dashboard and API-server hosts retain the
|
||||
ordinary session row.
|
||||
|
||||
Chat availability is derived only from the authenticated Gateway and supported
|
||||
API-server fallback routes. A Send with no usable route remains fail-closed and
|
||||
Chat availability is derived only from the active conversation owner: the
|
||||
authenticated Gateway or an explicitly API-owned compatibility route. A Send
|
||||
with no usable owner remains fail-closed and
|
||||
surfaces a retryable conversation failure plus secret-free Diagnostics evidence.
|
||||
Profile-owned Gateway history is required to load through that exact profile;
|
||||
an unavailable scoped reader surfaces a history failure instead of accepting an
|
||||
@@ -586,8 +610,8 @@ Bottom navigation bar with 4 tabs:
|
||||
- **Bot group projection** — Android merges the bounded `ui_meta["hermes-bots-groups"]` v3 projection across gateways by durable room identity and newest revision. Rooms and recent messages are visibly read-only; Android does not create, rename, disband, join, send, coordinate member turns, or become a second room-log authority. Binary room images are ignored at this metadata boundary.
|
||||
- **Session drawer** (swipe from left or hamburger icon) — session list with title, timestamp, message count. Create, switch, rename, delete, pin/unpin, and archive/restore. A profile switch marks the replacement list loading before clearing the previous profile's rows and keeps that state until the exact-profile fetch settles, so an empty-state claim never flashes before server truth arrives. The process-owned conversation binding is the single connection/profile/session identity for Chat; selecting an All Profiles row atomically makes its owner the selected agent and persists that profile/session, while merely browsing All Profiles changes no agent state. Lifecycle or locale-driven Activity recreation cannot replace an explicit binding with stale persisted state, and asynchronous list/history/mutation work is accepted only for the binding's exact namespace. A profile lock hides All Profiles and rejects stale/deep-linked cross-profile opens. The All Profiles browser mode otherwise survives Activity state restoration and refetches its rows after recreation. Pin and archive are durable upstream session fields loaded and patched through the owning connection/profile's Dashboard session API; Android does not keep a second local flag registry. Archived rows are requested explicitly so they remain restorable after recreation. Failed mutations roll back the optimistic row, while refresh and deletion reconcile from server truth. When a persisted title is absent, use upstream's first-user-message `preview`, matching the Hermes Desktop session picker; show "Untitled" only when neither value exists.
|
||||
- **Cold profile hydration** — a persisted named profile scopes its Dashboard session directory and last-session restore immediately, before `/api/profiles` metadata is available. Server-default selection waits for the lightweight active-profile scope. Roster, avatars, pets, skills, and model metadata never precede the first directory result. The startup sphere releases after route selection; Chat keeps identity and cached rows mounted while its existing animated status surfaces show Gateway wake, session restore, and directory loading.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; an exact terminal, `session.info {running:false}`, or an exact live/durable active-list row reporting Idle can settle only the matching Android-owned turn and progress generation. Because active-list rows normally have no profile metadata, Android assigns a row only through exact foreground/detached ownership already held by that client, or explicit profile metadata if a future upstream sends it. A bounded REST directory never proves global uniqueness. Unresolved rows create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, bare session ids from another profile, delayed snapshots, and snapshots crossed by newer turn events cannot settle or revive a newer generation.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and SSE fallback stays single-stream and cancels on navigation.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; an exact terminal, `session.info {running:false}`, or an exact live/durable active-list row reporting Idle can settle only the matching Android-owned turn and progress generation. Because active-list rows normally have no profile metadata, Android assigns a row through exact foreground/detached ownership already held by that client, explicit profile metadata if a future upstream sends it, or the currently selected passive session when its durable id has exactly one owner in the current connection directory. Duplicate same-id owners across profiles remain unresolved and create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, ambiguous bare session ids, delayed snapshots, and snapshots crossed by newer turn events cannot settle or revive a newer generation.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and Direct API compatibility chat stays single-stream and cancels on navigation.
|
||||
- **Queued Gateway follow-ups** — every local queued item is immutably scoped to its originating connection, profile, stored session, transport, and run generation; only that run's completion can make it eligible, and switching sessions shows only that session's queue. Restored text queues retain the same scope, while unavailable/deleted destinations and non-restorable attachment queues fail visibly instead of following the current composer. Drained messages add `queued: true` to `prompt.submit`; ordinary sends omit the field. Authoritative submit rejections (`4004`, `4018`, `4028`, `4029`, `4030`, `4090`, `5008`, `5070`, and `5071`) preserve the server message and never fall through to API-server SSE.
|
||||
- **Durable composer drafts** — each connection/profile/session owns one app-private draft containing text, quote/edit context, and pending attachment bytes. Metadata and content-addressed blobs live under Android's no-backup directory, are capped at 64 drafts and 128 MB of retained blobs outside the active draft, flush when Chat backgrounds, and are removed after a successful send. Session/profile/connection navigation saves the previous owner before restoring the destination; an opened cross-profile session uses its actual owning profile rather than the global picker.
|
||||
- **Large paste review** — a default-on Chat setting converts any single insertion of at least 5,000 characters into a visible `pasted-text.txt` attachment before the normal message-length limit rejects it. Gateway uses upstream `file.attach`; API-server SSE and proactive Thread paths materialize the same UTF-8 text into the outgoing prompt and remove only the synthetic attachment from that transport, so the behavior never requires Relay or silently drops content.
|
||||
@@ -639,7 +663,7 @@ The bridge UI drives — and is driven by — Tier 5 safety-rails (`BridgeSafety
|
||||
### Settings Tab
|
||||
- **Active agent card (v0.6.0)** — top-of-screen summary card showing the current Connection / Profile / Personality. Tap navigates to Chat and auto-opens the agent sheet via the `openAgentSheet` nav arg, giving Settings-originating users a one-tap path to change agent context without leaving the flow.
|
||||
- **Connections** (v0.6.0+) — lists every paired Hermes server with a per-card status chip. Actions: rename (inline), re-pair (reuses `ConnectionWizard` with `connectionId` nav arg), revoke, remove. Add-connection button launches the standard QR flow. Settings briefly treats a paired + disconnected relay as **Connecting** during the reconnect grace window, then promotes it to **Relay unreachable - tap to reconnect** if the live socket does not recover. API / Relay / Session detail sheets include compact sanitized recent-activity tails, and **Settings -> Diagnostics** shows the consolidated app-level API, relay, session, endpoint, voice, Pair-readiness, credential-store recovery, history-failure, and rejected-Send evidence without secrets. See `docs/decisions.md` §19.
|
||||
- **Connection (single-server settings)** — summary-first detail for one Hermes installation. Dashboard/Gateway health drives standard Chat, Manage, Sessions, and Voice readiness. API fallback and Relay extensions appear as independently optional capabilities. Dashboard/Gateway address and network paths are edited under Routes. Advanced retains only the optional direct API credential, explicit direct Relay endpoint override, and insecure-development controls; missing API or Relay settings never make a healthy Dashboard/Gateway connection look broken. Every Relay QR, enter-code, and show-code method uses the shared connection-scoped Pair flow. Transport security posture and paired-device grants remain visible without leading the normal setup flow with ports or bearer keys.
|
||||
- **Connection (single-server settings)** — summary-first detail for one Hermes installation. Dashboard/Gateway health drives standard Chat, Manage, Sessions, and Voice readiness. Direct API compatibility and Relay extensions appear as independently optional capabilities. Dashboard/Gateway address and network paths are edited under Routes. Advanced retains only the optional direct API credential, explicit direct Relay endpoint override, and insecure-development controls; missing API or Relay settings never make a healthy Dashboard/Gateway connection look broken. Every Relay QR, enter-code, and show-code method uses the shared connection-scoped Pair flow. Transport security posture and paired-device grants remain visible without leading the normal setup flow with ports or bearer keys.
|
||||
- **Chat** — Show reasoning toggle, smooth auto-scroll toggle (live-follow streaming, default on), show token usage toggle, app context prompt toggle, tool call display (Off/Compact/Detailed), streaming endpoint selector (`auto` / `sessions` / `runs`), Stats for Nerds (analytics charts)
|
||||
- **Voice** — route-aware voice engine selector (`Vanilla Hermes` via dashboard audio, `Relay Voice Output`, and experimental `Realtime Agent`), global interaction mode (tap / hold / continuous), silence threshold slider, a final-answer-only speech policy, Auto-TTS toggle, selected-engine cards for dashboard or relay-backed settings, language picker, and a Test Current Engine card. Final-answer-only keeps tool/service progress and intermediate commentary visual while both voice engines wait to speak the settled answer; approvals, confirmation questions, and blocking failures remain actionable. Vanilla Hermes voice depends on Manage/dashboard auth; Relay-backed engines run a fast relay health preflight before uploading audio or opening a realtime provider session so a hung relay surfaces as a connection error instead of an indefinite Thinking state.
|
||||
- **Notification companion** — opt-in status, "Open Android Settings" action, test notification dump
|
||||
@@ -690,13 +714,15 @@ HTTP routes registered by `create_app()` in `plugin/relay/server.py`:
|
||||
| `/api/profiles/{name}/soul` | GET | Profile-scoped raw `SOUL.md` read. Returns `{profile, path, content, exists, size_bytes}` with optional `truncated: true` when content exceeds the 200KB inline cap. Absent SOUL.md returns 200 with `exists: false` and an empty content string so the Inspector can distinguish "no soul" from transport failure. Same auth model as `/config`. 404 on unknown profile; 500 `{error: "soul_read_failed"}` on decode error. See §22 in decisions.md. |
|
||||
| `/api/profiles/{name}/memory` | GET | Profile-scoped memory listing. Returns `{profile, memories_dir, entries: [{name, filename, path, content, size_bytes, truncated}], total}` for `*.md` files directly under `<profile>/memories/` (non-recursive). Ordering: `MEMORY.md` first, `USER.md` second, remainder alphabetical. Each entry capped at 50KB inline with `truncated: true` when larger. Absent memories dir → 200 with empty `entries` array. Same auth model as `/config`. 404 on unknown profile. See §22 in decisions.md. |
|
||||
|
||||
### 6.2 Chat — Dashboard/Gateway Primary with Optional API Fallback
|
||||
### 6.2 Chat — Dashboard/Gateway Primary with Explicit API Compatibility
|
||||
|
||||
Chat bypasses the Relay server entirely. In `Auto`, Android uses the upstream
|
||||
dashboard `/api/ws` gateway when dashboard auth is ready because that is the
|
||||
vanilla upstream path with live thinking/reasoning events. When that gateway is
|
||||
unavailable, Android falls back to API-server SSE routes. The native Sessions
|
||||
API fallback looks like:
|
||||
Chat bypasses the Relay server entirely. In `Auto`, a standard saved connection
|
||||
uses the upstream dashboard `/api/ws` gateway because that is the vanilla
|
||||
upstream path with live thinking/reasoning events. That owner is stable: sign-in
|
||||
expiry or a temporary route failure preserves the transcript and draft and
|
||||
offers sign-in/retry; it never dispatches the turn to another database. A
|
||||
legacy API-only record or an explicit advanced Direct API selection uses the
|
||||
API-server SSE routes. The native Sessions compatibility path looks like:
|
||||
|
||||
Model inventory also stays upstream-owned. Android may call the optional Relay
|
||||
`POST /relay/model-capabilities` route to refine reasoning-effort choices for
|
||||
@@ -1183,7 +1209,7 @@ See `docs/decisions.md` → **Voice Mode — Architecture** for the historical b
|
||||
|
||||
## 8. Current Scope
|
||||
|
||||
As of v1.0.0, the current scope is maintaining the vanilla-Hermes-first contract while keeping Relay power features additive and cleanly manageable. Vanilla Hermes Dashboard/Gateway chat, Manage, sessions, and dashboard voice must continue to work against unmodified upstream Hermes without an API-server or Relay requirement. API fallback remains optional and Relay work should be plugin-owned, diagnosable through `hermes relay doctor`, and removable without becoming a hidden requirement for the vanilla Hermes app path.
|
||||
As of v1.0.0, the current scope is maintaining the vanilla-Hermes-first contract while keeping Relay power features additive and cleanly manageable. Vanilla Hermes Dashboard/Gateway chat, Manage, sessions, and dashboard voice must continue to work against unmodified upstream Hermes without an API-server or Relay requirement. Direct API compatibility remains optional and Relay work should be plugin-owned, diagnosable through `hermes relay doctor`, and removable without becoming a hidden requirement for the vanilla Hermes app path.
|
||||
|
||||
**Still non-goals for the current cadence:**
|
||||
- Biometric session lock (fingerprint/face gate on terminal and/or chat resume). Tracked under Phase 4.
|
||||
@@ -1231,7 +1257,7 @@ Current Android dependency versions. Source of truth is `gradle/libs.versions.to
|
||||
| Surface | How We Connect |
|
||||
|---------|---------------|
|
||||
| **Gateway chat** | Dashboard `/api/auth/ws-ticket` + `/api/ws` for live thinking/reasoning and session-scoped `image.attach_bytes` / `pdf.attach` / `file.attach` uploads when Manage auth is ready |
|
||||
| **API-server chat fallback** | `/api/sessions/*/chat/stream`, `/v1/chat/completions`, or `/v1/runs` based on capability probes; a known selected multiplex profile uses the shared listener's `/p/<profile>` prefix and its own encrypted profile credential |
|
||||
| **API-only compatibility chat** | `/api/sessions/*/chat/stream`, `/v1/chat/completions`, or `/v1/runs` based on capability probes; a known selected multiplex profile uses the shared listener's `/p/<profile>` prefix and its own encrypted profile credential |
|
||||
| **API-server sessions** | `GET/POST/PATCH/DELETE /api/sessions` for CRUD |
|
||||
| **Manage** | Dashboard `/api/status`, `/api/auth/me`, `/api/config`, `/api/profiles/*`, `/api/env`, `/api/model/*`, `/api/mcp/*` |
|
||||
| **Vanilla Hermes voice** | Dashboard `POST /api/audio/transcribe`, WebSocket `/api/audio/speak-stream`, and `POST /api/audio/speak` compatibility fallback, all scoped by the selected profile when present |
|
||||
|
||||
@@ -34,15 +34,15 @@ Verified upstream source snapshot:
|
||||
|
||||
| Surface | Owner | Requires Relay | Android usage | Notes |
|
||||
|---------|-------|----------------|---------------|-------|
|
||||
| `/v1/capabilities` | Upstream API server | No | Optional fallback capability probe | Source of truth for API-server features; current upstream advertises no audio API. |
|
||||
| `/v1/chat/completions` | Upstream API server | No | Chat fallback | OpenAI-compatible streaming. Tool events may degrade to inline annotations. |
|
||||
| `/v1/runs`, `/v1/runs/{id}/events` | Upstream API server | No | Chat fallback | Structured run events and stop/approval support. |
|
||||
| `/v1/capabilities` | Upstream API server | No | Direct API capability probe | Source of truth for API-server features; current upstream advertises no audio API. |
|
||||
| `/v1/chat/completions` | Upstream API server | No | API-only compatibility chat | OpenAI-compatible streaming. Tool events may degrade to inline annotations. |
|
||||
| `/v1/runs`, `/v1/runs/{id}/events` | Upstream API server | No | API-only compatibility chat | Structured run events and stop/approval support. |
|
||||
| Dashboard `/api/health` | Upstream dashboard | No | Route/process readiness | Lightweight canonical readiness probe used by official Desktop. Android falls back to `/api/status` only for confirmed legacy hosts without this route; transient failures never trigger the heavyweight fallback. |
|
||||
| `/api/sessions/*` | Upstream Dashboard/Gateway and API server | No | Primary profile-scoped session directory/history or optional SSE fallback | Native upstream session list/create/read/update/delete/messages/fork/chat/chat-stream. The standard Android drawer and stored-history reader use authenticated Dashboard REST independently of `/api/ws` readiness; the Gateway socket owns live chat and activity, not whether persisted rows may be read. Dashboard lists expose profile-stamped `pinned`/`archived`, accept `archived=exclude\|only\|include`, and PATCH either durable flag in the owning profile DB. The API-server resource also exposes and patches both fields, but its current list omits archived rows and has no archive filter; Android therefore offers restart-safe archive/restore only on the Dashboard path while API-only pinning remains valid. Newer Dashboard hosts also expose single-session JSON export and guarded bulk cleanup; Android must dry-run prune first. The bootstrap no longer injects session CRUD/messages/fork routes; only `/api/sessions/search` remains a compatibility route. |
|
||||
| `/api/sessions/*` | Upstream Dashboard/Gateway and API server | No | Primary profile-scoped Dashboard directory/history or API-only compatibility storage | Native upstream session list/create/read/update/delete/messages/fork/chat/chat-stream. The standard Android drawer and stored-history reader use authenticated Dashboard REST independently of `/api/ws` readiness; the Gateway socket owns live chat and activity, not whether persisted rows may be read. Dashboard lists expose profile-stamped `pinned`/`archived`, accept `archived=exclude\|only\|include`, and PATCH either durable flag in the owning profile DB. The API-server resource also exposes and patches both fields, but its current list omits archived rows and has no archive filter; Android therefore offers restart-safe archive/restore only on the Dashboard path while API-only pinning remains valid. Newer Dashboard hosts also expose single-session JSON export and guarded bulk cleanup; Android must dry-run prune first. The bootstrap no longer injects session CRUD/messages/fork routes; only `/api/sessions/search` remains a compatibility route. |
|
||||
| `/v1/skills`, `/v1/toolsets` | Upstream API server | No | Discovery | Authenticated read-only API-server skill/toolset inventory; Android Diagnostics summarizes enabled toolsets and Relay tool visibility. |
|
||||
| Dashboard `/api/status`, `/api/auth/me` | Upstream dashboard | No | Manage auth and post-selection diagnostics | Dashboard cookie/session path; separate from API bearer. Optional status diagnostics include Nous bootstrap validity, resource pressure, and profile/gateway topology; these do not gate transport selection. |
|
||||
| Dashboard `/api/auth/ws-ticket`, `/api/ws` | Upstream dashboard/tui_gateway | No | Preferred chat transport | Vanilla Hermes gateway chat path with live reasoning/thinking events. `message.complete` is the ordinary terminal event; `session.info {running:false}` is the authoritative settle backstop when a replacement socket missed that terminal frame. A reconnect reactivates the exact live runtime with `session.activate`; durable `session.resume` remains the cold-open path and an explicit rejection never creates a replacement context. |
|
||||
| Gateway `session.active_list` | Upstream tui_gateway | No | Authoritative process-wide live activity | Returns attachable runtimes across the Gateway process, with live `id`, durable `session_key`, and `starting`, `working`, `waiting`, or `idle`. The only optional selector is `current_session_id`; rows normally carry no profile metadata. Android attributes a row only from exact foreground/detached ownership already held by that client, or from explicit profile metadata if a future upstream sends it. An exact live/durable Idle row may settle only the same Android-owned turn and unchanged progress generation when a terminal frame is missing; it never claims a passively observed Desktop/TUI turn. A bounded REST directory never proves global uniqueness. Unresolved rows remain unattributed, and absence settles a scope only after a complete, unambiguously resolved successful snapshot. Method-not-found or refresh failure is Unavailable, not Idle. Pending input outranks running work. |
|
||||
| Gateway `session.active_list` | Upstream tui_gateway | No | Authoritative process-wide live activity | Returns attachable runtimes across the Gateway process, with live `id`, durable `session_key`, and `starting`, `working`, `waiting`, or `idle`. The only optional selector is `current_session_id`; rows normally carry no profile metadata. Android attributes a row from exact foreground/detached ownership already held by that client, explicit profile metadata if a future upstream sends it, or a unique match to the currently selected passive session in the current connection directory. Duplicate same-id owners across profiles remain unresolved. An exact live/durable Idle row may settle only the same Android-owned turn and unchanged progress generation when a terminal frame is missing; it never claims a passively observed Desktop/TUI turn. Unresolved rows stay unattributed, and absence settles a scope only after a complete, unambiguously resolved successful snapshot. Method-not-found or refresh failure is Unavailable, not Idle. Pending input outranks running work. |
|
||||
| Dashboard `model.options` / `/api/model/*` | Upstream dashboard/tui_gateway | No | Provider/model inventory and selection | Source of truth for coherent provider/model identities. A reasoning boolean or exact effort list is consumed when present; clients do not infer provider identity from a model string alone. |
|
||||
| Gateway `pet.info`, `pet.gallery`, `pet.select`, `pet.disable` | Upstream tui_gateway | No | Profile-scoped animated companion | `pet.info` supplies bounded PNG/WebP sheet bytes, revision, geometry, real frame counts, loop timing, scale, and row taxonomy. Android passes `knownRevision` to avoid duplicate sheet transfer, renders the active pet through its native activity-aware companion, and keeps phone-local pet packs separate. All four RPCs carry the effective profile. |
|
||||
| Dashboard `/api/audio/transcribe`, `/api/audio/speak-stream`, `/api/audio/speak` | Upstream dashboard | No | Vanilla Hermes voice | Manage sign-in unlocks Vanilla Hermes voice. Assistant text streams into upstream speech when available; older hosts fall back to whole-request speech before audio starts. API server has no `/v1/audio/*` route today. |
|
||||
@@ -168,7 +168,7 @@ capabilities, not identity:
|
||||
| Surface | Product role | Required for the standard path |
|
||||
|---------|--------------|--------------------------------|
|
||||
| Dashboard/Gateway | Primary chat, auth, sessions, Manage, and Vanilla Hermes voice | Yes |
|
||||
| API server | Automatic chat fallback and advanced headless compatibility | No |
|
||||
| API server | Explicit API-only and advanced headless compatibility | No |
|
||||
| Relay | Pairing, terminal, bridge/device control, media, and enhanced voice; normally reached through the Dashboard plugin ingress | No |
|
||||
|
||||
Existing API-only records and headless deployments remain supported compatibility
|
||||
@@ -181,10 +181,10 @@ The app should present Vanilla Hermes as the default path:
|
||||
|
||||
1. Connect to and authenticate with the Dashboard/Gateway.
|
||||
2. Use gateway chat when `/api/ws` is ready.
|
||||
3. Discover or accept an API server as an optional automatic fallback; otherwise
|
||||
keep the connection healthy with API fallback marked unavailable.
|
||||
4. When needed, fall back to API-server
|
||||
SSE.
|
||||
3. Keep any discovered API server as an optional compatibility capability; it
|
||||
does not alter the owner of the active Dashboard conversation.
|
||||
4. Use API-server SSE only for a legacy API-only record or an explicit advanced
|
||||
Direct API selection/new chat.
|
||||
5. Use Vanilla Hermes dashboard voice when audio routes are present.
|
||||
6. Offer Relay pairing only for Relay-owned power features. Prefer the
|
||||
Dashboard-origin plugin ingress advertised by pairing; retain a direct Relay
|
||||
@@ -233,7 +233,7 @@ keeping route ownership explicit:
|
||||
- Connection/profile ownership plus request generation are rechecked before
|
||||
publication, so a late response cannot populate a newer profile selection.
|
||||
|
||||
## API Fallback Compatibility Details
|
||||
## Direct API Compatibility Details
|
||||
|
||||
- Dashboard/API session-list `is_active` is a persistence-recency hint: an
|
||||
unended row whose `last_active` is less than five minutes old. It is not a
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -53,7 +53,7 @@ function normalizeRoute(endpoint, index, globalPayload, endpointCount) {
|
||||
const surfaces = [
|
||||
dashboard ? { surface: "dashboard", label: "Dashboard", url: dashboard } : null,
|
||||
relay ? { surface: "relay", label: "Relay", url: relay } : null,
|
||||
api ? { surface: "api", label: "API fallback", url: api } : null,
|
||||
api ? { surface: "api", label: "Direct API", url: api } : null,
|
||||
].filter(Boolean);
|
||||
const issues = [];
|
||||
|
||||
@@ -72,7 +72,7 @@ function normalizeRoute(endpoint, index, globalPayload, endpointCount) {
|
||||
issues.push("public: Relay must use WSS");
|
||||
}
|
||||
if (api && !api.startsWith("https://")) {
|
||||
issues.push("public: API fallback must use HTTPS");
|
||||
issues.push("public: Direct API must use HTTPS");
|
||||
}
|
||||
} else if (normalizedRole === "public_legacy") {
|
||||
if (!relay) issues.push("public_legacy: missing Relay route");
|
||||
|
||||
@@ -149,7 +149,7 @@ function TailscaleCard({ status, onEnable, onDisable, busy, resultMessage }) {
|
||||
<div className="flex items-center gap-2">
|
||||
<Dot tone={apiServing ? "ok" : "muted"} />
|
||||
<span>
|
||||
API fallback → host :8642: {apiServing
|
||||
Direct API → host :8642: {apiServing
|
||||
? `active on ${listenerLabel(apiService)} · optional`
|
||||
: "off"}
|
||||
</span>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user