Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8156a821eb | ||
|
|
e6368dada8 | ||
|
|
e55662e0e1 | ||
|
|
051844bc14 | ||
|
|
1e5ce986be | ||
|
|
06b24631e3 | ||
|
|
2d2e54ba79 | ||
|
|
ee59149b41 | ||
|
|
23a6231b20 | ||
|
|
a4fac4550a | ||
|
|
88ab48cfc0 | ||
|
|
7c03f8554f | ||
|
|
367e5d271c | ||
|
|
47a395ab76 | ||
|
|
e7cbed3c8f | ||
|
|
2f7bd843bc | ||
|
|
d1527d47e4 | ||
|
|
bc0853360a | ||
|
|
b72ab5aef2 | ||
|
|
40fcb80a7d | ||
|
|
ff64548085 | ||
|
|
35362b8895 | ||
|
|
ff7ca89b90 | ||
|
|
042f02b852 | ||
|
|
5fc85c1699 | ||
|
|
c01c6cf457 | ||
|
|
22780881e1 | ||
|
|
201e204290 | ||
|
|
eb8434e508 | ||
|
|
597b13e2db | ||
|
|
946b333109 | ||
|
|
8b3731b22f | ||
|
|
b76ba7a314 | ||
|
|
2c15bd4207 | ||
|
|
949add15b1 | ||
|
|
6a93d13ecb | ||
|
|
cbc02bb407 | ||
|
|
525f6b5fc0 | ||
|
|
de8f5558c2 | ||
|
|
58e8b1edb6 | ||
|
|
adcf4ded79 | ||
|
|
05d6ee4d7c | ||
|
|
d42fa91698 | ||
|
|
41cbafddba | ||
|
|
a2be512c45 | ||
|
|
6a66710763 | ||
|
|
8632ced503 | ||
|
|
ae18bbee24 | ||
|
|
9690071e7d | ||
|
|
698b45cbb3 | ||
|
|
55a838cb78 | ||
|
|
afa875d89f | ||
|
|
aff758fb99 | ||
|
|
8625963846 | ||
|
|
d367cd3a24 | ||
|
|
5bd0b2acaf | ||
|
|
6f0948ca01 | ||
|
|
541a7c078d | ||
|
|
e0b726de85 | ||
|
|
8865a31013 | ||
|
|
a199c35377 | ||
|
|
6a495b6e06 | ||
|
|
105da550e7 | ||
|
|
23c06d60b9 | ||
|
|
febc26fe35 | ||
|
|
28a906215d | ||
|
|
1617f75f1a | ||
|
|
dbf71a87f4 | ||
|
|
95ed8e6edb | ||
|
|
d26bf6c25b | ||
|
|
181e10f2ad | ||
|
|
78203fd8a1 | ||
|
|
c519502551 | ||
|
|
814afc56da | ||
|
|
1f055cb91f | ||
|
|
936b9bed8a | ||
|
|
dafa6f3a18 | ||
|
|
245362d58e | ||
|
|
857a1551f3 | ||
|
|
95e78e0657 | ||
|
|
00052d20d9 | ||
|
|
246d9f1010 | ||
|
|
e9f32673be | ||
|
|
7b390fa99f | ||
|
|
cd856da6a0 | ||
|
|
9a40aedb7d | ||
|
|
30eb70daa3 | ||
|
|
6be6cec201 | ||
|
|
4f5f3fac10 | ||
|
|
7f7112caf2 | ||
|
|
4c00e8edb7 | ||
|
|
44f0acec94 | ||
|
|
41b724e072 |
@@ -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"
|
||||
@@ -61,7 +67,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -80,6 +86,7 @@ jobs:
|
||||
- name: Validate Android release notes
|
||||
run: |
|
||||
python3 scripts/check-android-release-notes.py
|
||||
python3 -m unittest scripts.tests.android_prepush_test
|
||||
python3 -m unittest scripts.tests.check_android_release_notes_test
|
||||
|
||||
- name: Test Android native compatibility checker
|
||||
@@ -101,7 +108,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -151,7 +158,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -215,7 +222,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -176,7 +176,7 @@ jobs:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -83,7 +83,7 @@ jobs:
|
||||
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+30
-1
@@ -6,9 +6,38 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android Chat and Voice use tablet space intentionally.** Expanded layouts keep introductions, transcripts, composer controls, and status chrome on readable centered rails, while landscape Voice Focus separates identity controls from conversation activity without changing phone or portrait interaction behavior.
|
||||
|
||||
## [Android 1.15.0] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android prefers current upstream Hermes for standard media, Git, usage, and notices.** Authenticated Dashboard file delivery, current-session `/api/git/*`, Gateway `usage.bars`, and keyed agent notices work without the optional Hermes-Relay Plugin; Relay remains additive for older-host media compatibility, sensitivity metadata, repository discovery and guarded mutations, multi-provider usage, and true Relay tools.
|
||||
- **Android Settings separates standard Hermes from Relay tools.** Media now sits with Chat and Voice under Hermes, while proactive Threads, Terminal, Notification Companion, Relay sessions, and Device Control remain clearly grouped behind the optional plugin.
|
||||
- **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
|
||||
|
||||
- **Standard Hermes attachments no longer demand Relay pairing.** Host-local images, audio, video, and files download through the authenticated Dashboard, stay loaded across history reconciliation, and fall back to one neutral compatibility card on older hosts instead of flashing `Relay URL not configured` or retrying indefinitely.
|
||||
- **Removing optional Relay does not strand Standard voice or leak preferences across connections.** Runtime fallback keeps Dashboard voice usable, preserves configured choices through temporary outages, and normalizes only connection-scoped named-profile settings after explicit Relay removal.
|
||||
- **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)
|
||||
- **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.
|
||||
|
||||
## [Plugin 1.11.1] - 2026-08-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- **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.
|
||||
- **Relay prompt context advertises only real callable phone tools.** Phone-control and cross-platform delivery guidance now follows the exact selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` capabilities.
|
||||
|
||||
## [Android 1.14.0] - 2026-08-30
|
||||
|
||||
@@ -58,7 +87,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
- **Dense pairing QRs scan reliably.** Dashboard, CLI, and TUI render integer-sized modules with a full quiet zone.
|
||||
- **Remote-access migration keeps existing listeners safe.** Recommended setup avoids taking over `:443`, explicit legacy cleanup remains available, and default disable actions remove only the listeners they own.
|
||||
|
||||
## [0.4.0-beta.6] - 2026-08-30
|
||||
## [0.4.0-beta.6] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Hermes-Relay CLI+UI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-30
|
||||
**Release Date:** 2026-08-31
|
||||
|
||||
This beta preserves complete multi-route pairing while preventing Desktop from dialing Dashboard-ingress Relay routes before Dashboard WebSocket ticket support is available. (Related: #399)
|
||||
|
||||
|
||||
+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
|
||||
|
||||
+5
-19
@@ -1,29 +1,15 @@
|
||||
# Hermes-Relay Plugin v__VERSION__
|
||||
|
||||
**Release Date:** August 30, 2026
|
||||
**Release Date:** August 31, 2026
|
||||
|
||||
## Summary
|
||||
|
||||
This release lets one authenticated Hermes Dashboard origin carry Gateway plus optional Relay extensions, adds a bounded Git workspace, and reorganizes the Dashboard plugin around operator tasks. Standard chat, session history, profiles, Manage, and standard voice remain upstream-owned and do not require this plugin.
|
||||
|
||||
## Added
|
||||
|
||||
- **Dashboard same-origin Relay ingress.** Fixed allowlisted HTTP and WebSocket routes proxy to the local Relay while Dashboard admission and Relay session authentication remain independent. (Related: #399)
|
||||
- **Bounded Git workspace.** Configured roots, path containment, line totals, diffs, branches, staging, commits, remotes, grants, and explicit confirmations protect repository operations.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Task-oriented Dashboard UI.** Overview, Devices, Activity, Remote Access, Git, and Settings now have dedicated surfaces with QR-first pairing, responsive device cards, and honest media diagnostics. (#486)
|
||||
- **One explicit route topology.** Dashboard, CLI, and TUI pairing advertise Dashboard, Relay, and optional API surfaces with stable priorities across Tailscale, public HTTPS, and LAN.
|
||||
- **Dedicated Tailscale listener.** Recommended setup uses tailnet HTTPS `:10443` to local Dashboard `:9119`, avoiding ownership of a reverse proxy's `:443`. Existing `:443`, `:9119`, and direct `:8767` routes remain migration compatibility.
|
||||
This patch restores native installation compatibility on affected Hermes versions and makes Relay prompt context advertise only capabilities the selected session can actually call. Standard Chat, Manage, standard voice, and ordinary inbound files remain upstream-owned.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Public and roaming invites no longer synthesize closed direct Relay `:8767` or wrong Dashboard `:9119` routes.
|
||||
- Ambiguous, credential-bearing, or plaintext public candidates fail closed before an invite is exposed.
|
||||
- Dense pairing QRs use integer-sized modules and a full quiet zone.
|
||||
- Inactive optional API routes are omitted; protected Dashboard-ingress `401/403` responses display as authentication-required while direct Relay and API failures remain failures.
|
||||
- Default Tailscale disable actions remove only owned listeners, and explicit migration cleanup accepts only the bounded supported ports.
|
||||
- **Native installer compatibility.** The plugin keeps its complete current manifest while avoiding the installer/runtime schema mismatch that caused `manifest_version 2` installs to fail after an apparent Hermes update.
|
||||
- **Capability-gated phone context.** Phone-control and cross-platform delivery guidance now follows the selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` callables.
|
||||
|
||||
## Install / update
|
||||
|
||||
@@ -35,7 +21,7 @@ This release lets one authenticated Hermes Dashboard origin carry Gateway plus o
|
||||
# or, if already installed:
|
||||
hermes-relay-update
|
||||
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest, routes, and committed Dashboard bundle are active.
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest and prompt context are active.
|
||||
|
||||
## Verify
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — your Hermes agent, in your pocket" width="800">
|
||||
<img src="assets/readme-hero-v2.jpg" alt="Hermes-Relay — Your Hermes agent. Wherever you are. Android, Voice, Desktop." width="1000">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -38,10 +38,10 @@ Hermes-Relay puts your [Hermes agent](https://github.com/NousResearch/hermes-age
|
||||
- **📱 Android app** — streaming chat, hands-free voice, native plugin pages, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. Add a floating Petdex companion or optionally make Hermes your Android assistant; sideload builds can also let the agent read and act on your screen.
|
||||
- **⌨️ Hermes-Relay CLI** *(beta)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
|
||||
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, media, desktop tools, enhanced voice, Relay sessions, page drafts, and optional Device Control. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, inbound files, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, desktop tools, enhanced voice, Relay sessions, page drafts, optional Device Control, and media compatibility or metadata. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/diagrams/architecture-homepage.png" alt="How Hermes-Relay connects — upstream Hermes owns Chat, Manage, and standard Voice; the encouraged Relay extension fills current gaps for Terminal, notifications, media, enhanced voice, sessions, desktop tools, and optional Device Control." width="900">
|
||||
<img src="assets/readme-connection-map-v2.png" alt="How Hermes-Relay connects — Dashboard and Gateway own the standard Android path for Chat, Manage, Voice, and inbound files; the optional Relay plugin separately adds Android enhancements plus CLI and UI tools; sideload adds Device Control." width="1000">
|
||||
</p>
|
||||
|
||||
## Quick Start (Android)
|
||||
@@ -50,7 +50,7 @@ Install → connect → talk, in about two minutes.
|
||||
|
||||
### 1 · Install the app
|
||||
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, and Manage work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, media, notifications, and Relay sessions.
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, Manage, and inbound files work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, notifications, Relay sessions, and media enhancements.
|
||||
- **APK** *(full phone-control feature set)* — download the file ending in **`-sideload-release.apk`** from the newest `android-v*` release on [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases) and open it (allow your browser to install unknown apps the first time). Integrity verification, signing fingerprint, and per-build details are in the [Sideload guide](https://hermes-relay.dev/docs/guide/getting-started.html#sideload-apk).
|
||||
|
||||
Sideload builds check GitHub for updates and show a one-tap banner when you're behind; Play builds update through the Store. See [Release tracks](https://hermes-relay.dev/docs/guide/release-tracks) for the capability matrix.
|
||||
@@ -58,7 +58,7 @@ Sideload builds check GitHub for updates and show a one-tap banner when you're b
|
||||
### 2 · Have the Hermes Dashboard running
|
||||
|
||||
The normal Android connection uses the upstream Hermes Dashboard/Gateway for
|
||||
chat, sign-in, sessions, Manage, and voice. Installing Hermes and choosing a
|
||||
chat, sign-in, sessions, Manage, voice, and inbound files. Installing Hermes and choosing a
|
||||
provider is vanilla Hermes setup:
|
||||
|
||||
```bash
|
||||
@@ -77,16 +77,15 @@ the [remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
||||
|
||||
### 3 · Connect and talk
|
||||
|
||||
For a plugin-enabled host, open the Web Dashboard's **Relay** page, click
|
||||
**Connect mobile app**, and scan that tokenless QR from Android **Connect → Scan
|
||||
Hermes setup QR**. It contains only the Dashboard address and configures the
|
||||
upstream Chat, sessions, Manage, sign-in, and standard voice connection.
|
||||
|
||||
Without the Dashboard plugin, use **Find Hermes on LAN** or enter the Dashboard
|
||||
address manually (conventionally `http://<host>:9119`). Sign in through the
|
||||
Use **Find Hermes on LAN** or enter the Dashboard address manually
|
||||
(conventionally `http://<host>:9119`). Sign in through the
|
||||
Dashboard's configured provider when prompted. The app probes the available
|
||||
upstream capabilities and finishes with a connection summary.
|
||||
|
||||
If the Relay Dashboard page is already installed, **Connect mobile app** offers
|
||||
the same standard connection as a tokenless QR. It contains only the Dashboard
|
||||
address and does not install, enable, or pair Relay.
|
||||
|
||||
The separate API server can be discovered automatically or added later under
|
||||
**Advanced** as a chat fallback or for a headless compatibility setup. Its API
|
||||
key is requested only when that optional endpoint is configured. Existing
|
||||
@@ -99,7 +98,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
|
||||
@@ -109,9 +108,9 @@ the whole Vanilla Hermes setup.
|
||||
|
||||
### 4 · Recommended: pair Relay for the complete experience
|
||||
|
||||
Install Relay for Terminal/TUI, notifications, media handoff, desktop tools,
|
||||
enhanced voice, Relay sessions, approval-gated page drafts, and optional Device
|
||||
Control:
|
||||
Install Relay for Terminal/TUI, notifications, desktop tools, enhanced voice,
|
||||
Relay sessions, approval-gated page drafts, optional Device Control, and media
|
||||
compatibility or sensitivity metadata:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
@@ -140,7 +139,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
|
||||
|
||||
@@ -161,7 +160,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/supplemental/15_git_workspace.png" alt="Native Git workspace showing repository changes, an inline diff, and staging controls" width="260"><br>
|
||||
<sub><b>Native Git workspace</b> — optional Hermes-Relay plugin</sub>
|
||||
<sub><b>Native Git workspace</b> — upstream session context with optional Relay discovery and operations</sub>
|
||||
</p>
|
||||
|
||||
### Simplified Chinese
|
||||
@@ -239,17 +238,17 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice, inbound files]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media enhancements, 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
|
||||
install needs no plugin for those surfaces or ordinary inbound files. The optional relay on `:8767` adds
|
||||
terminal, bridge phone control, media compatibility/metadata, machine tools, and
|
||||
relay-side voice, which is preferred automatically when paired. One QR can
|
||||
configure API, dashboard, and relay routes without merging their auth models.
|
||||
|
||||
|
||||
+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
|
||||
|
||||
+22
-23
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.14.0
|
||||
# Hermes-Relay Android v1.15.0
|
||||
|
||||
**Release Date:** August 30, 2026
|
||||
**Release Date:** August 31, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.14.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.15.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,33 +12,32 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This release makes saved Hermes connections reliable across LAN, Tailscale, and public HTTPS while keeping Dashboard authentication bound to its exact trusted origin. It also adds delegated-agent previews and an optional native Git workspace, and improves Voice, Assistant, Threads, profile drafts, and Clarify interactions.
|
||||
|
||||
## Added
|
||||
|
||||
- **Delegated-agent previews.** Follow bounded lifecycle, progress, tool previews, and available read-only child history without leaving the parent chat. Partial history and reconnect gaps remain explicit. (#447)
|
||||
- **Native Git workspace.** Review repository state, diffs, branches, staging, commits, and remotes from Chat or Settings. Git operations require Hermes-Relay Plugin v1.11.0 and retain confirmation and grant boundaries.
|
||||
This release makes the everyday Android experience work through current upstream Hermes without treating the optional Hermes-Relay Plugin as a prerequisite. It also strengthens parent access, cross-client activity, transport ownership, recovery, and release visibility.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Route-aware connections.** Dashboard, Relay, and optional API health are evaluated independently across LAN, Tailscale, and public HTTPS. Same-origin Relay ingress stays on the Dashboard origin that owns authentication, while direct compatibility routes keep separate credentials. (Related: #399)
|
||||
- **Voice Focus controls.** Stop and immediate spoken steering remain accessible while Hermes is Thinking, Transcribing, or Speaking, including TalkBack, Switch Access, keyboard, and sideload overlay surfaces.
|
||||
- **Upstream-first standard surfaces.** Chat attachments, inbound host files, current-session Git reads, Nous usage bars, and keyed Hermes notices use authenticated Dashboard/Gateway contracts first. Relay remains an additive compatibility and enhancement layer.
|
||||
- **Clear Settings ownership.** Media sits with Chat and Voice under Hermes. Proactive Threads, Terminal, Notification Companion, Relay sessions, enhanced voice, and Device Control stay grouped under Relay tools.
|
||||
- **App-specific supervised parent access.** Parents choose a PIN or password and receive a six-word recovery phrase; Android device credentials and biometrics no longer grant parent authority.
|
||||
- **Complete What's New history.** Release highlights, the remaining improvements and fixes, compatibility notes, toast counts, and history now come from one structured inventory.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Wake-word detection packages one compatible ONNX Runtime for sherpa and Java JNI on every supported ABI. (#444)
|
||||
- Continuous voice waits for barge-in microphone teardown before listening again. (#464)
|
||||
- Fresh chats retain their selected profile without reopening a previous session or carrying a proactive Thread route across profiles. (#436)
|
||||
- Provisional Threads can be removed locally and reconcile with promoted sessions without deleting server history. (#461)
|
||||
- Clarify cards expose a reachable Other answer, keyboard Send, and authoritative expiry behavior. (#446)
|
||||
- Passive Android browsing no longer claims or interrupts a turn owned by another client. (Related: #365)
|
||||
- Assistant sessions show retryable no-speech feedback, recover their active state after recreation, and redact conversation details behind the keyguard. (Related: #424)
|
||||
- Protected Relay ingress `401/403` responses are recognized as authentication boundaries rather than outages; malformed, different-origin, and direct unauthorized routes still fail closed.
|
||||
- Host-local images, audio, video, and files download through the authenticated Dashboard and remain loaded across history reconciliation instead of flashing `Relay URL not configured` or returning to Loading.
|
||||
- Standard voice remains usable after explicit Relay removal, while temporary Relay outages preserve configured choices and default-profile preferences stay isolated across connections.
|
||||
- Android can display uniquely matched Desktop/TUI Working and Waiting activity without resuming, activating, or interrupting the external turn.
|
||||
- Dashboard/Gateway chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing to Direct API.
|
||||
- Completed text survives Dashboard-history authentication expiry and returns the existing sign-in recovery path.
|
||||
- Long-running context compaction refreshes the turn watchdog instead of being interrupted as idle.
|
||||
- Bot Chat history renders immediately after its route-owned handler binds.
|
||||
- An exact idle live-session snapshot settles an Android-owned turn whose terminal frame was lost, reconciles history, and drains its queued follow-up.
|
||||
- Supervised Add Gateway remains parent-owned across relock, back navigation, and pending setup cancellation.
|
||||
- Completed generated images stay visible during marker persistence lag and retain the intended image-generation presentation.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.14.0** (versionCode **52**).
|
||||
- Standard Chat, sessions, profiles, Manage, and standard voice continue to work against unmodified upstream Hermes without the optional Relay plugin.
|
||||
- Install Hermes-Relay Plugin v1.11.0 for same-origin Relay extensions, Git workspace actions, Bridge, media, proactive features, and enhanced voice.
|
||||
- App version: **1.15.0** (versionCode **53**).
|
||||
- Standard Chat, sessions, profiles, Manage, standard voice, outbound attachments, and ordinary inbound files work against current unmodified upstream Hermes without the optional Hermes-Relay Plugin.
|
||||
- Install Hermes-Relay Plugin v1.11.1 for Terminal, proactive Threads/offline delivery, Notification Companion, Relay sessions, provider-native/realtime voice, compatibility media metadata, Secure Link, and phone/device control.
|
||||
- Explicit Direct API/API-only connections remain supported and are never used as a silent failover for a Dashboard-owned chat.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
|
||||
- Existing connections, drafts, sessions, profile ownership, and legacy direct Relay routes remain data-preserving compatibility paths.
|
||||
|
||||
@@ -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
|
||||
@@ -20,6 +45,32 @@ compatibility route.
|
||||
|
||||
---
|
||||
|
||||
## Upstream an Android Gateway platform hint
|
||||
|
||||
Android currently identifies its standard Gateway sessions with the legacy
|
||||
`webui` source because upstream has no stable Android/mobile session platform.
|
||||
Current upstream deliberately removed the unused `webui` prompt hint and only
|
||||
ships renderer-verified `desktop` and `tui` guidance. Do not relabel Android as
|
||||
Desktop: that would also advertise Desktop-only inline widgets and directives.
|
||||
Propose an upstream Android/mobile platform hint, or a bounded authenticated
|
||||
client-surface context contract, that accurately describes mobile Markdown,
|
||||
standard upstream media/file delivery, and concise-response expectations. Once
|
||||
that contract is available in the supported Hermes baseline, adopt it and add
|
||||
Gateway conformance coverage proving the exact prompt bytes and session source.
|
||||
|
||||
---
|
||||
|
||||
## Scope sensitive-media prompt guidance to capable clients
|
||||
|
||||
The Relay plugin's sensitive-media prompt section currently describes the
|
||||
Android `||||` and alt-text conventions profile-wide. Before
|
||||
expanding that behavior, make the section depend on an authoritative client
|
||||
capability or replace it with a portable convention verified against every
|
||||
renderer that receives the profile prompt. Do not make Desktop/TUI sessions
|
||||
emit Android-only spoiler syntax merely because the Relay plugin is installed.
|
||||
|
||||
---
|
||||
|
||||
## Certify Android session activity across lifecycle and profile boundaries
|
||||
|
||||
The contract fixture now covers every upstream live status, complete-snapshot
|
||||
@@ -28,8 +79,11 @@ and older Gateways without `session.active_list`. Before calling the status
|
||||
model device-certified:
|
||||
|
||||
- Exercise working, quiet tool-heavy work, each pending-input surface, normal
|
||||
completion, Stop, reconnect, app restart, and process recreation against
|
||||
current vanilla upstream.
|
||||
completion, a lost terminal followed by an exact active-list Idle row, Stop,
|
||||
reconnect, app restart, and process recreation against current vanilla
|
||||
upstream. Confirm the lost-terminal path preserves the partial transcript,
|
||||
settles composer/steering state, and drains or cancels queued corrections
|
||||
exactly once according to the owning turn outcome.
|
||||
- Verify All Profiles with duplicate session ids across two profiles and two
|
||||
saved connections; no late snapshot or old socket generation may mark the
|
||||
wrong row live.
|
||||
|
||||
@@ -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
|
||||
|
||||
+241
-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")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,6 +258,46 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActiveList_settlesExactOwnedTurnAndRendersAuthoritativeHistory() {
|
||||
viewModel.sendMessage("Run an Android-owned task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", PARTIAL_ANSWER) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.activeSessionStatus = "idle"
|
||||
runBlocking { gatewayClient.listActiveSessions() }
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gatewayClient.hasActiveTurn() &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
assertEquals(0, fixture.rpcCount("session.interrupt"))
|
||||
assertEquals(0, fixture.rpcCount("session.activate"))
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
@@ -252,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(
|
||||
@@ -269,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)
|
||||
@@ -293,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"
|
||||
@@ -301,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,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)
|
||||
@@ -377,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)
|
||||
}
|
||||
}
|
||||
@@ -388,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 =
|
||||
@@ -406,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)
|
||||
@@ -415,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)
|
||||
@@ -425,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() {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 509 KiB |
@@ -1,3 +1,3 @@
|
||||
v1.14.0 - Connections that follow you
|
||||
v1.15.0 - Standard Hermes first, with clearer Relay boundaries
|
||||
|
||||
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.
|
||||
Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.
|
||||
|
||||
@@ -1,55 +1,222 @@
|
||||
{
|
||||
"schema": 2,
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.14.0",
|
||||
"title": "Connections that follow you",
|
||||
"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": [
|
||||
"version": "1.15.0",
|
||||
"title": "Standard Hermes first, with clearer Relay boundaries",
|
||||
"date": "2026-08-31",
|
||||
"summary": "Chat, voice, attachments, inbound files, current-session Git, usage, and Hermes notices now prefer current upstream Dashboard and Gateway support. Relay stays optional for compatibility and the tools it uniquely provides.",
|
||||
"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": "upstream-standard-surfaces",
|
||||
"kind": "improved",
|
||||
"title": "Use standard Hermes without Relay prompts",
|
||||
"summary": "Chat attachments, inbound files, current-session Git, Nous usage, and Hermes notices use upstream routes first.",
|
||||
"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": "stable-inbound-media",
|
||||
"kind": "fixed",
|
||||
"title": "Keep returned files loaded",
|
||||
"summary": "Images, audio, video, and documents download through the Dashboard and no longer flash Relay errors or return to Loading.",
|
||||
"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": "supervised-parent-access",
|
||||
"kind": "improved",
|
||||
"title": "Use app-specific parent access",
|
||||
"summary": "A parent PIN or password plus recovery phrase protects Supervised Mode without trusting the phone unlock credential.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "settings-relay-boundaries",
|
||||
"kind": "improved",
|
||||
"title": "See which features need Relay",
|
||||
"summary": "Media sits with standard Hermes settings while Threads, Terminal, notifications, enhanced voice, and device tools stay under Relay tools."
|
||||
},
|
||||
{
|
||||
"id": "complete-release-history",
|
||||
"kind": "improved",
|
||||
"title": "Read the complete release record",
|
||||
"summary": "What's New shows one release summary, selected highlights, every remaining change, and relevant compatibility notes."
|
||||
},
|
||||
{
|
||||
"id": "relay-removal-voice",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Standard voice after removing Relay",
|
||||
"summary": "Dashboard voice remains ready, temporary outages preserve choices, and shared default-profile settings stay isolated."
|
||||
},
|
||||
{
|
||||
"id": "passive-external-activity",
|
||||
"kind": "fixed",
|
||||
"title": "Observe another client's activity safely",
|
||||
"summary": "A uniquely matched Desktop or TUI turn can show Working or Waiting without Android taking control."
|
||||
},
|
||||
{
|
||||
"id": "chat-transport-ownership",
|
||||
"kind": "fixed",
|
||||
"title": "Keep each chat on its chosen transport",
|
||||
"summary": "Dashboard chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing databases."
|
||||
},
|
||||
{
|
||||
"id": "history-auth-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Preserve completed replies at sign-in expiry",
|
||||
"summary": "A Dashboard history authentication failure keeps completed text visible and opens the existing sign-in recovery path."
|
||||
},
|
||||
{
|
||||
"id": "compaction-watchdog",
|
||||
"kind": "fixed",
|
||||
"title": "Let long context compaction finish",
|
||||
"summary": "Visible compaction activity refreshes the turn watchdog instead of being interrupted as idle."
|
||||
},
|
||||
{
|
||||
"id": "bot-chat-binding",
|
||||
"kind": "fixed",
|
||||
"title": "Render Bot Chat history immediately",
|
||||
"summary": "Route-owned Bot Chats observe their bound history from first composition."
|
||||
},
|
||||
{
|
||||
"id": "missing-terminal-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Settle turns after a lost terminal frame",
|
||||
"summary": "An exact idle live-session snapshot reconciles the Android-owned turn and drains its queued follow-up."
|
||||
},
|
||||
{
|
||||
"id": "supervised-gateway-setup",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Gateway setup parent-owned",
|
||||
"summary": "Relock and back navigation cancel the exact pending setup without bypassing parent authority."
|
||||
},
|
||||
{
|
||||
"id": "generated-image-retention",
|
||||
"kind": "fixed",
|
||||
"title": "Keep completed generated images visible",
|
||||
"summary": "Generated media survives marker persistence lag and retains its intended Chat animation."
|
||||
}
|
||||
]
|
||||
],
|
||||
"compatibility": [
|
||||
"Current upstream Hermes provides standard Chat, sessions, Manage, voice, attachments, inbound files, current-session Git reads, usage, and notices without the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.1 remains required for Terminal, proactive Threads and offline delivery, Notification Companion, Relay sessions, enhanced voice, Secure Link, and phone or device control.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain sideload-only."
|
||||
],
|
||||
"playNotes": "Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.14.0",
|
||||
"title": "Connections, delegated work, Git, and voice",
|
||||
"date": "2026-08-30",
|
||||
"summary": "Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "route-aware-connections",
|
||||
"kind": "improved",
|
||||
"title": "Connections recover independently",
|
||||
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "delegated-agent-previews",
|
||||
"kind": "added",
|
||||
"title": "Follow delegated-agent activity",
|
||||
"summary": "See lifecycle, progress, tool previews, and available read-only child history from the parent chat.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "native-git-workspace",
|
||||
"kind": "added",
|
||||
"title": "Work with repositories from Android",
|
||||
"summary": "Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "voice-focus-controls",
|
||||
"kind": "improved",
|
||||
"title": "Steer voice at any time",
|
||||
"summary": "Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "non-blocking-release-notice",
|
||||
"kind": "improved",
|
||||
"title": "Release notes stay out of your way",
|
||||
"summary": "A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings."
|
||||
},
|
||||
{
|
||||
"id": "single-chat-presentation",
|
||||
"kind": "improved",
|
||||
"title": "Chat uses one consistent presentation",
|
||||
"summary": "The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available."
|
||||
},
|
||||
{
|
||||
"id": "wake-word-runtime",
|
||||
"kind": "fixed",
|
||||
"title": "Wake-word detection starts reliably",
|
||||
"summary": "Compatible native voice components are now packaged for every supported phone architecture."
|
||||
},
|
||||
{
|
||||
"id": "sphere-motion",
|
||||
"kind": "fixed",
|
||||
"title": "The visible Sphere keeps moving smoothly",
|
||||
"summary": "Foreground animation no longer falls back to a stepped ambient pulse."
|
||||
},
|
||||
{
|
||||
"id": "continuous-microphone-handoff",
|
||||
"kind": "fixed",
|
||||
"title": "Continuous voice keeps the microphone",
|
||||
"summary": "The next listening turn waits for barge-in recording to release cleanly."
|
||||
},
|
||||
{
|
||||
"id": "fresh-profile-drafts",
|
||||
"kind": "fixed",
|
||||
"title": "New chats keep the selected profile",
|
||||
"summary": "Fresh drafts no longer reopen an older session or carry a Thread route into another profile."
|
||||
},
|
||||
{
|
||||
"id": "provisional-thread-removal",
|
||||
"kind": "fixed",
|
||||
"title": "Provisional Threads can be removed safely",
|
||||
"summary": "Local removal and later session promotion no longer risk duplicate rows or server history."
|
||||
},
|
||||
{
|
||||
"id": "clarify-custom-answers",
|
||||
"kind": "fixed",
|
||||
"title": "Clarify keeps custom answers reachable",
|
||||
"summary": "Other answers, keyboard Send, and expired prompts now behave consistently."
|
||||
},
|
||||
{
|
||||
"id": "passive-session-observation",
|
||||
"kind": "fixed",
|
||||
"title": "Browsing no longer interrupts another client",
|
||||
"summary": "Passive Android observation does not claim a turn owned by Desktop, TUI, or another client."
|
||||
},
|
||||
{
|
||||
"id": "assistant-recovery-privacy",
|
||||
"kind": "fixed",
|
||||
"title": "Assistant sessions recover more clearly",
|
||||
"summary": "No-speech feedback, recreated session state, and keyguard privacy now remain intact."
|
||||
},
|
||||
{
|
||||
"id": "relay-auth-boundaries",
|
||||
"kind": "fixed",
|
||||
"title": "Protected Relay routes report the right problem",
|
||||
"summary": "Authentication challenges are no longer presented as outages, while unsafe routes still fail closed."
|
||||
},
|
||||
{
|
||||
"id": "connection-session-readiness",
|
||||
"kind": "fixed",
|
||||
"title": "Connections and sessions become ready sooner",
|
||||
"summary": "Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.",
|
||||
"The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain available only in the sideload build."
|
||||
],
|
||||
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.13.2",
|
||||
|
||||
@@ -1,10 +1,29 @@
|
||||
v1.14.0 - Connections that follow you
|
||||
v1.15.0 - Standard Hermes first, with clearer Relay boundaries
|
||||
|
||||
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
|
||||
* Chat, voice, attachments, inbound files, current-session Git, usage, and Hermes notices now prefer current upstream Dashboard and Gateway support. Relay stays optional for compatibility and the tools it uniquely provides.
|
||||
|
||||
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
|
||||
* Use standard Hermes without Relay prompts — Chat attachments, inbound files, current-session Git, Nous usage, and Hermes notices use upstream routes first.
|
||||
* Keep returned files loaded — Images, audio, video, and documents download through the Dashboard and no longer flash Relay errors or return to Loading.
|
||||
* Use app-specific parent access — A parent PIN or password plus recovery phrase protects Supervised Mode without trusting the phone unlock credential.
|
||||
|
||||
Improved
|
||||
* See which features need Relay — Media sits with standard Hermes settings while Threads, Terminal, notifications, enhanced voice, and device tools stay under Relay tools.
|
||||
* Read the complete release record — What's New shows one release summary, selected highlights, every remaining change, and relevant compatibility notes.
|
||||
|
||||
Fixed
|
||||
* Keep Standard voice after removing Relay — Dashboard voice remains ready, temporary outages preserve choices, and shared default-profile settings stay isolated.
|
||||
* Observe another client's activity safely — A uniquely matched Desktop or TUI turn can show Working or Waiting without Android taking control.
|
||||
* Keep each chat on its chosen transport — Dashboard chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing databases.
|
||||
* Preserve completed replies at sign-in expiry — A Dashboard history authentication failure keeps completed text visible and opens the existing sign-in recovery path.
|
||||
* Let long context compaction finish — Visible compaction activity refreshes the turn watchdog instead of being interrupted as idle.
|
||||
* Render Bot Chat history immediately — Route-owned Bot Chats observe their bound history from first composition.
|
||||
* Settle turns after a lost terminal frame — An exact idle live-session snapshot reconciles the Android-owned turn and drains its queued follow-up.
|
||||
* Keep Gateway setup parent-owned — Relock and back navigation cancel the exact pending setup without bypassing parent authority.
|
||||
* Keep completed generated images visible — Generated media survives marker persistence lag and retains its intended Chat animation.
|
||||
|
||||
Compatibility
|
||||
* Current upstream Hermes provides standard Chat, sessions, Manage, voice, attachments, inbound files, current-session Git reads, usage, and notices without the optional Hermes-Relay Plugin.
|
||||
* Hermes-Relay Plugin 1.11.1 remains required for Terminal, proactive Threads and offline delivery, Notification Companion, Relay sessions, enhanced voice, Secure Link, and phone or device control.
|
||||
* Granular Device Control and the system Voice Focus overlay remain sideload-only.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardHttpException
|
||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
||||
import java.io.IOException
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
@@ -9,113 +15,178 @@ import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
// Read + write client for the Hermes-Relay Git State endpoints.
|
||||
// All requests are confined to the ``hermes-relay`` plugin namespace and the
|
||||
// ``git/*`` sub-path via ScopedPluginApiClient, which rejects traversal and
|
||||
// encodes query values.
|
||||
|
||||
private fun pathsArray(paths: List<String>) = buildJsonArray { paths.forEach { add(JsonPrimitive(it)) } }
|
||||
|
||||
/**
|
||||
* Uses official Dashboard `/api/git/…` reads for the active session repository.
|
||||
* Relay remains the discovery source and owns stronger write/preview extensions.
|
||||
* Operational upstream failures are never hidden by a Relay retry; only a 404
|
||||
* can fall back to a matching Relay-discovered repository.
|
||||
*/
|
||||
class GitStateApiClient(
|
||||
dashboard: DashboardApiClient,
|
||||
private val dashboard: DashboardApiClient,
|
||||
) {
|
||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val reposById = linkedMapOf<String, GitRepo>()
|
||||
private val relayRepoIdsByRoot = linkedMapOf<String, String>()
|
||||
|
||||
suspend fun repos(): Result<List<GitRepo>> = scoped
|
||||
.get("git/repos")
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<ReposResponse>(element).repos
|
||||
suspend fun repos(
|
||||
sessionRepoPath: String? = null,
|
||||
includeRelayDiscovery: Boolean = true,
|
||||
): Result<List<GitRepo>> {
|
||||
reposById.clear()
|
||||
relayRepoIdsByRoot.clear()
|
||||
val path = sessionRepoPath?.trim().orEmpty()
|
||||
if (path.isBlank()) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
suspend fun status(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitStatus>(element) }
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<BranchesResponse>(element).branches
|
||||
val upstream = upstreamStatus(path)
|
||||
if (upstream.isFailure) {
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.failure(error)
|
||||
}
|
||||
val status = upstream.getOrNull()
|
||||
if (status == null) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitDiff>(element) }
|
||||
val standardRepo = GitRepo(
|
||||
id = UPSTREAM_SESSION_REPO_ID,
|
||||
name = path.replace('\\', '/').trimEnd('/').substringAfterLast('/').ifBlank { path },
|
||||
root = path,
|
||||
currentBranch = status.branch,
|
||||
dirty = status.changed > 0,
|
||||
route = GitRepositoryRoute.UPSTREAM,
|
||||
)
|
||||
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitFile>(element) }
|
||||
// Plugin discovery is an enhancement. Once upstream answered, plugin
|
||||
// absence or breakage cannot take the standard session repository down.
|
||||
val relay = if (includeRelayDiscovery) relayRepos().getOrDefault(emptyList()) else emptyList()
|
||||
val merged = buildList {
|
||||
add(standardRepo)
|
||||
addAll(relay.filterNot { sameRoot(it.root, standardRepo.root) })
|
||||
}
|
||||
rememberRepos(merged)
|
||||
rememberRelayRepos(relay)
|
||||
return Result.success(merged)
|
||||
}
|
||||
|
||||
// ── Write operations ───────────────────────────────────────────────────
|
||||
// Every write requires the plugin.api.write grant, which the app enforces
|
||||
// (see GitStateViewModel: a POST is never sent without the grant). The
|
||||
// server additionally enforces per-use confirmation strings for destructive
|
||||
// ops (discard/push/dirty-checkout) — the caller passes the echoed token.
|
||||
suspend fun status(repo: String): Result<GitStatus> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayStatus(repo)
|
||||
return fallbackOnUnsupported(target, upstreamStatusWithFiles(target.root), ::relayStatus)
|
||||
}
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayBranches(repo)
|
||||
return fallbackOnUnsupported(target, upstreamBranches(target.root), ::relayBranches)
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayDiff(repo, path, kind)
|
||||
val upstream = dashboard.getJsonElement(
|
||||
upstreamPath(
|
||||
"/api/git/review/diff",
|
||||
mapOf(
|
||||
"path" to target.root,
|
||||
"file" to path,
|
||||
"scope" to "uncommitted",
|
||||
"staged" to (kind == "staged").toString(),
|
||||
),
|
||||
),
|
||||
).mapCatching { element ->
|
||||
GitDiff(
|
||||
path = path,
|
||||
kind = kind,
|
||||
diff = json.decodeFromJsonElement<UpstreamDiffResponse>(element).diff,
|
||||
)
|
||||
}
|
||||
return fallbackOnUnsupported(target, upstream) { relay -> relayDiff(relay, path, kind) }
|
||||
}
|
||||
|
||||
/** Clean tracked-file preview is a Relay enhancement; file-diff is not equivalent. */
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("Tracked-file preview requires the Relay plugin"))
|
||||
return relayFile(relay, path)
|
||||
}
|
||||
|
||||
// Writes intentionally stay on Relay. The upstream Desktop mutation shape
|
||||
// does not carry plugin.api.write or the server-enforced confirmation echoes
|
||||
// used by this mobile surface, so it is not an equivalent safety contract.
|
||||
|
||||
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun discard(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
put("confirmation", confirmation)
|
||||
put("delete_untracked", deleteUntracked)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||
scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commitSelected(
|
||||
repo: String,
|
||||
message: String,
|
||||
paths: List<String>,
|
||||
): Result<GitMutationResult> = scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||
scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||
scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun push(
|
||||
repo: String,
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
): Result<GitMutationResult> = scoped.post("git/push", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/push", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
put("confirmation", confirmation)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun checkout(
|
||||
repo: String,
|
||||
@@ -123,41 +194,217 @@ class GitStateApiClient(
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (confirmation != null) put("confirmation", confirmation)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
// ── Phase 3 extras ─────────────────────────────────────────────────────
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> = relayWrite(repo) { relay ->
|
||||
scoped.post("git/commit_message", buildJsonObject { put("repo", relay) })
|
||||
.mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
}
|
||||
|
||||
/** Generate a commit-message suggestion from the staged diff. */
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> =
|
||||
scoped.post("git/commit_message", buildJsonObject {
|
||||
put("repo", repo)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
suspend fun commitMessageSelected(repo: String, paths: List<String>): Result<GitCommitMessage> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) } }
|
||||
|
||||
/** Generate a commit-message suggestion from the given paths' staged diff. */
|
||||
suspend fun commitMessageSelected(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
): Result<GitCommitMessage> = scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
|
||||
/** Checkout that auto-stashes a dirty tree first. */
|
||||
suspend fun stashCheckout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitStashCheckoutResult> = scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitStashCheckoutResult> = relayWrite(repo) { relay -> scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) }
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) } }
|
||||
|
||||
private suspend fun relayRepos(): Result<List<GitRepo>> = scoped.get("git/repos").mapCatching {
|
||||
json.decodeFromJsonElement<ReposResponse>(it).repos
|
||||
}
|
||||
|
||||
private suspend fun relayStatus(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<GitStatus>(it) }
|
||||
|
||||
private suspend fun relayBranches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<BranchesResponse>(it).branches }
|
||||
|
||||
private suspend fun relayDiff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { json.decodeFromJsonElement<GitDiff>(it) }
|
||||
|
||||
private suspend fun relayFile(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { json.decodeFromJsonElement<GitFile>(it) }
|
||||
|
||||
private suspend fun upstreamStatus(path: String): Result<UpstreamStatus?> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/status", mapOf("path" to path)))
|
||||
.mapCatching { json.decodeFromJsonElement<UpstreamStatus?>(it) }
|
||||
|
||||
private suspend fun upstreamStatusWithFiles(path: String): Result<GitStatus> {
|
||||
val status = upstreamStatus(path).mapCatching {
|
||||
it ?: throw IOException("The active session path is not a Git repository")
|
||||
}.getOrElse { return Result.failure(it) }
|
||||
val review = dashboard.getJsonElement(
|
||||
upstreamPath("/api/git/review/list", mapOf("path" to path, "scope" to "uncommitted")),
|
||||
).mapCatching { json.decodeFromJsonElement<UpstreamReviewList>(it) }
|
||||
.getOrElse { return Result.failure(it) }
|
||||
val statusByPath = status.files.associateBy { it.path }
|
||||
val staged = mutableListOf<GitStatusEntry>()
|
||||
val modified = mutableListOf<GitStatusEntry>()
|
||||
val untracked = mutableListOf<GitStatusEntry>()
|
||||
review.files.forEach { file ->
|
||||
val entry = GitStatusEntry(file.path, file.added, file.removed)
|
||||
val fileStatus = statusByPath[file.path]
|
||||
if (fileStatus?.untracked == true) {
|
||||
untracked += entry
|
||||
} else {
|
||||
if (file.staged || fileStatus?.staged == true) staged += entry
|
||||
if (fileStatus?.unstaged == true || (!file.staged && fileStatus == null)) {
|
||||
modified += entry
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result.success(
|
||||
GitStatus(
|
||||
counts = GitStatusCounts(
|
||||
staged = status.staged,
|
||||
modified = status.unstaged,
|
||||
untracked = status.untracked,
|
||||
changes = status.changed,
|
||||
additions = status.added,
|
||||
deletions = status.removed,
|
||||
),
|
||||
staged = staged,
|
||||
modified = modified,
|
||||
untracked = untracked,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun upstreamBranches(path: String): Result<List<GitBranch>> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/branches", mapOf("path" to path)))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<UpstreamBranches>(element).branches.map {
|
||||
GitBranch(name = it.name, isCurrent = it.checkedOut)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> fallbackOnUnsupported(
|
||||
target: GitRepo,
|
||||
upstream: Result<T>,
|
||||
relayCall: suspend (String) -> Result<T>,
|
||||
): Result<T> {
|
||||
if (upstream.isSuccess) return upstream
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
val relay = relayRepoIdsByRoot[normalizedRoot(target.root)] ?: return Result.failure(error)
|
||||
return relayCall(relay)
|
||||
}
|
||||
|
||||
private suspend fun <T> relayWrite(repo: String, block: suspend (String) -> Result<T>): Result<T> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("This Git action requires the Relay plugin enhancement"))
|
||||
return block(relay)
|
||||
}
|
||||
|
||||
private fun relayRepoId(repo: String): String? {
|
||||
val target = reposById[repo] ?: return repo.takeUnless { it == UPSTREAM_SESSION_REPO_ID }
|
||||
return if (target.route == GitRepositoryRoute.RELAY) target.id
|
||||
else relayRepoIdsByRoot[normalizedRoot(target.root)]
|
||||
}
|
||||
|
||||
private fun rememberRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { reposById[it.id] = it }
|
||||
rememberRelayRepos(repos.filter { it.route == GitRepositoryRoute.RELAY })
|
||||
}
|
||||
|
||||
private fun rememberRelayRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { relayRepoIdsByRoot[normalizedRoot(it.root)] = it.id }
|
||||
}
|
||||
|
||||
private fun upstreamPath(path: String, query: Map<String, String>): String = buildString {
|
||||
append(path)
|
||||
if (query.isNotEmpty()) {
|
||||
append('?')
|
||||
append(query.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" })
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String =
|
||||
URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
|
||||
|
||||
private fun normalizedRoot(path: String): String {
|
||||
val normalized = path.trim().replace('\\', '/').trimEnd('/')
|
||||
return if (WINDOWS_ROOT.containsMatchIn(normalized) || normalized.startsWith("//")) {
|
||||
normalized.lowercase(Locale.ROOT)
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
private fun sameRoot(first: String, second: String): Boolean =
|
||||
normalizedRoot(first) == normalizedRoot(second)
|
||||
|
||||
private fun Result<kotlinx.serialization.json.JsonObject>.decodeMutation(): Result<GitMutationResult> =
|
||||
mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
private fun Throwable.isUnsupportedGitRoute(): Boolean =
|
||||
this is DashboardHttpException && statusCode == 404
|
||||
|
||||
private companion object {
|
||||
const val UPSTREAM_SESSION_REPO_ID = "__upstream_session__"
|
||||
val WINDOWS_ROOT = Regex("^[A-Za-z]:/")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatus(
|
||||
val branch: String? = null,
|
||||
val staged: Int = 0,
|
||||
val unstaged: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
val changed: Int = 0,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val files: List<UpstreamStatusFile> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatusFile(
|
||||
val path: String,
|
||||
val staged: Boolean = false,
|
||||
val unstaged: Boolean = false,
|
||||
val untracked: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewList(val files: List<UpstreamReviewFile> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewFile(
|
||||
val path: String,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val staged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranches(val branches: List<UpstreamBranch> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranch(
|
||||
val name: String,
|
||||
@SerialName("checkedOut") val checkedOut: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamDiffResponse(val diff: String = "")
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.hermesandroid.relay.data
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** A repository discovered by the plugin's /git/repos endpoint. */
|
||||
/** A current-session upstream repository or a Relay-discovered repository. */
|
||||
@Serializable
|
||||
data class GitRepo(
|
||||
val id: String,
|
||||
@@ -11,9 +11,19 @@ data class GitRepo(
|
||||
val root: String,
|
||||
@SerialName("current_branch") val currentBranch: String? = null,
|
||||
val dirty: Boolean = false,
|
||||
val route: GitRepositoryRoute = GitRepositoryRoute.RELAY,
|
||||
)
|
||||
|
||||
/** Working-tree status from /git/status. */
|
||||
@Serializable
|
||||
enum class GitRepositoryRoute {
|
||||
@SerialName("relay")
|
||||
RELAY,
|
||||
|
||||
@SerialName("upstream")
|
||||
UPSTREAM,
|
||||
}
|
||||
|
||||
/** Normalized working-tree status from upstream or Relay Git routes. */
|
||||
@Serializable
|
||||
data class GitStatus(
|
||||
val counts: GitStatusCounts = GitStatusCounts(),
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -344,6 +344,46 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
|
||||
dataStore.edit { it[key] = route.storageValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Relay-only selections after Relay has been explicitly removed from
|
||||
* the active connection. A temporarily unreachable configured Relay must
|
||||
* not call this: preserving the selection lets the richer route resume
|
||||
* when connectivity returns.
|
||||
*
|
||||
* [expectedScope] fences profile/connection changes that can race the
|
||||
* DataStore edit. Values are re-read inside the transaction instead of
|
||||
* trusting an earlier settings snapshot, so a newer user choice wins.
|
||||
* The legacy default-profile keys are global (their storage names predate
|
||||
* connection scoping), so they are never rewritten here: runtime fallback
|
||||
* handles an unpaired default profile without changing another
|
||||
* connection's selection.
|
||||
*/
|
||||
suspend fun reconcileRelayRemoval(expectedScope: VoiceProfileScope): Boolean {
|
||||
if (_scope.value != expectedScope || expectedScope.profileName == null) return false
|
||||
var changed = false
|
||||
dataStore.edit { prefs ->
|
||||
if (_scope.value != expectedScope) return@edit
|
||||
|
||||
val engine = VoiceEngineMode.fromStorage(
|
||||
resolveString(prefs, KEY_ENGINE_MODE, expectedScope, DEFAULT_ENGINE_MODE),
|
||||
)
|
||||
val route = VoiceAudioRoute.fromStorage(
|
||||
resolveString(prefs, KEY_AUDIO_ROUTE, expectedScope, DEFAULT_AUDIO_ROUTE),
|
||||
)
|
||||
if (engine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_ENGINE_MODE, expectedScope))] =
|
||||
VoiceEngineMode.HermesVoiceOutput.storageValue
|
||||
changed = true
|
||||
}
|
||||
if (route == VoiceAudioRoute.Relay) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_AUDIO_ROUTE, expectedScope))] =
|
||||
VoiceAudioRoute.Auto.storageValue
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/** "" clears the override (relay falls back to the server's saved voice). */
|
||||
suspend fun setEnhancedVoice(voice: String) {
|
||||
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
||||
|
||||
@@ -28,6 +28,7 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
||||
|
||||
@@ -88,6 +89,7 @@ class RelayHttpClient(
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayHttpClient"
|
||||
private const val DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES = 100L * 1024L * 1024L
|
||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
|
||||
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
|
||||
@@ -257,7 +259,10 @@ class RelayHttpClient(
|
||||
* underlying exception with a human-readable message suitable for
|
||||
* surfacing in the attachment's `errorMessage` field.
|
||||
*/
|
||||
suspend fun fetchMedia(token: String): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
suspend fun fetchMedia(
|
||||
token: String,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
return@withContext Result.failure(
|
||||
@@ -318,7 +323,7 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
@@ -352,6 +357,7 @@ class RelayHttpClient(
|
||||
suspend fun fetchMediaByPath(
|
||||
path: String,
|
||||
contentTypeHint: String? = null,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
@@ -427,12 +433,16 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMediaByPath failed for $path: ${e.message}")
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
if (e is RelayMediaLimitException) {
|
||||
Result.failure(e)
|
||||
} else {
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
||||
Result.failure(e)
|
||||
@@ -1456,6 +1466,33 @@ class RelayHttpClient(
|
||||
return match?.groupValues?.get(1)?.trim()?.ifBlank { null }
|
||||
}
|
||||
|
||||
private fun okhttp3.ResponseBody.readBytesBounded(maxBytes: Long): ByteArray {
|
||||
if (maxBytes <= 0L) throw RelayMediaLimitException()
|
||||
val declared = contentLength().takeIf { it >= 0L }
|
||||
if (declared != null && declared > maxBytes) throw RelayMediaLimitException()
|
||||
val output = ByteArrayOutputStream(
|
||||
declared?.coerceAtMost(Int.MAX_VALUE.toLong())?.toInt() ?: DEFAULT_BUFFER_SIZE,
|
||||
)
|
||||
byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
if (total > maxBytes) throw RelayMediaLimitException()
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
if (declared != null && total != declared) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
private class RelayMediaLimitException :
|
||||
IOException("File exceeds the configured download limit")
|
||||
|
||||
/**
|
||||
* Parse the relay's `X-Media-Sensitive` response header into a bool.
|
||||
*
|
||||
@@ -1468,7 +1505,7 @@ class RelayHttpClient(
|
||||
return value == "1" || value == "true"
|
||||
}
|
||||
|
||||
/** Provider-neutral compatibility fetch for gateways without `account.usage`. */
|
||||
/** Provider-neutral enhancement for pools and providers upstream does not expose. */
|
||||
suspend fun fetchProviderUsage(
|
||||
profile: String? = null,
|
||||
sessionId: String? = null,
|
||||
|
||||
@@ -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,34 @@ 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. Exact inbound marker attachments are also
|
||||
// carried by id: a history refresh must not replace a successfully
|
||||
// loaded image/file with a fresh LOADING placeholder. A process
|
||||
// restart has no prior attachment, so the marker still dispatches
|
||||
// normally and rehydrates it. One additional narrow exception
|
||||
// retains a completed image_generate result when the immediate
|
||||
// post-turn history read still lacks its MEDIA marker.
|
||||
val carriedAttachments = run {
|
||||
val persistedImagePaths = persistedImages.paths.toHashSet()
|
||||
val persistedMediaKeys = messageMediaHits.mapTo(HashSet()) { (_, hit) ->
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> hit.token
|
||||
is MediaMarkerHit.BarePath -> hit.path
|
||||
}
|
||||
}
|
||||
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 ||
|
||||
attachment.relayToken in persistedMediaKeys ||
|
||||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
||||
(
|
||||
role == MessageRole.USER &&
|
||||
attachment.relayToken in persistedImagePaths
|
||||
role == MessageRole.ASSISTANT &&
|
||||
priorGeneratedImage &&
|
||||
attachment.isImage &&
|
||||
messageMediaHits.isEmpty()
|
||||
)
|
||||
}
|
||||
when {
|
||||
@@ -1695,15 +1717,27 @@ class ChatHandler {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.token } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.path } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+132
-8
@@ -52,6 +52,7 @@ import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resume
|
||||
@@ -310,6 +311,19 @@ data class ElevenLabsVoices(
|
||||
val voices: List<ElevenLabsVoice>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Bytes fetched from upstream's authenticated managed-files surface.
|
||||
*
|
||||
* The Dashboard applies its own managed-root, sensitive-file, and maximum-size
|
||||
* policy before these bytes leave the Hermes host. Android applies the user's
|
||||
* stricter inbound-media cap while reading the response as a second boundary.
|
||||
*/
|
||||
data class DashboardFetchedFile(
|
||||
val bytes: ByteArray,
|
||||
val contentType: String,
|
||||
val fileName: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Native client for the Hermes dashboard/admin server (:9119).
|
||||
*
|
||||
@@ -381,6 +395,75 @@ class DashboardApiClient(
|
||||
executeJsonElement(request, normalized)
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a server-local artifact through current upstream Hermes.
|
||||
*
|
||||
* This is the same authenticated `/api/files/download` route official
|
||||
* Desktop uses for remote gateway files. The caller supplies its display
|
||||
* cap so a malicious or stale Content-Length cannot cause an unbounded
|
||||
* allocation. Audio/video are downloaded into Android's local media cache;
|
||||
* local playback supplies seeking, so `/api/files/stream` is unnecessary
|
||||
* on this path.
|
||||
*/
|
||||
suspend fun downloadManagedFile(
|
||||
serverPath: String,
|
||||
maxBytes: Long,
|
||||
): Result<DashboardFetchedFile> = withContext(Dispatchers.IO) {
|
||||
if (serverPath.isBlank()) {
|
||||
return@withContext Result.failure(IOException("Media path is empty"))
|
||||
}
|
||||
if (maxBytes <= 0L) {
|
||||
return@withContext Result.failure(IOException("Media download limit is invalid"))
|
||||
}
|
||||
val httpUrl = resolveUrl("/api/files/download")
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("path", serverPath)
|
||||
?.build()
|
||||
?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder().url(httpUrl).get().build()
|
||||
|
||||
executeCancellable(request, "Dashboard media download") { response ->
|
||||
val body = response.body
|
||||
val declaredLength = body.contentLength().takeIf { it >= 0L }
|
||||
if (declaredLength != null && declaredLength > maxBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
val initialSize = declaredLength
|
||||
?.coerceAtMost(Int.MAX_VALUE.toLong())
|
||||
?.toInt()
|
||||
?: DEFAULT_BUFFER_SIZE
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
body.byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var readTotal = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
readTotal += count
|
||||
if (readTotal > maxBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
if (declaredLength != null && readTotal != declaredLength) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
}
|
||||
DashboardFetchedFile(
|
||||
bytes = output.toByteArray(),
|
||||
contentType = response.header("Content-Type")
|
||||
?.substringBefore(';')
|
||||
?.trim()
|
||||
?.takeIf(String::isNotEmpty)
|
||||
?: "application/octet-stream",
|
||||
fileName = response.header("Content-Disposition")
|
||||
?.let(::contentDispositionFileName)
|
||||
?: serverPath.substringAfterLast('/').substringAfterLast('\\')
|
||||
.takeIf(String::isNotBlank),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun postJsonObject(
|
||||
path: String,
|
||||
payload: JsonObject = JsonObject(emptyMap()),
|
||||
@@ -2405,6 +2488,23 @@ private fun Response.readJsonElement(json: Json): JsonElement {
|
||||
return json.parseToJsonElement(raw)
|
||||
}
|
||||
|
||||
private fun contentDispositionFileName(header: String): String? {
|
||||
val encoded = Regex("""filename\*=UTF-8''([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.let { runCatching { java.net.URLDecoder.decode(it, "UTF-8") }.getOrNull() }
|
||||
val plain = Regex("""filename=\"([^\"]+)\"|filename=([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.let { it.groupValues[1].ifBlank { it.groupValues[2] } }
|
||||
?.trim()
|
||||
?.trim('"')
|
||||
return (encoded ?: plain)
|
||||
?.substringAfterLast('/')
|
||||
?.substringAfterLast('\\')
|
||||
?.takeIf(String::isNotBlank)
|
||||
}
|
||||
|
||||
internal class DashboardHttpException(
|
||||
val statusCode: Int,
|
||||
message: String,
|
||||
@@ -2436,14 +2536,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
|
||||
@@ -2451,6 +2548,33 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/** True only when the managed-file route itself is absent on this Hermes build. */
|
||||
internal fun Throwable.isDashboardManagedFilesUnsupported(): Boolean {
|
||||
var current: Throwable? = this
|
||||
val seen = java.util.Collections.newSetFromMap(
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
if (current is DashboardHttpException) {
|
||||
if (current.statusCode in setOf(405, 501)) return true
|
||||
if (current.statusCode == 404) {
|
||||
val detail = current.message.orEmpty()
|
||||
// FastAPI's missing-route response is the generic "Not Found".
|
||||
// A real managed-file miss says "File not found" and must not
|
||||
// silently escape to Relay's broader path policy.
|
||||
val isManagedFileMiss = detail.contains("File not found", ignoreCase = true) ||
|
||||
detail.contains("Path not found", ignoreCase = true)
|
||||
val isGenericRouteMiss = detail.trim().endsWith(": not found", ignoreCase = true) ||
|
||||
detail.contains("\"detail\":\"Not Found\"", ignoreCase = true) ||
|
||||
detail.contains("\"detail\": \"Not Found\"", ignoreCase = true)
|
||||
if (!isManagedFileMiss && isGenericRouteMiss) return true
|
||||
}
|
||||
}
|
||||
current = current.cause
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val bodyDetail = runCatching { response.body.string() }.getOrDefault("")
|
||||
val detail = bodyDetail.take(240).ifBlank { response.message }
|
||||
|
||||
+173
-17
@@ -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)
|
||||
@@ -384,6 +399,14 @@ class GatewayChatClient(
|
||||
private val _serverProject = MutableStateFlow<GatewaySessionProject?>(null)
|
||||
val serverProject: StateFlow<GatewaySessionProject?> = _serverProject.asStateFlow()
|
||||
|
||||
/**
|
||||
* Exact model-callable tool names from upstream `session.info.tools` for
|
||||
* the selected live session/profile. Null means the gateway has not
|
||||
* supplied a catalog; an empty set means it authoritatively supplied none.
|
||||
*/
|
||||
private val _serverTools = MutableStateFlow<Set<String>?>(null)
|
||||
val serverTools: StateFlow<Set<String>?> = _serverTools.asStateFlow()
|
||||
|
||||
/** Serializes connect / session-establish so concurrent sends share one socket. */
|
||||
private val connectMutex = Mutex()
|
||||
|
||||
@@ -548,6 +571,28 @@ class GatewayChatClient(
|
||||
val terminalRequired: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* One exact turn settled from authoritative session state may still receive
|
||||
* the terminal frame that was already in flight. Consume only that terminal
|
||||
* so it cannot be reported as a second unmatched completion. A subsequent
|
||||
* message.start clears the drain because it establishes the next turn on
|
||||
* the same live runtime.
|
||||
*/
|
||||
@Volatile
|
||||
private var settledTurnDrain: SettledTurnDrain? = null
|
||||
|
||||
private data class SettledTurnDrain(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
)
|
||||
|
||||
private data class ActiveTurnLivenessProbe(
|
||||
val turn: GatewayTurn,
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val progressGeneration: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates UI callbacks when the server starts a turn that has no matching
|
||||
* [sendTurn] call (for example a background-process completion). The
|
||||
@@ -677,6 +722,7 @@ class GatewayChatClient(
|
||||
): ActiveTurnHandle {
|
||||
val turn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
androidOwned = true,
|
||||
onTransportAccepted = onTransportAccepted,
|
||||
)
|
||||
// Warm = the connection-establish phases are skipped this turn (socket
|
||||
@@ -724,6 +770,10 @@ class GatewayChatClient(
|
||||
cleanupStagedAttachments(stagedImagePaths)
|
||||
return@launch
|
||||
}
|
||||
// A newly accepted Android send is a distinct generation on
|
||||
// this runtime. Its terminal must never be consumed by the
|
||||
// prior turn's optional late-terminal drain.
|
||||
settledTurnDrain = null
|
||||
activeTurn = turn
|
||||
turn.armWatchdog()
|
||||
// Generic `file.attach` uploads are staged artifacts, not
|
||||
@@ -758,7 +808,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) {
|
||||
@@ -850,6 +900,7 @@ class GatewayChatClient(
|
||||
storedSessionId = null
|
||||
liveSessionProfile = null
|
||||
cancelledTurnDrain = null
|
||||
_serverTools.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1363,6 +1414,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1486,6 +1538,7 @@ class GatewayChatClient(
|
||||
boundTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1519,6 +1572,7 @@ class GatewayChatClient(
|
||||
val queuedTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
// recoverTurn is resumed on its caller's coroutine context;
|
||||
// ChatViewModel calls it from Main, so this admission runs
|
||||
@@ -1765,18 +1819,17 @@ class GatewayChatClient(
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider-neutral account limits owned by upstream Hermes. Current hosts
|
||||
* may not expose this additive method yet; callers should treat JSON-RPC
|
||||
* method-not-found as capability absence and use the optional Relay
|
||||
* compatibility surface when paired.
|
||||
* Official upstream Nous usage bars. Current hosts may not expose this
|
||||
* additive method yet; callers should treat JSON-RPC method-not-found as
|
||||
* capability absence and use the optional Relay enhancement when paired.
|
||||
*/
|
||||
suspend fun providerUsage(): Result<JsonObject> {
|
||||
suspend fun usageBars(): Result<JsonObject> {
|
||||
try {
|
||||
connectMutex.withLock { ensureConnected() }
|
||||
} catch (e: Exception) {
|
||||
return Result.failure(e)
|
||||
}
|
||||
return rpc("account.usage", JsonObject(emptyMap()))
|
||||
return rpc("usage.bars", JsonObject(emptyMap()))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2414,6 +2467,7 @@ class GatewayChatClient(
|
||||
} catch (error: Exception) {
|
||||
return GatewayActiveSessionsResult.TransientFailure(error)
|
||||
}
|
||||
val livenessProbe = captureActiveTurnLivenessProbe()
|
||||
val result = rpc(
|
||||
"session.active_list",
|
||||
buildJsonObject {
|
||||
@@ -2433,12 +2487,58 @@ class GatewayChatClient(
|
||||
val payload = result.getOrThrow()
|
||||
val rows = payload["sessions"] as? JsonArray
|
||||
?: throw GatewayRpcException("session.active_list returned no sessions array")
|
||||
GatewayActiveSessionsResult.Success(rows.map(::parseGatewayActiveSession))
|
||||
val sessions = rows.map(::parseGatewayActiveSession)
|
||||
reconcileActiveTurnFromSnapshot(livenessProbe, sessions)
|
||||
GatewayActiveSessionsResult.Success(sessions)
|
||||
} catch (parseError: Exception) {
|
||||
GatewayActiveSessionsResult.TransientFailure(parseError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture only a locally submitted/recovered turn. Merely observing an
|
||||
* exact session through the shared Gateway socket never grants Android
|
||||
* authority to settle Desktop/TUI work.
|
||||
*/
|
||||
private fun captureActiveTurnLivenessProbe(): ActiveTurnLivenessProbe? {
|
||||
val turn = activeTurn ?: return null
|
||||
val generation = turn.captureLivenessGeneration() ?: return null
|
||||
val storedId = storedSessionId ?: return null
|
||||
val liveId = liveSessionId ?: return null
|
||||
return ActiveTurnLivenessProbe(turn, storedId, liveId, generation)
|
||||
}
|
||||
|
||||
/**
|
||||
* `session.active_list` is process-wide, but a row naming both identifiers
|
||||
* already owned by this client is authoritative for that exact runtime.
|
||||
* Fence the delayed snapshot by turn identity and progress generation so an
|
||||
* old idle result cannot settle a newer turn or race newer live events.
|
||||
*/
|
||||
private fun reconcileActiveTurnFromSnapshot(
|
||||
probe: ActiveTurnLivenessProbe?,
|
||||
sessions: List<GatewayActiveSession>,
|
||||
) {
|
||||
probe ?: return
|
||||
if (activeTurn !== probe.turn ||
|
||||
storedSessionId != probe.storedSessionId ||
|
||||
liveSessionId != probe.liveSessionId
|
||||
) return
|
||||
val exact = sessions.singleOrNull { row ->
|
||||
row.runtimeSessionId == probe.liveSessionId &&
|
||||
row.storedSessionId == probe.storedSessionId
|
||||
} ?: return
|
||||
if (exact.status != GatewayActiveSessionStatus.Idle) return
|
||||
if (probe.turn.settleFromAuthoritativeSessionState(
|
||||
running = false,
|
||||
source = "session.active_list",
|
||||
expectedProgressGeneration = probe.progressGeneration,
|
||||
)
|
||||
) {
|
||||
if (activeTurn === probe.turn) activeTurn = null
|
||||
if (!AppForegroundTracker.isForeground.value) scheduleBackgroundClose()
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop one process owned by the current live gateway session. */
|
||||
suspend fun killProcess(processId: String): Result<Unit> {
|
||||
if (processId.isBlank()) {
|
||||
@@ -2831,6 +2931,7 @@ class GatewayChatClient(
|
||||
activeTurn = null
|
||||
backgroundTurns.clear()
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
unsolicitedTurnProvider = null
|
||||
coldPrewarmSessionReadyListener = null
|
||||
unmatchedTurnCompleteListener = null
|
||||
@@ -3134,6 +3235,18 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (info.containsKey("tools")) {
|
||||
val groups = info["tools"] as? JsonObject
|
||||
_serverTools.value = groups
|
||||
?.values
|
||||
?.asSequence()
|
||||
?.mapNotNull { it as? JsonArray }
|
||||
?.flatMap { it.asSequence() }
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
|
||||
?.filter { it.isNotBlank() }
|
||||
?.toSet()
|
||||
?: emptySet()
|
||||
}
|
||||
// Context usage: require used > 0 — a COLD resume resets counters and
|
||||
// reports 0 until the first turn rebuilds the prompt; painting 0 would
|
||||
// mislead on a session that actually has history.
|
||||
@@ -3149,6 +3262,7 @@ class GatewayChatClient(
|
||||
/** Apply a session create/resume result without leaking metadata from the prior session. */
|
||||
private fun applySessionResultInfo(result: JsonObject) {
|
||||
_serverProject.value = null
|
||||
_serverTools.value = null
|
||||
(result["info"] as? JsonObject)?.let { applySessionInfo(it) }
|
||||
}
|
||||
|
||||
@@ -3267,6 +3381,7 @@ class GatewayChatClient(
|
||||
val requestedProfile = currentSessionProfile()
|
||||
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
}
|
||||
if (
|
||||
liveSessionId != null &&
|
||||
@@ -3336,6 +3451,7 @@ class GatewayChatClient(
|
||||
storedSessionId = stored
|
||||
liveSessionProfile = requestedProfile
|
||||
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
||||
if (settledTurnDrain?.storedSessionId != stored) settledTurnDrain = null
|
||||
turn.callbacks.onSessionId(stored)
|
||||
}
|
||||
|
||||
@@ -3713,6 +3829,7 @@ class GatewayChatClient(
|
||||
}
|
||||
dispatchProcessEvent(type, payload, eventSessionId)
|
||||
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
||||
if (consumeSettledTurnTerminal(type, eventSessionId)) return
|
||||
var turn = activeTurn
|
||||
if (turn == null && type == "message.start") {
|
||||
// Unsolicited turns are accepted only with an explicit exact live-
|
||||
@@ -4226,10 +4343,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
|
||||
}
|
||||
|
||||
@@ -4237,6 +4356,7 @@ class GatewayChatClient(
|
||||
val callbacks: GatewayTurnCallbacks,
|
||||
dedupeAdjacentMessageStarts: Boolean = false,
|
||||
deferEvents: Boolean = false,
|
||||
private val androidOwned: Boolean = false,
|
||||
private val onTransportAccepted: () -> Unit = { },
|
||||
) : ActiveTurnHandle {
|
||||
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
||||
@@ -4263,6 +4383,7 @@ class GatewayChatClient(
|
||||
|
||||
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
private val transportAccepted = AtomicBoolean(false)
|
||||
private val progressGeneration = java.util.concurrent.atomic.AtomicLong(0L)
|
||||
|
||||
fun markTransportAccepted() {
|
||||
if (transportAccepted.compareAndSet(false, true)) {
|
||||
@@ -4339,6 +4460,7 @@ class GatewayChatClient(
|
||||
if (settledWithoutTerminalFrame) return
|
||||
if (type != "session.info") {
|
||||
started = true
|
||||
progressGeneration.incrementAndGet()
|
||||
markTransportAccepted()
|
||||
}
|
||||
tracer.mark("ttfe")
|
||||
@@ -4348,7 +4470,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.
|
||||
@@ -4368,10 +4490,20 @@ class GatewayChatClient(
|
||||
* exact turn has proved it went live. A pre-start `running=false`
|
||||
* heartbeat can race `prompt.submit` and is not a completion boundary.
|
||||
*/
|
||||
fun settleFromAuthoritativeSessionState(running: Boolean?, source: String): Boolean {
|
||||
fun captureLivenessGeneration(): Long? =
|
||||
if (androidOwned && started && !ended) progressGeneration.get() else null
|
||||
|
||||
fun settleFromAuthoritativeSessionState(
|
||||
running: Boolean?,
|
||||
source: String,
|
||||
expectedProgressGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (running != false || !started) return false
|
||||
val settled = synchronized(deferredEventLock) {
|
||||
if (ended) {
|
||||
if (ended ||
|
||||
(expectedProgressGeneration != null &&
|
||||
progressGeneration.get() != expectedProgressGeneration)
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
settledWithoutTerminalFrame = true
|
||||
@@ -4382,6 +4514,7 @@ class GatewayChatClient(
|
||||
if (!settled) return false
|
||||
|
||||
disarmWatchdog()
|
||||
armSettledTurnDrain()
|
||||
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
||||
callbacks.onReconcileRequired()
|
||||
callbacks.onComplete()
|
||||
@@ -4402,6 +4535,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4529,6 +4663,26 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
|
||||
private fun armSettledTurnDrain() {
|
||||
val storedId = storedSessionId ?: return
|
||||
val liveId = liveSessionId ?: return
|
||||
settledTurnDrain = SettledTurnDrain(storedId, liveId)
|
||||
}
|
||||
|
||||
/** Consume one late terminal from a turn already settled by session state. */
|
||||
private fun consumeSettledTurnTerminal(type: String, eventSessionId: String?): Boolean {
|
||||
val drain = settledTurnDrain ?: return false
|
||||
if (eventSessionId != drain.liveSessionId) return false
|
||||
if (type == "message.start") {
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
return false
|
||||
}
|
||||
if (type != "message.complete" && type != "error") return false
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
Log.d(TAG, "Ignored late terminal for gateway turn settled from session state")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun updateCancelledDrainLiveSession(storedId: String, liveId: String) {
|
||||
val drain = cancelledTurnDrain ?: return
|
||||
if (drain.storedSessionId == storedId) {
|
||||
@@ -4655,6 +4809,8 @@ class GatewayChatClient(
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
||||
},
|
||||
onStatusClear = { kind -> dispatchIfCurrent(stillCurrent) { callbacks.onStatusClear(kind) } },
|
||||
onNoticeShow = { notice -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeShow(notice) } },
|
||||
onNoticeClear = { key -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeClear(key) } },
|
||||
)
|
||||
|
||||
private fun dispatchIfCurrent(stillCurrent: () -> Boolean, callback: () -> Unit) {
|
||||
@@ -4707,7 +4863,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. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
|
||||
/**
|
||||
@@ -397,8 +398,26 @@ class GatewayEventMapper(
|
||||
}
|
||||
}
|
||||
|
||||
// Known-but-unrendered (notification.show, …) and unknown types
|
||||
// alike: ignore.
|
||||
"notification.show" -> {
|
||||
val text = payload.string("text")?.trim().orEmpty()
|
||||
if (text.isNotEmpty()) {
|
||||
callbacks.onNoticeShow(
|
||||
GatewayAgentNotice(
|
||||
text = text,
|
||||
level = payload.string("level"),
|
||||
kind = payload.string("kind"),
|
||||
ttlMs = payload.long("ttl_ms"),
|
||||
key = payload.string("key"),
|
||||
id = payload.string("id"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"notification.clear" ->
|
||||
payload.string("key")?.trim()?.takeIf(String::isNotEmpty)?.let(callbacks.onNoticeClear)
|
||||
|
||||
// Unknown event types remain forward-compatible no-ops.
|
||||
else -> Unit
|
||||
}
|
||||
previousEventType = type
|
||||
@@ -596,6 +615,9 @@ private fun JsonObject?.string(key: String): String? =
|
||||
private fun JsonObject?.int(key: String): Int? =
|
||||
(this?.get(key) as? JsonPrimitive)?.intOrNull
|
||||
|
||||
private fun JsonObject?.long(key: String): Long? =
|
||||
(this?.get(key) as? JsonPrimitive)?.longOrNull
|
||||
|
||||
private fun JsonObject?.double(key: String): Double? =
|
||||
(this?.get(key) as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,6 +256,16 @@ data class GatewayToolOutputRisk(
|
||||
val redacted: Boolean,
|
||||
)
|
||||
|
||||
/** Official upstream `notification.show` AgentNotice payload. */
|
||||
data class GatewayAgentNotice(
|
||||
val text: String,
|
||||
val level: String? = null,
|
||||
val kind: String? = null,
|
||||
val ttlMs: Long? = null,
|
||||
val key: String? = null,
|
||||
val id: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One `subagent.*` lifecycle event, emitted on the PARENT session. Lifecycle
|
||||
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
||||
@@ -734,6 +737,10 @@ class GatewayTurnCallbacks(
|
||||
val onStatusUpdate: (kind: String?, text: String) -> Unit = { _, _ -> },
|
||||
/** Clear a transient status only when [kind] still owns the visible status slot. */
|
||||
val onStatusClear: (kind: String) -> Unit = { _ -> },
|
||||
/** Official upstream account/agent notice; distinct from Relay proactive messages. */
|
||||
val onNoticeShow: (GatewayAgentNotice) -> Unit = { _ -> },
|
||||
/** Exact-key dismissal for an upstream notice. */
|
||||
val onNoticeClear: (key: String) -> Unit = { _ -> },
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
+132
-21
@@ -3,10 +3,12 @@ package com.hermesandroid.relay.network.usage
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
|
||||
/** Relay-enhanced usage with an upstream fallback for hosts without Relay support. */
|
||||
/** Upstream usage enriched by the optional Relay provider/pool surface. */
|
||||
class ProviderUsageRepository(
|
||||
private val gatewayClientProvider: () -> GatewayChatClient?,
|
||||
private val dashboardClientProvider: () -> DashboardApiClient? = { null },
|
||||
@@ -14,33 +16,142 @@ class ProviderUsageRepository(
|
||||
private val profileProvider: () -> String? = { null },
|
||||
private val sessionProvider: () -> String? = { null },
|
||||
) {
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
coerceInputValues = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
suspend fun fetch(): Result<ProviderUsageResponse?> {
|
||||
val profile = profileProvider()
|
||||
val session = sessionProvider()
|
||||
val upstream: Result<ProviderUsageResponse?> = gatewayClientProvider()
|
||||
?.usageBars()
|
||||
?.mapCatching(::providerUsageFromUpstreamBars)
|
||||
?: Result.success(null)
|
||||
|
||||
val dashboard = dashboardClientProvider()
|
||||
var enhancement: Result<ProviderUsageResponse?>? = null
|
||||
if (dashboard != null) {
|
||||
val enhanced = dashboard.getProviderUsage(profile, session)
|
||||
if (enhanced.isSuccess && enhanced.getOrNull() != null) return enhanced
|
||||
enhancement = dashboard.getProviderUsage(profile, session)
|
||||
}
|
||||
|
||||
val relay = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
if (enhancement?.getOrNull() == null) {
|
||||
enhancement = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
)
|
||||
}
|
||||
|
||||
val merged = mergeProviderUsage(
|
||||
upstream = upstream.getOrNull(),
|
||||
enhancement = enhancement?.getOrNull(),
|
||||
)
|
||||
if (relay.isSuccess && relay.getOrNull() != null) return relay
|
||||
if (merged != null) return Result.success(merged)
|
||||
|
||||
val gateway = gatewayClientProvider()
|
||||
if (gateway != null) {
|
||||
val upstream = gateway.providerUsage()
|
||||
.mapCatching { json.decodeFromJsonElement<ProviderUsageResponse>(it) }
|
||||
if (upstream.isSuccess) return upstream
|
||||
return when {
|
||||
upstream.isFailure && enhancement?.isFailure == true ->
|
||||
Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
enhancement?.isFailure == true -> Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
else -> Result.success(null)
|
||||
}
|
||||
return relay
|
||||
}
|
||||
}
|
||||
|
||||
internal fun providerUsageFromUpstreamBars(root: JsonObject): ProviderUsageResponse? {
|
||||
if (root.boolean("available") != true) return null
|
||||
|
||||
val renewsAt = root.string("renews_at")
|
||||
val windows = listOfNotNull(
|
||||
root.usageWindow("plan", "Plan", renewsAt),
|
||||
root.usageWindow("topup", "Top-up", null),
|
||||
)
|
||||
val details = listOfNotNull(
|
||||
root.string("subscription_remaining_display")?.let { "Subscription remaining: $it" },
|
||||
root.string("topup_remaining_display")?.let { "Top-up remaining: $it" },
|
||||
root.string("total_spendable_display")?.let { "Total spendable: $it" },
|
||||
)
|
||||
|
||||
return ProviderUsageResponse(
|
||||
providers = listOf(
|
||||
ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "upstream:usage.bars",
|
||||
plan = root.string("plan_name"),
|
||||
windows = windows,
|
||||
details = details,
|
||||
renewsAt = renewsAt,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun mergeProviderUsage(
|
||||
upstream: ProviderUsageResponse?,
|
||||
enhancement: ProviderUsageResponse?,
|
||||
): ProviderUsageResponse? {
|
||||
if (upstream == null) return enhancement
|
||||
if (enhancement == null) return upstream
|
||||
|
||||
val providers = linkedMapOf<String, ProviderUsageProvider>()
|
||||
upstream.providers.forEach { providers[it.id] = it }
|
||||
enhancement.providers.forEach { enhanced ->
|
||||
val standard = providers[enhanced.id]
|
||||
providers[enhanced.id] = when {
|
||||
standard == null -> enhanced
|
||||
standard.available -> standard.copy(
|
||||
// Official usage.bars stays authoritative for every field it
|
||||
// supplies. Relay enriches the row with pool/balance metadata
|
||||
// and fills only gaps that upstream left absent.
|
||||
fetchedAt = standard.fetchedAt ?: enhanced.fetchedAt,
|
||||
plan = standard.plan ?: enhanced.plan,
|
||||
windows = standard.windows.ifEmpty { enhanced.windows },
|
||||
details = (standard.details + enhanced.details).distinct(),
|
||||
balances = enhanced.balances,
|
||||
renewsAt = standard.renewsAt ?: enhanced.renewsAt,
|
||||
actionUrl = standard.actionUrl ?: enhanced.actionUrl,
|
||||
credentials = enhanced.credentials,
|
||||
activeCredentialId = enhanced.activeCredentialId,
|
||||
activeCredentialState = enhanced.activeCredentialState,
|
||||
activeObservedAt = enhanced.activeObservedAt,
|
||||
message = standard.message ?: enhanced.message,
|
||||
)
|
||||
enhanced.available -> enhanced
|
||||
else -> enhanced
|
||||
}
|
||||
}
|
||||
return ProviderUsageResponse(
|
||||
schemaVersion = maxOf(upstream.schemaVersion, enhancement.schemaVersion),
|
||||
fetchedAt = enhancement.fetchedAt ?: upstream.fetchedAt,
|
||||
capabilities = upstream.capabilities + enhancement.capabilities,
|
||||
providers = providers.values.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.usageWindow(
|
||||
id: String,
|
||||
label: String,
|
||||
resetAt: String?,
|
||||
): ProviderUsageWindow? {
|
||||
val bar = this["${id}_bar"] as? JsonObject ?: return null
|
||||
val remaining = bar.string("remaining_display")
|
||||
val total = bar.string("total_display")
|
||||
val detail = when {
|
||||
remaining != null && total != null -> "$remaining remaining of $total"
|
||||
remaining != null -> "$remaining remaining"
|
||||
total != null -> "$total total"
|
||||
else -> null
|
||||
}
|
||||
return ProviderUsageWindow(
|
||||
id = id,
|
||||
label = label,
|
||||
usedPercent = bar.double("pct_used"),
|
||||
resetAt = resetAt,
|
||||
detail = detail,
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.string(key: String): String? =
|
||||
(this[key] as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty)
|
||||
|
||||
private fun JsonObject.boolean(key: String): Boolean? =
|
||||
(this[key] as? JsonPrimitive)?.booleanOrNull
|
||||
|
||||
private fun JsonObject.double(key: String): Double? =
|
||||
(this[key] as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.hermesandroid.relay.data.EnhancedVoiceOverrides
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||
import com.hermesandroid.relay.data.VoiceProfileScope
|
||||
import com.hermesandroid.relay.data.VoiceSettings
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||
@@ -170,6 +171,9 @@ internal class HermesRuntimeBinder(
|
||||
relayHttpClient = connection.relayHttpClient,
|
||||
mediaSettingsRepo = connection.mediaSettingsRepo,
|
||||
mediaCacheWriter = connection.mediaCacheWriter,
|
||||
dashboardMediaClientProvider = {
|
||||
connection.activeDashboardUrl()?.let(connection::dashboardClientForActive)
|
||||
},
|
||||
)
|
||||
chat.setSelectedProfileProvider { connection.selectedProfile.value }
|
||||
chat.setIsolatedProfileApiProvider { connection.selectedProfileUsesIsolatedApiRoute() }
|
||||
@@ -209,6 +213,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 +266,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,
|
||||
@@ -281,6 +291,36 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.connectionsHydrated,
|
||||
connection.activeConnectionId,
|
||||
connection.relayConfigured,
|
||||
voiceSettingsHydrated,
|
||||
voicePreferencesRepository.activeScope,
|
||||
) { connectionsReady, connectionId, relayConfigured, settingsReady, scope ->
|
||||
VoiceRelayReconciliationInputs(
|
||||
connectionsReady = connectionsReady,
|
||||
connectionId = connectionId,
|
||||
relayConfigured = relayConfigured,
|
||||
settingsReady = settingsReady,
|
||||
scope = scope,
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
if (
|
||||
inputs.connectionsReady &&
|
||||
inputs.settingsReady &&
|
||||
inputs.connectionId != null &&
|
||||
!inputs.relayConfigured &&
|
||||
// Default-profile storage is a legacy global layer shared
|
||||
// across connections. Keep its fallback runtime-only.
|
||||
inputs.scope.profileName != null &&
|
||||
inputs.scope.connectionId == inputs.connectionId
|
||||
) {
|
||||
voicePreferencesRepository.reconcileRelayRemoval(inputs.scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.streamingEndpoint,
|
||||
@@ -397,13 +437,22 @@ internal class HermesRuntimeBinder(
|
||||
connection.chatReady,
|
||||
connection.standardVoiceAvailability,
|
||||
connection.relayVoiceReady,
|
||||
connection.profileSelectionSettled,
|
||||
) { settings, chatReady, standard, relayReady, profileSettled ->
|
||||
connection.relayConfigured,
|
||||
) { settings, chatReady, standard, relayReady, relayConfigured ->
|
||||
VoiceReadinessInputs(
|
||||
settings = settings,
|
||||
chatReady = chatReady,
|
||||
standardAvailability = standard,
|
||||
relayReady = relayReady,
|
||||
relayConfigured = relayConfigured,
|
||||
)
|
||||
}.combine(connection.profileSelectionSettled) { inputs, profileSettled ->
|
||||
resolveVoiceActivationReadiness(
|
||||
settings,
|
||||
chatReady,
|
||||
standard,
|
||||
relayReady,
|
||||
inputs.settings,
|
||||
inputs.chatReady,
|
||||
inputs.standardAvailability,
|
||||
inputs.relayReady,
|
||||
inputs.relayConfigured,
|
||||
profileSettled,
|
||||
)
|
||||
}
|
||||
@@ -557,6 +606,22 @@ internal class HermesRuntimeBinder(
|
||||
val hiddenSources: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
private data class VoiceRelayReconciliationInputs(
|
||||
val connectionsReady: Boolean,
|
||||
val connectionId: String?,
|
||||
val relayConfigured: Boolean,
|
||||
val settingsReady: Boolean,
|
||||
val scope: VoiceProfileScope,
|
||||
)
|
||||
|
||||
private data class VoiceReadinessInputs(
|
||||
val settings: VoiceSettings,
|
||||
val chatReady: Boolean,
|
||||
val standardAvailability: StandardVoiceAvailability,
|
||||
val relayReady: Boolean,
|
||||
val relayConfigured: Boolean,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val PROFILE_SETTLE_BACKSTOP_MS = 2_500L
|
||||
const val PROFILE_CONTEXT_COALESCE_MS = 160L
|
||||
@@ -595,12 +660,14 @@ internal fun resolveVoiceActivationReadiness(
|
||||
chatReady: Boolean,
|
||||
standardAvailability: StandardVoiceAvailability,
|
||||
relayReady: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
profileSettled: Boolean,
|
||||
): HermesVoiceActivationReadiness {
|
||||
if (!profileSettled) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Loading the selected Hermes profile")
|
||||
}
|
||||
return when (VoiceEngineMode.fromStorage(settings.engineMode)) {
|
||||
val effectiveSettings = voiceSettingsForRelayConfiguration(settings, relayConfigured)
|
||||
return when (VoiceEngineMode.fromStorage(effectiveSettings.engineMode)) {
|
||||
VoiceEngineMode.RealtimeAgent -> {
|
||||
if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Realtime)
|
||||
@@ -612,7 +679,7 @@ internal fun resolveVoiceActivationReadiness(
|
||||
if (!chatReady) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Waiting for Hermes chat")
|
||||
}
|
||||
when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
when (VoiceAudioRoute.fromStorage(effectiveSettings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(
|
||||
HermesVoiceActivationRoute.RelayAudio
|
||||
@@ -636,6 +703,24 @@ internal fun resolveVoiceActivationReadiness(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relay absence is a topology decision, unlike a transient route outage. Only
|
||||
* the former may fall back from Relay-only persisted selections.
|
||||
*/
|
||||
internal fun voiceSettingsForRelayConfiguration(
|
||||
settings: VoiceSettings,
|
||||
relayConfigured: Boolean,
|
||||
): VoiceSettings {
|
||||
if (relayConfigured) return settings
|
||||
return settings.copy(
|
||||
engineMode = VoiceEngineMode.HermesVoiceOutput.storageValue,
|
||||
audioRoute = when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> VoiceAudioRoute.Auto.storageValue
|
||||
else -> settings.audioRoute
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun standardVoiceReadiness(
|
||||
availability: StandardVoiceAvailability,
|
||||
): HermesVoiceActivationReadiness = when (availability) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Width policy shared by Chat's content and persistent status surfaces. */
|
||||
internal data class ChatResponsiveLayout(
|
||||
val introMaxWidth: Dp?,
|
||||
val avatarSize: Dp?,
|
||||
val chromeMaxWidth: Dp?,
|
||||
val transcriptMaxWidth: Dp?,
|
||||
val focusVoiceMaxWidth: Dp?,
|
||||
)
|
||||
|
||||
internal fun chatResponsiveLayout(screenWidthDp: Int): ChatResponsiveLayout = when {
|
||||
screenWidthDp >= 840 -> ChatResponsiveLayout(
|
||||
introMaxWidth = 720.dp,
|
||||
avatarSize = 360.dp,
|
||||
chromeMaxWidth = 960.dp,
|
||||
transcriptMaxWidth = 960.dp,
|
||||
focusVoiceMaxWidth = 1120.dp,
|
||||
)
|
||||
screenWidthDp >= 600 -> ChatResponsiveLayout(
|
||||
introMaxWidth = 600.dp,
|
||||
avatarSize = 300.dp,
|
||||
chromeMaxWidth = 760.dp,
|
||||
transcriptMaxWidth = 760.dp,
|
||||
focusVoiceMaxWidth = 760.dp,
|
||||
)
|
||||
else -> ChatResponsiveLayout(
|
||||
introMaxWidth = null,
|
||||
avatarSize = null,
|
||||
chromeMaxWidth = null,
|
||||
transcriptMaxWidth = null,
|
||||
focusVoiceMaxWidth = null,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun useSplitVoiceLayout(screenWidthDp: Int, screenHeightDp: Int): Boolean =
|
||||
screenWidthDp >= 840 && screenWidthDp > screenHeightDp
|
||||
@@ -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/
|
||||
@@ -983,6 +1015,17 @@ fun RelayApp() {
|
||||
chatSessions.firstOrNull { it.sessionId == currentChatSessionId }
|
||||
}
|
||||
|
||||
LaunchedEffect(
|
||||
gitOwnerKey,
|
||||
activeChatSession?.gitRepoRoot,
|
||||
activeChatSession?.workingDirectory,
|
||||
) {
|
||||
gitStateViewModel.setSessionWorkspace(
|
||||
repoRoot = activeChatSession?.gitRepoRoot,
|
||||
workingDirectory = activeChatSession?.workingDirectory,
|
||||
)
|
||||
}
|
||||
|
||||
// Bind Git to the active coding session when upstream supplies its exact
|
||||
// workspace metadata. CWD fallback only matches a path-segment descendant;
|
||||
// an ambiguous multi-repo catalog stays unselected until the user chooses.
|
||||
@@ -999,7 +1042,7 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
|
||||
val gitWorkspaceAvailable = gitRepoScanningEnabled &&
|
||||
val gitWorkspaceAvailable =
|
||||
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
||||
val gitWorkspaceSummary = remember(
|
||||
gitReposState,
|
||||
@@ -1351,6 +1394,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 +1612,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 +1639,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 +2147,9 @@ fun RelayApp() {
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||
streamingEndpoint,
|
||||
),
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
@@ -2113,10 +2164,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 = {
|
||||
@@ -2139,6 +2200,9 @@ fun RelayApp() {
|
||||
// Routine in-progress reconnect surfaces here (amber cue)
|
||||
// instead of a take-space banner or a floating toast.
|
||||
reconnecting = connectionReconnecting,
|
||||
maxContentWidth = chatResponsiveLayout(
|
||||
LocalConfiguration.current.screenWidthDp,
|
||||
).chromeMaxWidth,
|
||||
modifier = Modifier.petPerchSurface(
|
||||
key = APP_STATUS_PET_WALK_REGION,
|
||||
routes = APP_STATUS_PET_ROUTES,
|
||||
@@ -2930,7 +2994,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 +3030,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 +3277,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 +3448,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 +3476,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 +3515,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
|
||||
|
||||
@@ -8,17 +8,38 @@ import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** Visual tone of a transient banner message. Errors are NOT modelled here —
|
||||
* they stay on the snackbar (see [LocalSnackbarHost]); this bus is info-only. */
|
||||
enum class UiMessageSeverity { Info, Success, Status }
|
||||
/** Visual tone of a transient banner message. */
|
||||
enum class UiMessageSeverity { Info, Success, Status, Warning }
|
||||
|
||||
data class UiMessage(
|
||||
val id: Long,
|
||||
val text: String,
|
||||
val severity: UiMessageSeverity,
|
||||
val ttlMillis: Long,
|
||||
/** Stable upstream key for replace-in-place and exact dismissal. */
|
||||
val key: String? = null,
|
||||
)
|
||||
|
||||
sealed interface UiMessageEvent {
|
||||
data class Show(val message: UiMessage) : UiMessageEvent
|
||||
data class Clear(val key: String) : UiMessageEvent
|
||||
}
|
||||
|
||||
internal fun reduceUiMessages(
|
||||
current: List<UiMessage>,
|
||||
event: UiMessageEvent,
|
||||
maxRetained: Int,
|
||||
): List<UiMessage> = when (event) {
|
||||
is UiMessageEvent.Clear -> current.filterNot { it.key == event.key }
|
||||
is UiMessageEvent.Show -> {
|
||||
val incoming = event.message
|
||||
val withoutDuplicate = current.filterNot { existing ->
|
||||
if (incoming.key != null) existing.key == incoming.key else existing.text == incoming.text
|
||||
}
|
||||
(withoutDuplicate + incoming).takeLast(maxRetained)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* App-wide bus for transient, non-error status/confirmation messages that
|
||||
* surface in the top [com.hermesandroid.relay.ui.components.MessageBannerHost]
|
||||
@@ -26,8 +47,10 @@ data class UiMessage(
|
||||
* shows the newest line collapsed, expands to a few recent lines, auto-dismisses
|
||||
* and coalesces duplicates.
|
||||
*
|
||||
* Deliberately info-only: errors and persistent/actionable messages keep going
|
||||
* to the snackbar so they demand acknowledgement. Migrate frequent
|
||||
* App-owned errors and persistent/actionable messages keep going to the
|
||||
* snackbar so they demand acknowledgement. Upstream keyed AgentNotices may use
|
||||
* the warning tone here because their own sticky/clear lifecycle owns them.
|
||||
* Migrate frequent
|
||||
* `snackbarHostState.showSnackbar("…")` confirmations/status to [info] /
|
||||
* [success] / [status] here.
|
||||
*
|
||||
@@ -39,8 +62,8 @@ object UiMessageBus {
|
||||
const val STATUS_TTL_MS = 6_000L
|
||||
|
||||
private val counter = AtomicLong(0L)
|
||||
private val _events = MutableSharedFlow<UiMessage>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessage> = _events.asSharedFlow()
|
||||
private val _events = MutableSharedFlow<UiMessageEvent>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessageEvent> = _events.asSharedFlow()
|
||||
|
||||
// Number of messages currently shown by the host. Lifted here so the app
|
||||
// scaffold can fold banner visibility into its status-bar inset accounting
|
||||
@@ -52,10 +75,26 @@ object UiMessageBus {
|
||||
text: String,
|
||||
severity: UiMessageSeverity = UiMessageSeverity.Info,
|
||||
ttlMillis: Long = DEFAULT_TTL_MS,
|
||||
key: String? = null,
|
||||
) {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return
|
||||
_events.tryEmit(UiMessage(counter.incrementAndGet(), trimmed, severity, ttlMillis))
|
||||
_events.tryEmit(
|
||||
UiMessageEvent.Show(
|
||||
UiMessage(
|
||||
id = counter.incrementAndGet(),
|
||||
text = trimmed,
|
||||
severity = severity,
|
||||
ttlMillis = ttlMillis.coerceAtLeast(0L),
|
||||
key = key?.trim()?.takeIf(String::isNotEmpty),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Dismiss only the keyed message owned by the matching upstream notice. */
|
||||
fun clear(key: String) {
|
||||
key.trim().takeIf(String::isNotEmpty)?.let { _events.tryEmit(UiMessageEvent.Clear(it)) }
|
||||
}
|
||||
|
||||
/** Neutral confirmation/info (e.g. "Pairing code copied"). */
|
||||
|
||||
+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."
|
||||
}
|
||||
|
||||
@@ -741,6 +741,7 @@ fun AgentInfoSheet(
|
||||
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||
val standardVoiceReady by connectionViewModel.standardVoiceReady.collectAsState()
|
||||
val proactiveEnabled by connectionViewModel.proactiveEnabled.collectAsState()
|
||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||
val allConnections by connectionViewModel.connectionStore.connections.collectAsState()
|
||||
@@ -842,6 +843,7 @@ fun AgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready || standardVoiceReady,
|
||||
relayConnected = relayConnectionState == ConnectionState.Connected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
@@ -3423,6 +3425,8 @@ private fun LegacyAgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready ||
|
||||
connectionViewModel.standardVoiceReady.collectAsState().value,
|
||||
relayConnected = relayConnected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -206,29 +206,49 @@ private fun FailedCard(
|
||||
modifier: Modifier,
|
||||
maxWidth: Dp
|
||||
) {
|
||||
val hostOnly = attachment.errorMessage == ChatViewModel.MEDIA_HOST_ONLY
|
||||
Surface(
|
||||
shape = appearanceRoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
color = if (hostOnly) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = modifier
|
||||
.widthIn(max = maxWidth)
|
||||
.clickable { onRetry() }
|
||||
.then(if (hostOnly) Modifier else Modifier.clickable { onRetry() })
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Text(text = "\u26A0\uFE0F", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = if (hostOnly) "\uD83D\uDCCE" else "\u26A0\uFE0F",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only)
|
||||
} else {
|
||||
attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer
|
||||
},
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.inbound_attach_tap_retry),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only_help)
|
||||
} else {
|
||||
stringResource(R.string.inbound_attach_tap_retry)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -53,7 +54,9 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.UiMessage
|
||||
import com.hermesandroid.relay.ui.UiMessageBus
|
||||
import com.hermesandroid.relay.ui.UiMessageEvent
|
||||
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||
import com.hermesandroid.relay.ui.reduceUiMessages
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val MAX_RETAINED = 6
|
||||
@@ -68,7 +71,8 @@ private const val ROW_MIN_HEIGHT_DP = 34
|
||||
* overlay. Auto-dismisses (paused while expanded) and coalesces duplicates so a
|
||||
* burst of the same status collapses to one refreshed row.
|
||||
*
|
||||
* Errors stay on the snackbar — only post info/success/status here.
|
||||
* App-owned errors stay on the snackbar. Keyed upstream AgentNotices may also
|
||||
* use the warning tone because their sticky/clear lifecycle is server-owned.
|
||||
*/
|
||||
@Composable
|
||||
fun MessageBannerHost(
|
||||
@@ -82,18 +86,19 @@ fun MessageBannerHost(
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
UiMessageBus.events.collect { msg ->
|
||||
// Coalesce identical text so e.g. repeated "Reconnecting…" collapses
|
||||
// to a single, freshly-timed row rather than stacking.
|
||||
shown.filter { it.text == msg.text }.forEach { dup ->
|
||||
shown.remove(dup)
|
||||
expiresAt.remove(dup.id)
|
||||
}
|
||||
shown.add(msg)
|
||||
expiresAt[msg.id] = nowMs() + msg.ttlMillis
|
||||
while (shown.size > MAX_RETAINED) {
|
||||
val dropped = shown.removeAt(0)
|
||||
expiresAt.remove(dropped.id)
|
||||
UiMessageBus.events.collect { event ->
|
||||
val next = reduceUiMessages(shown, event, MAX_RETAINED)
|
||||
val retainedIds = next.mapTo(mutableSetOf()) { it.id }
|
||||
expiresAt.keys.filterNot(retainedIds::contains).forEach { expiresAt.remove(it) }
|
||||
shown.clear()
|
||||
shown.addAll(next)
|
||||
if (event is UiMessageEvent.Show) {
|
||||
val msg = event.message
|
||||
expiresAt[msg.id] = if (msg.ttlMillis == 0L) {
|
||||
Long.MAX_VALUE
|
||||
} else {
|
||||
nowMs() + msg.ttlMillis
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,6 +109,7 @@ fun MessageBannerHost(
|
||||
while (shown.isNotEmpty()) {
|
||||
val now = nowMs()
|
||||
val soonest = shown.minOfOrNull { expiresAt[it.id] ?: Long.MAX_VALUE } ?: break
|
||||
if (soonest == Long.MAX_VALUE) break
|
||||
if (soonest <= now) {
|
||||
shown.filter { (expiresAt[it.id] ?: Long.MAX_VALUE) <= now }.forEach { expired ->
|
||||
shown.remove(expired)
|
||||
@@ -281,6 +287,7 @@ private fun MessageRow(
|
||||
private fun severityContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.58f)
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.74f)
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f)
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.90f)
|
||||
}
|
||||
|
||||
@@ -288,12 +295,14 @@ private fun severityContainer(severity: UiMessageSeverity): Color = when (severi
|
||||
private fun severityOnContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.onTertiaryContainer
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.onErrorContainer
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
|
||||
private fun severityIcon(severity: UiMessageSeverity): ImageVector = when (severity) {
|
||||
UiMessageSeverity.Success -> Icons.Filled.CheckCircle
|
||||
UiMessageSeverity.Status -> Icons.Filled.Sync
|
||||
UiMessageSeverity.Warning -> Icons.Filled.Warning
|
||||
UiMessageSeverity.Info -> Icons.Filled.Info
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -4,6 +4,7 @@ import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
@@ -15,6 +16,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawing
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Text
|
||||
@@ -24,7 +26,10 @@ import androidx.compose.ui.Modifier
|
||||
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.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,74 +46,81 @@ 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.
|
||||
*/
|
||||
reconnecting: Boolean = false,
|
||||
maxContentWidth: Dp? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(
|
||||
WindowInsets.safeDrawing.only(
|
||||
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom,
|
||||
),
|
||||
)
|
||||
.padding(start = 14.dp, end = 14.dp, top = 3.dp, bottom = 4.dp)
|
||||
.clip(appearanceRoundedCornerShape(16.dp))
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.relayPanel(
|
||||
shape = appearanceRoundedCornerShape(16.dp),
|
||||
background = RelayRefresh.Navy2.copy(alpha = 0.88f),
|
||||
borderColor = RelayRefresh.Line,
|
||||
),
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
Column(
|
||||
modifier = modifier
|
||||
.then(maxContentWidth?.let { Modifier.widthIn(max = it) } ?: Modifier)
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 22.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
.windowInsetsPadding(
|
||||
WindowInsets.safeDrawing.only(
|
||||
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom,
|
||||
),
|
||||
)
|
||||
.padding(start = 14.dp, end = 14.dp, top = 3.dp, bottom = 4.dp)
|
||||
.clip(appearanceRoundedCornerShape(16.dp))
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.relayPanel(
|
||||
shape = appearanceRoundedCornerShape(16.dp),
|
||||
background = RelayRefresh.Navy2.copy(alpha = 0.88f),
|
||||
borderColor = RelayRefresh.Line,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 22.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
leadingBadge()
|
||||
if (securityGlyph != null) {
|
||||
securityGlyph()
|
||||
}
|
||||
// Route is in flux mid-reconnect, so the amber cue replaces the
|
||||
// route label rather than stacking beside it in the 22dp strip.
|
||||
when {
|
||||
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
||||
routeLabel.isNotBlank() -> Text(
|
||||
text = "· $routeLabel",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
leadingBadge()
|
||||
if (securityGlyph != null) {
|
||||
securityGlyph()
|
||||
}
|
||||
// Route is in flux mid-reconnect, so the amber cue replaces the
|
||||
// route label rather than stacking beside it in the 22dp strip.
|
||||
when {
|
||||
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
||||
routeLabel.isNotBlank() -> Text(
|
||||
text = "· $routeLabel",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = trailing,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = trailing,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +144,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,
|
||||
|
||||
@@ -141,8 +141,8 @@ internal data class SessionCapability(
|
||||
* live. SSE paths only get post-hoc reasoning, so this is gateway-only.
|
||||
* While the gateway is still being probed (Unknown) we surface it as a
|
||||
* "checking" reason rather than a confirmed chip.
|
||||
* - Media / Terminal → require the relay to be CONNECTED (the relay brokers
|
||||
* those channels). A configured-but-disconnected relay is not enough.
|
||||
* - Media → current upstream Dashboard managed-file delivery OR connected
|
||||
* Relay compatibility transport. Terminal remains Relay-owned.
|
||||
* - Voice → `voiceReady` (standard dashboard voice OR relay voice — whichever
|
||||
* the connection actually has).
|
||||
*/
|
||||
@@ -150,6 +150,7 @@ internal data class SessionCapability(
|
||||
internal fun sessionCapabilities(
|
||||
transport: SessionPathTransport,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
upstreamMediaAvailable: Boolean,
|
||||
relayConnected: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
voiceReady: Boolean,
|
||||
@@ -170,11 +171,11 @@ internal fun sessionCapabilities(
|
||||
),
|
||||
SessionCapability(
|
||||
type = "media",
|
||||
available = relayConnected,
|
||||
available = upstreamMediaAvailable || relayConnected,
|
||||
reason = when {
|
||||
relayConnected -> null
|
||||
upstreamMediaAvailable || relayConnected -> null
|
||||
relayConfigured -> stringResource(R.string.session_path_relay_not_connected)
|
||||
else -> stringResource(R.string.session_path_pair_relay_media)
|
||||
else -> stringResource(R.string.session_path_media_not_ready)
|
||||
},
|
||||
),
|
||||
SessionCapability(
|
||||
@@ -401,7 +402,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(
|
||||
|
||||
@@ -23,14 +23,18 @@ 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.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
@@ -71,6 +75,7 @@ import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -81,6 +86,7 @@ import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
@@ -92,7 +98,9 @@ import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAgentAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalBackgroundVisualizationEnabled
|
||||
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
||||
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||
import com.hermesandroid.relay.ui.showHumanError
|
||||
import com.hermesandroid.relay.ui.useSplitVoiceLayout
|
||||
import com.hermesandroid.relay.util.HumanError
|
||||
import kotlinx.coroutines.delay
|
||||
import com.hermesandroid.relay.viewmodel.BackgroundRunPhase
|
||||
@@ -112,6 +120,8 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
|
||||
internal const val VOICE_MODE_MIC_TEST_TAG = "voiceModeMic"
|
||||
internal const val VOICE_FOCUS_SPLIT_LAYOUT_TEST_TAG = "voiceFocusSplitLayout"
|
||||
internal const val VOICE_FOCUS_STACKED_LAYOUT_TEST_TAG = "voiceFocusStackedLayout"
|
||||
|
||||
/**
|
||||
* Full-screen voice-mode overlay. Renders the MorphingSphere in its voiceMode
|
||||
@@ -186,6 +196,56 @@ fun VoiceModeOverlay(
|
||||
val backgroundVisualizationEnabled = LocalBackgroundVisualizationEnabled.current
|
||||
val surface = MaterialTheme.colorScheme.surface
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val configuration = LocalConfiguration.current
|
||||
val responsiveLayout = chatResponsiveLayout(configuration.screenWidthDp)
|
||||
val splitFocusLayout = useSplitVoiceLayout(
|
||||
screenWidthDp = configuration.screenWidthDp,
|
||||
screenHeightDp = configuration.screenHeightDp,
|
||||
)
|
||||
|
||||
val focusMicTap: () -> Unit = {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onStopListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
}
|
||||
val focusMicHoldPress: () -> Unit = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onInterruptAndStart = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onInterrupt()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
}
|
||||
val focusMicHoldRelease: () -> Unit = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
}
|
||||
|
||||
var controlsExpanded by remember { mutableStateOf(false) }
|
||||
val focusMode = presentationMode == VoicePresentationMode.Focus
|
||||
@@ -253,6 +313,11 @@ fun VoiceModeOverlay(
|
||||
onOpenSettings = onOpenSettings,
|
||||
onExit = onDismiss,
|
||||
modifier = Modifier
|
||||
.then(
|
||||
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.statusBarsPadding()
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
||||
@@ -328,162 +393,93 @@ fun VoiceModeOverlay(
|
||||
exit = fadeOut(tween(120)),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.0f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (backgroundVisualizationEnabled) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = voiceStateToSphereState(uiState.state),
|
||||
voiceAmplitude = uiState.amplitude,
|
||||
voiceMode = true,
|
||||
),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
if (splitFocusLayout) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.widthIn(max = responsiveLayout.focusVoiceMaxWidth ?: 1120.dp)
|
||||
.fillMaxSize()
|
||||
.navigationBarsPadding()
|
||||
.padding(top = 92.dp, bottom = 28.dp, start = 32.dp, end = 32.dp)
|
||||
.testTag(VOICE_FOCUS_SPLIT_LAYOUT_TEST_TAG),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
VoiceFocusIdentityPane(
|
||||
uiState = uiState,
|
||||
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||
onMicTap = focusMicTap,
|
||||
onMicHoldPress = focusMicHoldPress,
|
||||
onMicHoldRelease = focusMicHoldRelease,
|
||||
showMic = true,
|
||||
modifier = Modifier
|
||||
.weight(0.86f)
|
||||
.fillMaxHeight(),
|
||||
)
|
||||
Spacer(Modifier.width(32.dp))
|
||||
VoiceFocusStatusAndTranscriptPane(
|
||||
uiState = uiState,
|
||||
transcriptMessages = visibleTranscriptMessages,
|
||||
pendingTranscriptText = pendingTranscriptText,
|
||||
transcriptListState = transcriptListState,
|
||||
showThinking = showThinking,
|
||||
onBackgroundRunCancel = onBackgroundRunCancel,
|
||||
onBackgroundRunTap = onBackgroundRunTap,
|
||||
onPermissionDeniedChipTap = onPermissionDeniedChipTap,
|
||||
onHermesConfirmationAnswer = onHermesConfirmationAnswer,
|
||||
onPresentationModeChange = onPresentationModeChange,
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
horizontalContentPadding = 0.dp,
|
||||
modifier = Modifier
|
||||
.weight(1.14f)
|
||||
.fillMaxHeight(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
VoiceWaveform(
|
||||
amplitude = uiState.amplitude,
|
||||
state = uiState.state,
|
||||
outputAudioActive = uiState.outputAudioActive,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 32.dp, vertical = 8.dp),
|
||||
)
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = uiState.handoffStatus != null,
|
||||
enter = fadeIn(tween(140)),
|
||||
exit = fadeOut(tween(180)),
|
||||
) {
|
||||
VoiceHandoffStrip(
|
||||
status = uiState.handoffStatus,
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
BackgroundRunChip(
|
||||
run = uiState.backgroundRun,
|
||||
onCancel = onBackgroundRunCancel,
|
||||
onTap = onBackgroundRunTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
DestructiveCountdownRow(
|
||||
countdown = uiState.destructiveCountdown,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp),
|
||||
)
|
||||
|
||||
PermissionDeniedChip(
|
||||
callout = uiState.permissionDeniedCallout,
|
||||
onTap = onPermissionDeniedChipTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
HermesConfirmationCard(
|
||||
confirmation = uiState.hermesConfirmation,
|
||||
onAnswer = onHermesConfirmationAnswer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.25f, fill = true),
|
||||
) {
|
||||
val hasTranscript = visibleTranscriptMessages.isNotEmpty() ||
|
||||
pendingTranscriptText != null
|
||||
if (hasTranscript) {
|
||||
val latestId = visibleTranscriptMessages.lastOrNull()?.id
|
||||
LazyColumn(
|
||||
state = transcriptListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// Match ChatScreen's identity contract. A history
|
||||
// reconcile can adopt the same authoritative server
|
||||
// id into a live row while Compose still holds the
|
||||
// pre-reconcile row for a frame. uiKey remains stable
|
||||
// and unique across that transition.
|
||||
items(visibleTranscriptMessages, key = ::voiceTranscriptItemKey) { msg ->
|
||||
CompactTranscriptRow(
|
||||
message = msg,
|
||||
showThinking = showThinking,
|
||||
expanded = msg.id == latestId || msg.isStreaming,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
if (pendingTranscriptText != null) {
|
||||
item(key = "aux:pending-voice-transcript") {
|
||||
CompactTranscriptRow(
|
||||
message = ChatMessage(
|
||||
id = "pending-voice-transcript",
|
||||
role = MessageRole.USER,
|
||||
content = pendingTranscriptText,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
isStreaming = true,
|
||||
),
|
||||
showThinking = showThinking,
|
||||
expanded = true,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
}
|
||||
item { Spacer(Modifier.height(12.dp)) }
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = stateHint(uiState.state),
|
||||
transitionSpec = {
|
||||
fadeIn(tween(200)) togetherWith fadeOut(tween(200))
|
||||
},
|
||||
label = "stateHint",
|
||||
) { hint ->
|
||||
Text(
|
||||
text = hint,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
.then(
|
||||
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxSize()
|
||||
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp)
|
||||
.testTag(VOICE_FOCUS_STACKED_LAYOUT_TEST_TAG),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
VoiceFocusIdentityPane(
|
||||
uiState = uiState,
|
||||
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||
onMicTap = focusMicTap,
|
||||
onMicHoldPress = focusMicHoldPress,
|
||||
onMicHoldRelease = focusMicHoldRelease,
|
||||
showMic = false,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
)
|
||||
VoiceFocusStatusAndTranscriptPane(
|
||||
uiState = uiState,
|
||||
transcriptMessages = visibleTranscriptMessages,
|
||||
pendingTranscriptText = pendingTranscriptText,
|
||||
transcriptListState = transcriptListState,
|
||||
showThinking = showThinking,
|
||||
onBackgroundRunCancel = onBackgroundRunCancel,
|
||||
onBackgroundRunTap = onBackgroundRunTap,
|
||||
onPermissionDeniedChipTap = onPermissionDeniedChipTap,
|
||||
onHermesConfirmationAnswer = onHermesConfirmationAnswer,
|
||||
onPresentationModeChange = onPresentationModeChange,
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
horizontalContentPadding = 24.dp,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.25f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -498,6 +494,12 @@ fun VoiceModeOverlay(
|
||||
exit = fadeOut(tween(180)),
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 176.dp, start = 24.dp, end = 24.dp),
|
||||
) {
|
||||
BackgroundRunChip(
|
||||
@@ -515,6 +517,12 @@ fun VoiceModeOverlay(
|
||||
exit = fadeOut(),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopCenter)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(top = 64.dp, start = 16.dp, end = 16.dp),
|
||||
) {
|
||||
Surface(
|
||||
@@ -570,57 +578,205 @@ fun VoiceModeOverlay(
|
||||
// that visually said "Stop" but was actually wired to "Start."
|
||||
VoiceMicButton(
|
||||
uiState = uiState,
|
||||
onTap = {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onStopListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
},
|
||||
onHoldPress = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onInterruptAndStart = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onInterrupt()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
},
|
||||
onHoldRelease = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onTap = focusMicTap,
|
||||
onHoldPress = focusMicHoldPress,
|
||||
onHoldRelease = focusMicHoldRelease,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = 48.dp),
|
||||
visible = focusMode,
|
||||
visible = focusMode && !splitFocusLayout,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceFocusIdentityPane(
|
||||
uiState: VoiceUiState,
|
||||
backgroundVisualizationEnabled: Boolean,
|
||||
onMicTap: () -> Unit,
|
||||
onMicHoldPress: () -> Unit,
|
||||
onMicHoldRelease: () -> Unit,
|
||||
showMic: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.testTag("voiceFocusIdentityPane"),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (backgroundVisualizationEnabled) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = voiceStateToSphereState(uiState.state),
|
||||
voiceAmplitude = uiState.amplitude,
|
||||
voiceMode = true,
|
||||
),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
VoiceWaveform(
|
||||
amplitude = uiState.amplitude,
|
||||
state = uiState.state,
|
||||
outputAudioActive = uiState.outputAudioActive,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 8.dp),
|
||||
)
|
||||
if (showMic) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
VoiceMicButton(
|
||||
uiState = uiState,
|
||||
onTap = onMicTap,
|
||||
onHoldPress = onMicHoldPress,
|
||||
onHoldRelease = onMicHoldRelease,
|
||||
visible = true,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceFocusStatusAndTranscriptPane(
|
||||
uiState: VoiceUiState,
|
||||
transcriptMessages: List<ChatMessage>,
|
||||
pendingTranscriptText: String?,
|
||||
transcriptListState: LazyListState,
|
||||
showThinking: Boolean,
|
||||
onBackgroundRunCancel: () -> Unit,
|
||||
onBackgroundRunTap: () -> Unit,
|
||||
onPermissionDeniedChipTap: (PermissionDeniedCallout) -> Unit,
|
||||
onHermesConfirmationAnswer: (String) -> Unit,
|
||||
onPresentationModeChange: (VoicePresentationMode) -> Unit,
|
||||
onCardAction: (messageId: String, cardKey: String, action: HermesCardAction) -> Unit,
|
||||
onCardInput: (messageId: String, cardKey: String, value: String) -> Unit,
|
||||
horizontalContentPadding: Dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(modifier = modifier.testTag("voiceFocusTranscriptPane")) {
|
||||
AnimatedVisibility(
|
||||
visible = uiState.handoffStatus != null,
|
||||
enter = fadeIn(tween(140)),
|
||||
exit = fadeOut(tween(180)),
|
||||
) {
|
||||
VoiceHandoffStrip(
|
||||
status = uiState.handoffStatus,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
BackgroundRunChip(
|
||||
run = uiState.backgroundRun,
|
||||
onCancel = onBackgroundRunCancel,
|
||||
onTap = onBackgroundRunTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
DestructiveCountdownRow(
|
||||
countdown = uiState.destructiveCountdown,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding),
|
||||
)
|
||||
PermissionDeniedChip(
|
||||
callout = uiState.permissionDeniedCallout,
|
||||
onTap = onPermissionDeniedChipTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
HermesConfirmationCard(
|
||||
confirmation = uiState.hermesConfirmation,
|
||||
onAnswer = onHermesConfirmationAnswer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f, fill = true),
|
||||
) {
|
||||
val hasTranscript = transcriptMessages.isNotEmpty() || pendingTranscriptText != null
|
||||
if (hasTranscript) {
|
||||
val latestId = transcriptMessages.lastOrNull()?.id
|
||||
LazyColumn(
|
||||
state = transcriptListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// uiKey remains stable while Gateway reconciliation adopts
|
||||
// an authoritative server id into a live transcript row.
|
||||
items(transcriptMessages, key = ::voiceTranscriptItemKey) { msg ->
|
||||
CompactTranscriptRow(
|
||||
message = msg,
|
||||
showThinking = showThinking,
|
||||
expanded = msg.id == latestId || msg.isStreaming,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
if (pendingTranscriptText != null) {
|
||||
item(key = "aux:pending-voice-transcript") {
|
||||
CompactTranscriptRow(
|
||||
message = ChatMessage(
|
||||
id = "pending-voice-transcript",
|
||||
role = MessageRole.USER,
|
||||
content = pendingTranscriptText,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
isStreaming = true,
|
||||
),
|
||||
showThinking = showThinking,
|
||||
expanded = true,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
}
|
||||
item { Spacer(Modifier.height(12.dp)) }
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = stateHint(uiState.state),
|
||||
transitionSpec = {
|
||||
fadeIn(tween(200)) togetherWith fadeOut(tween(200))
|
||||
},
|
||||
label = "stateHint",
|
||||
) { hint ->
|
||||
Text(
|
||||
text = hint,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceMicButton(
|
||||
uiState: VoiceUiState,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -98,6 +98,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
@@ -119,6 +120,7 @@ import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||
import com.hermesandroid.relay.ui.theme.radialNavyBackground
|
||||
import com.hermesandroid.relay.network.upstream.ApiModelOption
|
||||
import com.hermesandroid.relay.network.upstream.ChatMode
|
||||
@@ -265,6 +267,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
|
||||
@@ -748,6 +751,7 @@ fun ChatScreen(
|
||||
gitWorkspaceAvailable: Boolean = gitWorkspaceSummary != null,
|
||||
onNavigateToGitWorkspace: () -> Unit = {},
|
||||
) {
|
||||
val responsiveLayout = chatResponsiveLayout(LocalConfiguration.current.screenWidthDp)
|
||||
val supervised = supervisedPolicy.enabled
|
||||
val supervisedVisibility = supervisedPolicy.visibility.resolved()
|
||||
LaunchedEffect(supervisedPolicy) {
|
||||
@@ -1228,7 +1232,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)
|
||||
@@ -3310,7 +3314,13 @@ fun ChatScreen(
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(horizontal = 32.dp)
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 32.dp)
|
||||
.then(
|
||||
responsiveLayout.introMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
),
|
||||
) {
|
||||
Spacer(modifier = Modifier.weight(0.15f))
|
||||
|
||||
@@ -3319,12 +3329,15 @@ fun ChatScreen(
|
||||
LocalBackgroundVisualizationEnabled.current &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.weight(0.7f, fill = false)
|
||||
) {
|
||||
val avatarModifier = responsiveLayout.avatarSize?.let { size ->
|
||||
Modifier
|
||||
.size(size)
|
||||
.clipToBounds()
|
||||
} ?: Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.weight(0.7f, fill = false)
|
||||
Box(modifier = avatarModifier) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = if (error != null) SphereState.Error else SphereState.Idle,
|
||||
@@ -3567,7 +3580,14 @@ fun ChatScreen(
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.align(Alignment.Center)
|
||||
.fillMaxHeight()
|
||||
.then(
|
||||
responsiveLayout.transcriptMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.padding(top = if (showTranscriptSearch) 112.dp else 0.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp)
|
||||
@@ -4649,6 +4669,13 @@ fun ChatScreen(
|
||||
supervisedPolicy.capabilities.attachmentCategories
|
||||
)) pasteImageFromClipboard else ({ }),
|
||||
onLongPressAttach = { if (!supervised) showCommandPalette = true },
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
),
|
||||
charLimit = charLimit,
|
||||
caption = turnStatus ?: inputCaption,
|
||||
voiceReady = voiceReady,
|
||||
|
||||
@@ -706,8 +706,9 @@ fun ChatSettingsScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// Live preview of the exact text that will be sent.
|
||||
// Rebuilds on every toggle change via remember(key1..key5).
|
||||
// Representative preview of each enabled block.
|
||||
// The chat context audit remains the exact selected-
|
||||
// session preview. Rebuilds on every toggle change.
|
||||
val previewText = remember(
|
||||
appContextEnabled,
|
||||
appContextBridgeState,
|
||||
@@ -735,6 +736,14 @@ fun ChatSettingsScreen(
|
||||
destructiveVerbCount = 5,
|
||||
autoDisableMinutes = 15,
|
||||
),
|
||||
// This card is an explanatory fixture, not
|
||||
// the active session audit. Supply one
|
||||
// representative Relay tool so the bridge
|
||||
// and safety toggles remain visible; the
|
||||
// real send path uses the selected
|
||||
// session/profile's authoritative catalog.
|
||||
availableTools =
|
||||
com.hermesandroid.relay.util.PHONE_CONTEXT_PREVIEW_TOOLS,
|
||||
)
|
||||
}
|
||||
Card(
|
||||
@@ -778,7 +787,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(
|
||||
|
||||
@@ -544,19 +544,24 @@ internal fun buildStatusChecks(
|
||||
)
|
||||
}
|
||||
|
||||
// A healthy standard-only connection should not read like three missing
|
||||
// dependencies. Collapse the absent optional extension to one neutral row;
|
||||
// configured Relay keeps the detailed auth/server/plugin troubleshooting.
|
||||
if (!relayConfigured) {
|
||||
checks += StatusCheck(
|
||||
context.getString(R.string.diag_relay_tools_optional),
|
||||
CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.diag_relay_tools_not_paired),
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
}
|
||||
// 6) Optional Relay / pairing auth.
|
||||
val authLabel = context.getString(R.string.diag_check_pairing_auth)
|
||||
val authRelayActive = context.getString(R.string.diag_check_relay_active)
|
||||
val authPairingProg = context.getString(R.string.diag_check_pairing_progress)
|
||||
val authNotPaired = context.getString(R.string.diag_check_not_paired)
|
||||
val authErr = recentError(DiagnosticCategory.Auth)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.active_section_optional),
|
||||
category = DiagnosticCategory.Auth,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
authState is AuthState.Paired ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Pass,
|
||||
@@ -586,18 +591,11 @@ internal fun buildStatusChecks(
|
||||
|
||||
// 7) Relay server (optional — Unknown when not paired/configured).
|
||||
val relayLabel = context.getString(R.string.active_section_optional_relay)
|
||||
val relayNotConfigured = context.getString(R.string.diag_check_relay_not_configured)
|
||||
val relayConnected = context.getString(R.string.diag_check_connected)
|
||||
val relayReachableNotReady = context.getString(R.string.diag_check_reachable_not_ready)
|
||||
val relayConfiguredNotReachable = context.getString(R.string.diag_check_configured_not_reachable)
|
||||
val relayErr = recentError(DiagnosticCategory.Relay)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Unknown,
|
||||
reason = relayNotConfigured,
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
relayReady ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Pass,
|
||||
@@ -629,7 +627,7 @@ internal fun buildStatusChecks(
|
||||
relayReady = relayReady,
|
||||
relayUpdateInfo = relayUpdateInfo,
|
||||
)
|
||||
checks += when (pluginState) {
|
||||
if (relayConfigured) checks += when (pluginState) {
|
||||
RelayPluginDiagnosticState.NotConfigured ->
|
||||
StatusCheck(
|
||||
pluginLabel, CheckStatus.Unknown,
|
||||
|
||||
@@ -98,7 +98,7 @@ private data class DisplayFile(
|
||||
val deletions: Int?,
|
||||
)
|
||||
|
||||
/** First-class native Git workspace backed by the optional Relay contribution. */
|
||||
/** Native Git workspace: upstream current-session reads plus optional Relay enhancements. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GitStateScreen(
|
||||
@@ -131,7 +131,7 @@ fun GitStateScreen(
|
||||
var pendingConfirm by remember { mutableStateOf<ConfirmationRequest?>(null) }
|
||||
|
||||
LaunchedEffect(scanningEnabled) {
|
||||
if (scanningEnabled) viewModel.loadRepos()
|
||||
viewModel.loadRepos()
|
||||
}
|
||||
|
||||
val repos = (reposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
@@ -202,29 +202,27 @@ fun GitStateScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (scanningEnabled) {
|
||||
IconButton(onClick = { selectedRepo?.let { viewModel.selectRepo(it.id) } ?: viewModel.loadRepos() }) {
|
||||
Icon(Icons.Filled.Refresh, "Refresh Git workspace")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showOverflow = true }) { Icon(Icons.Filled.MoreVert, "More Git actions") }
|
||||
DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {
|
||||
DropdownMenuItem(text = { Text("Choose repository") }, onClick = { showOverflow = false; showRepos = true })
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.git_state_branches)) }, enabled = detail != null, onClick = { showOverflow = false; showBranches = true })
|
||||
}
|
||||
IconButton(onClick = { selectedRepo?.let { viewModel.selectRepo(it.id) } ?: viewModel.loadRepos() }) {
|
||||
Icon(Icons.Filled.Refresh, "Refresh Git workspace")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showOverflow = true }) { Icon(Icons.Filled.MoreVert, "More Git actions") }
|
||||
DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {
|
||||
DropdownMenuItem(text = { Text("Choose repository") }, onClick = { showOverflow = false; showRepos = true })
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.git_state_branches)) }, enabled = detail != null, onClick = { showOverflow = false; showBranches = true })
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (scanningEnabled && detail != null) {
|
||||
if (detail != null) {
|
||||
Surface(shadowElevation = 8.dp, tonalElevation = 2.dp) {
|
||||
Column {
|
||||
if (selection.isNotEmpty()) {
|
||||
SelectionRail(
|
||||
count = selection.size,
|
||||
canWrite = hasGrant,
|
||||
canWrite = hasGrant && scanningEnabled,
|
||||
allStaged = selection.all { it.filter == FileFilter.Staged },
|
||||
onStage = stageSelection,
|
||||
onDiscard = discardSelection,
|
||||
@@ -234,7 +232,7 @@ fun GitStateScreen(
|
||||
OutlinedButton(onClick = { showBranches = true }, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AccountTree, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_branches))
|
||||
}
|
||||
Button(onClick = { showCommit = true }, enabled = hasGrant && detail.status.counts.staged > 0, modifier = Modifier.weight(1f)) {
|
||||
Button(onClick = { showCommit = true }, enabled = scanningEnabled && hasGrant && detail.status.counts.staged > 0, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_commit))
|
||||
}
|
||||
}
|
||||
@@ -248,21 +246,21 @@ fun GitStateScreen(
|
||||
enabled = scanningEnabled,
|
||||
onEnabledChange = onScanningEnabledChange,
|
||||
)
|
||||
if (scanningEnabled) {
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No Git repositories found", "Add a repository to the host's configured Git roots, then refresh.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No current-session Git repository", "Open a Hermes coding session with repository context, or enable host repository discovery above.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
modifier = Modifier.weight(1f),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
relayEnhancementsEnabled = scanningEnabled,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
@@ -289,8 +287,7 @@ fun GitStateScreen(
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,7 +308,7 @@ fun GitStateScreen(
|
||||
onCreate = { name, track -> showBranches = false; viewModel.checkout("", newBranch = name, track = track) },
|
||||
)
|
||||
}
|
||||
if (showCommit && detail != null) {
|
||||
if (showCommit && scanningEnabled && detail != null) {
|
||||
val stagedPaths = detail.status.staged.map { it.path }
|
||||
CommitDialog(
|
||||
hasStaged = stagedPaths.isNotEmpty(),
|
||||
@@ -392,6 +389,7 @@ private fun WorkspaceBody(
|
||||
detailState: GitRepoDetailState,
|
||||
mutation: GitMutationState,
|
||||
stashNotice: String?,
|
||||
relayEnhancementsEnabled: Boolean,
|
||||
hasGrant: Boolean,
|
||||
filter: FileFilter,
|
||||
onFilter: (FileFilter) -> Unit,
|
||||
@@ -421,9 +419,11 @@ private fun WorkspaceBody(
|
||||
LazyColumn(modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 18.dp)) {
|
||||
item {
|
||||
SummaryRail(repo, detailState)
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
if (relayEnhancementsEnabled) {
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
}
|
||||
reposNotice?.let { NoticeCard(it) }
|
||||
if (!hasGrant) WriteGrantNotice()
|
||||
if (relayEnhancementsEnabled && !hasGrant) WriteGrantNotice()
|
||||
MutationBanner(mutation, onClearMutation)
|
||||
stashNotice?.let { NoticeCard(it) }
|
||||
if (status.truncated) NoticeCard(stringResource(R.string.git_state_truncated), error = true)
|
||||
@@ -438,6 +438,7 @@ private fun WorkspaceBody(
|
||||
FileRow(
|
||||
file = file,
|
||||
selected = file in selection,
|
||||
selectionEnabled = relayEnhancementsEnabled,
|
||||
expanded = expandedPath == file.path,
|
||||
mode = contentMode,
|
||||
contentState = contentState,
|
||||
@@ -554,6 +555,7 @@ private fun GitStatus.uniqueChangeCount(): Int = counts.changes.takeIf { it >= 0
|
||||
private fun FileRow(
|
||||
file: DisplayFile,
|
||||
selected: Boolean,
|
||||
selectionEnabled: Boolean,
|
||||
expanded: Boolean,
|
||||
mode: ContentMode,
|
||||
contentState: GitContentViewState,
|
||||
@@ -572,7 +574,7 @@ private fun FileRow(
|
||||
) {
|
||||
Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelected() },
|
||||
onCheckedChange = if (selectionEnabled) ({ _ -> onToggleSelected() }) else null,
|
||||
modifier = Modifier.semantics {
|
||||
contentDescription = "Select ${file.path}"
|
||||
},
|
||||
@@ -602,7 +604,9 @@ private fun FileRow(
|
||||
if (expanded && file.filter != FileFilter.Untracked) {
|
||||
Row(Modifier.padding(start = 56.dp, end = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (file.filter != FileFilter.Untracked) FilterChip(mode == ContentMode.Diff, { onOpen(ContentMode.Diff) }, label = { Text("Diff") })
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
if (selectionEnabled) {
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
}
|
||||
}
|
||||
InlineContent(contentState, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp))
|
||||
}
|
||||
|
||||
@@ -355,7 +355,7 @@ fun SettingsScreen(
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
// The Power tools below all ride the relay plugin. Rather than stamp an
|
||||
// The Relay tools below all ride the optional plugin. Rather than stamp an
|
||||
// identical badge on every card (noise, not signal), the dependency is
|
||||
// surfaced ONCE on the section header as a single plugin-state badge.
|
||||
val pluginBadge = when (relayUiState) {
|
||||
@@ -629,6 +629,14 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc),
|
||||
onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.GraphicEq,
|
||||
title = stringResource(R.string.settings_voice_mode),
|
||||
@@ -637,6 +645,8 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.AutoMirrored.Filled.Message,
|
||||
title = stringResource(R.string.settings_threads),
|
||||
@@ -645,8 +655,6 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Code,
|
||||
title = stringResource(R.string.settings_terminal),
|
||||
@@ -681,13 +689,6 @@ fun SettingsScreen(
|
||||
)
|
||||
// === END PHASE3-notif-listener-followup ===
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc), onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
if (BuildFlavor.isSideload) {
|
||||
// === PHASE3-safety-rails: bridge safety entry-point ===
|
||||
SettingsCategoryRow(
|
||||
|
||||
+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,
|
||||
|
||||
@@ -957,25 +957,6 @@ private fun VoiceForThisProfileCard(
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// Auto-repair when Relay disappears out from under a Relay-only selection:
|
||||
// a persisted RealtimeAgent engine (Relay-only) or Relay route can't run
|
||||
// without a paired Relay, so fall back to the always-available defaults.
|
||||
LaunchedEffect(relayVoiceReady, currentEngine, currentAudioRoute) {
|
||||
if (!relayVoiceReady) {
|
||||
if (currentEngine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefsRepo.setEngineMode(VoiceEngineMode.HermesVoiceOutput)
|
||||
}
|
||||
val coerced = coerceAudioRoute(
|
||||
engine = VoiceEngineMode.HermesVoiceOutput,
|
||||
route = currentAudioRoute,
|
||||
relayVoiceReady = false,
|
||||
)
|
||||
if (coerced != currentAudioRoute) {
|
||||
prefsRepo.setAudioRoute(coerced)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionCard(title = stringResource(R.string.voice_settings_for_profile_title)) {
|
||||
Text(
|
||||
text = stringResource(R.string.voice_settings_engine_label),
|
||||
|
||||
@@ -99,8 +99,14 @@ private const val PREAMBLE =
|
||||
"The user is chatting via the Hermes-Relay Android app. " +
|
||||
"Keep responses mobile-friendly and concise when possible."
|
||||
|
||||
/** Representative capability used only by the Settings preview fixture. */
|
||||
internal val PHONE_CONTEXT_PREVIEW_TOOLS = setOf("android_phone_status")
|
||||
|
||||
/**
|
||||
* Build the system-prompt block from [settings] + [snapshot].
|
||||
* Build the system-prompt block from [settings] + [snapshot]. Relay-only
|
||||
* bridge guidance is emitted only when [availableTools] proves that this exact
|
||||
* selected session/profile can call at least one `android_*` tool. A missing
|
||||
* catalog fails closed for tool claims while preserving neutral mobile context.
|
||||
*
|
||||
* Returns `null` iff:
|
||||
* 1. [AppContextSettings.master] is false, OR
|
||||
@@ -112,14 +118,27 @@ private const val PREAMBLE =
|
||||
* itself is useful (it's the original v0.1.0 behavior). The "everything
|
||||
* off → null" case in the brief is the `master=false` branch.
|
||||
*/
|
||||
fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): String? {
|
||||
fun buildPromptBlock(
|
||||
settings: AppContextSettings,
|
||||
snapshot: PhoneSnapshot,
|
||||
availableTools: Set<String>? = null,
|
||||
): String? {
|
||||
if (!settings.master) return null
|
||||
|
||||
val lines = mutableListOf<String>()
|
||||
lines += PREAMBLE
|
||||
|
||||
if (settings.bridgeState) {
|
||||
lines += buildBridgeLine(snapshot)
|
||||
val phoneControlTools = availableTools
|
||||
?.filterTo(mutableSetOf()) {
|
||||
it.startsWith("android_") && it != "android_setup"
|
||||
}
|
||||
.orEmpty()
|
||||
|
||||
if (settings.bridgeState && phoneControlTools.isNotEmpty()) {
|
||||
lines += buildBridgeLine(
|
||||
snapshot = snapshot,
|
||||
phoneStatusToolAvailable = "android_phone_status" in phoneControlTools,
|
||||
)
|
||||
}
|
||||
|
||||
if (settings.currentApp && snapshot.currentApp != null) {
|
||||
@@ -130,7 +149,7 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
lines += "Battery: ${snapshot.batteryPercent}%."
|
||||
}
|
||||
|
||||
if (settings.safetyStatus) {
|
||||
if (settings.safetyStatus && phoneControlTools.isNotEmpty()) {
|
||||
buildSafetyLine(snapshot)?.let { lines += it }
|
||||
}
|
||||
|
||||
@@ -151,7 +170,10 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
* the bridge isn't bound — "Phone bridge: not installed" is itself useful
|
||||
* context (tells the agent not to try tool calls into the phone).
|
||||
*/
|
||||
private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
private fun buildBridgeLine(
|
||||
snapshot: PhoneSnapshot,
|
||||
phoneStatusToolAvailable: Boolean,
|
||||
): String {
|
||||
if (!snapshot.bridgeBound) {
|
||||
return "Phone bridge: not connected. Tool calls into the phone are unavailable."
|
||||
}
|
||||
@@ -189,8 +211,12 @@ private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
|
||||
val screenText = if (snapshot.screenOn) "Screen: on." else "Screen: off."
|
||||
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText " +
|
||||
"For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
val statusToolHint = if (phoneStatusToolAvailable) {
|
||||
" For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText$statusToolHint"
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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) {
|
||||
|
||||
@@ -72,8 +72,9 @@ data class GitTarget(
|
||||
/**
|
||||
* View model for the Git State Android surface (read + write).
|
||||
*
|
||||
* Loads the scanned repo list from the Hermes-Relay plugin and, on selection,
|
||||
* fetches working-tree status + branches. Mutations (stage/unstage/discard/
|
||||
* Loads the active session repository from upstream first and adds repositories
|
||||
* discovered by the Hermes-Relay plugin. On selection it fetches working-tree
|
||||
* status + branches. Mutations (stage/unstage/discard/
|
||||
* commit/fetch/pull/push/checkout) all require the ``plugin.api.write`` grant:
|
||||
* ``configure`` binds one connection/profile/Dashboard owner and every mutation
|
||||
* refuses (surfacing a readable message, never a POST) when that owner's grant
|
||||
@@ -119,12 +120,12 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
private var mutationJob: Job? = null
|
||||
private var messageJob: Job? = null
|
||||
private var scopeKey: String? = null
|
||||
private var sessionRepoPath: String? = null
|
||||
private var targetGeneration: Long = 0
|
||||
|
||||
fun selectedRepoIdForDisplay(): String? = _selectedRepoId.value
|
||||
|
||||
fun currentTarget(): GitTarget? {
|
||||
if (!_scanningEnabled.value) return null
|
||||
val owner = scopeKey ?: return null
|
||||
val repo = _selectedRepoId.value ?: return null
|
||||
return GitTarget(owner, repo, targetGeneration)
|
||||
@@ -143,10 +144,34 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
api = dashboard?.let(::GitStateApiClient)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind standard Git to the active upstream session workspace.
|
||||
*
|
||||
* An exact `git_repo_root` wins; `cwd` is the official Desktop-compatible
|
||||
* fallback. Changing sessions invalidates every selected repository target
|
||||
* before starting a fresh, owner-bound discovery pass.
|
||||
*/
|
||||
fun setSessionWorkspace(repoRoot: String?, workingDirectory: String?) {
|
||||
val next = repoRoot?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: workingDirectory?.trim()?.takeIf { it.isNotBlank() }
|
||||
if (sessionRepoPath == next) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
sessionRepoPath = next
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
// Preserve lazy discovery: the first host scan still starts only when
|
||||
// the Git workspace asks for it. Once visible/loaded, a session switch
|
||||
// refreshes immediately against the new exact workspace.
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
fun setScanningEnabled(enabled: Boolean) {
|
||||
if (_scanningEnabled.value == enabled) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
_scanningEnabled.value = enabled
|
||||
if (!enabled) clearWorkspaceState()
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
/** Grants the plugin.api.write capability for this connection/profile. */
|
||||
@@ -158,7 +183,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
fun hasWriteGrant(): Boolean = _writeGrant.value
|
||||
|
||||
fun loadRepos() {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: run {
|
||||
_repos.value = GitStateUiState.Error("Dashboard connection unavailable")
|
||||
return
|
||||
@@ -167,7 +191,10 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
reposJob?.cancel()
|
||||
reposJob = viewModelScope.launch {
|
||||
_repos.value = GitStateUiState.Loading
|
||||
client.repos().fold(
|
||||
client.repos(
|
||||
sessionRepoPath = sessionRepoPath,
|
||||
includeRelayDiscovery = _scanningEnabled.value,
|
||||
).fold(
|
||||
onSuccess = { list ->
|
||||
if (scopeKey == expectedScope) {
|
||||
_repos.value = GitStateUiState.Ready(list, null)
|
||||
@@ -208,7 +235,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
}
|
||||
|
||||
fun selectRepo(repoId: String) {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: return
|
||||
targetGeneration += 1
|
||||
_selectedRepoId.value = repoId
|
||||
|
||||
+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,12 +665,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">Permita que o agente inicie conversas com você (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas avançadas</string>
|
||||
<string name="settings_threads_desc">Conversas iniciadas pelo Relay e entrega proativa (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas do Relay</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Acesso ao shell do servidor por uma sessão pareada do relay</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -673,7 +682,7 @@
|
||||
<string name="settings_notification_companion">Assistente de notificações</string>
|
||||
<string name="settings_notification_companion_desc">Notificações compartilhadas do celular para ferramentas pareadas do relay</string>
|
||||
<string name="settings_media">Mídia</string>
|
||||
<string name="settings_media_desc">Anexos recebidos pelo Relay, busca automática e limite do cache</string>
|
||||
<string name="settings_media_desc">Anexos do chat, downloads, privacidade e cache</string>
|
||||
<string name="settings_bridge_safety">Segurança do Bridge</string>
|
||||
<string name="settings_bridge_safety_desc">Lista de bloqueio, confirmação de verbos destrutivos e desativação automática</string>
|
||||
<string name="settings_sideload">Sideload</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>
|
||||
@@ -1153,8 +1162,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Mídia</string>
|
||||
<string name="media_back">Voltar</string>
|
||||
<string name="media_intro_1">Controla como o app lida com arquivos enviados pelos resultados de ferramentas (capturas de tela, PDFs etc.) pelo relay.</string>
|
||||
<string name="media_intro_2">Somente Relay — estas configurações não afetam as imagens que você anexa no chat nem nada em uma conexão padrão (sem Relay).</string>
|
||||
<string name="media_intro_1">Controla como o app baixa, protege e armazena em cache os arquivos enviados pelo Hermes no chat.</string>
|
||||
<string name="media_intro_2">A mídia padrão do Dashboard é priorizada. Quando pareado, o Relay pode acrescentar entrega de compatibilidade e metadados de sensibilidade.</string>
|
||||
<string name="media_max_inbound">Tamanho máximo dos anexos recebidos</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Arquivos maiores que isso são rejeitados após o download.</string>
|
||||
@@ -2071,7 +2080,8 @@
|
||||
<string name="session_path_signin_for_gateway">Entre em Gerenciar para usar o Gateway com pensamento ao vivo.</string>
|
||||
<string name="session_path_gateway_api_server">Disponível no transporte do Gateway — esta sessão transmite pelo servidor API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay pareado, mas desconectado.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o relay para enviar e receber mídia.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o Relay para compatibilidade de mídia em hosts Hermes mais antigos.</string>
|
||||
<string name="session_path_media_not_ready">Atualize o Hermes para entrega de mídia padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="session_path_pair_relay_terminal">Pareie o relay para acessar o terminal.</string>
|
||||
<string name="session_path_voice_not_ready">A voz não está pronta nesta conexão.</string>
|
||||
<string name="session_path_threads_pair_relay">Pareie o relay e ative \"Permitir que o Hermes me envie mensagens\" para o agente poder abrir Threads.</string>
|
||||
@@ -2669,6 +2679,8 @@
|
||||
<string name="inbound_attach_downloading">Baixando…%1$s</string>
|
||||
<string name="inbound_attach_failed">Falha no anexo</string>
|
||||
<string name="inbound_attach_tap_retry">Toque para tentar novamente</string>
|
||||
<string name="inbound_attach_host_only">O arquivo está no seu host Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Atualize o Hermes para downloads padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="inbound_attach_open">Abrir externamente</string>
|
||||
<string name="inbound_attach_share">Compartilhar</string>
|
||||
<string name="inbound_attach_save">Salvar no dispositivo</string>
|
||||
@@ -3142,6 +3154,8 @@
|
||||
<string name="diag_check_ready_with">Pronto com %s</string>
|
||||
<string name="diag_check_relay_active">Relay ativo</string>
|
||||
<string name="diag_check_relay_not_configured">Relay não configurado</string>
|
||||
<string name="diag_relay_tools_optional">Ferramentas do Relay (opcionais)</string>
|
||||
<string name="diag_relay_tools_not_paired">Não pareado</string>
|
||||
<string name="diag_check_relay_server">Verificar servidor relay</string>
|
||||
<string name="diag_check_relay_plugin">Plugin do Relay</string>
|
||||
<string name="diag_plugin_not_configured">O plugin opcional não está configurado</string>
|
||||
@@ -3171,8 +3185,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancelar</string>
|
||||
<string name="inbound_attach_open_failed">Não foi possível abrir o anexo</string>
|
||||
<string name="inbound_attach_share_failed">Não foi possível compartilhar o anexo</string>
|
||||
<string name="injected_context_media_no_relay">A mídia exige uma conexão ativa com o Relay</string>
|
||||
<string name="injected_context_media_relay_active">Relay ativo para mídia</string>
|
||||
<string name="injected_context_media_no_relay">Nenhuma instrução extra de mídia — a entrega padrão continua sob responsabilidade do servidor</string>
|
||||
<string name="injected_context_media_relay_active">Aprimoramento de mídia do Relay disponível</string>
|
||||
<string name="injected_context_media_title">Compartilhamento de mídia</string>
|
||||
<string name="injected_context_persona_not_set">Nenhuma persona definida</string>
|
||||
<string name="injected_context_persona_server_side">Persona no servidor</string>
|
||||
@@ -3239,7 +3253,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 +3344,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 +3369,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>
|
||||
@@ -4323,7 +4337,7 @@
|
||||
<string name="chat_git_deletions">%1$d exclusões</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d alteração</item><item quantity="other">%1$d alterações</item></plurals>
|
||||
<string name="settings_git_workspace">Espaço de trabalho Git</string>
|
||||
<string name="settings_git_workspace_desc">Revise alterações, branches, commits e remotos</string>
|
||||
<string name="settings_git_workspace_desc">Git da sessão atual primeiro, com descoberta opcional do host</string>
|
||||
<string name="current_chat_activity_title">Atividade atual do chat</string>
|
||||
<string name="current_chat_activity_subtitle">Detalhes ao vivo e somente leitura deste chat</string>
|
||||
<string name="current_chat_activity_open">Visualizar atividade atual do chat</string>
|
||||
@@ -4358,7 +4372,7 @@
|
||||
<string name="agent_activity_child_role_task">Tarefa</string>
|
||||
<string name="agent_activity_child_role_agent">Agente</string>
|
||||
<string name="agent_activity_child_role_system">Sistema</string>
|
||||
<string name="settings_git_workspace_off_desc">Desativado · A verificação de repositórios no host é opcional</string>
|
||||
<string name="settings_git_workspace_off_desc">Somente repositório da sessão · A descoberta do host é opcional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4369,7 +4383,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 +4400,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,12 +703,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">允许代理主动与你对话(默认关闭)</string>
|
||||
<string name="settings_power_tools">高级工具</string>
|
||||
<string name="settings_threads_desc">由 Relay 发起的对话和主动推送(默认关闭)</string>
|
||||
<string name="settings_power_tools">Relay 工具</string>
|
||||
<string name="settings_terminal">终端</string>
|
||||
<string name="settings_terminal_desc">通过已配对的 Relay 会话访问服务器 shell</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -712,7 +720,7 @@
|
||||
<string name="settings_notification_companion">通知助手</string>
|
||||
<string name="settings_notification_companion_desc">为已配对的 Relay 工具共享手机通知</string>
|
||||
<string name="settings_media">媒体</string>
|
||||
<string name="settings_media_desc">Relay 入站附件、自动获取、缓存上限</string>
|
||||
<string name="settings_media_desc">聊天附件、下载行为、隐私和缓存</string>
|
||||
<string name="settings_bridge_safety">Bridge 安全</string>
|
||||
<string name="settings_bridge_safety_desc">黑名单、破坏性动词确认、自动禁用</string>
|
||||
<string name="settings_sideload">Sideload</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>
|
||||
@@ -1204,8 +1212,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">媒体</string>
|
||||
<string name="media_back">返回</string>
|
||||
<string name="media_intro_1">控制应用如何处理通过 Relay 传来的工具结果文件(截图、PDF 等)。</string>
|
||||
<string name="media_intro_2">仅限 Relay——这些设置不影响你在聊天中附加的图片或标准(无 Relay)连接上的任何内容。</string>
|
||||
<string name="media_intro_1">控制应用如何下载、保护和缓存 Hermes 在聊天中发送的文件。</string>
|
||||
<string name="media_intro_2">优先使用标准 Dashboard 媒体。配对后,Relay 可补充兼容性传输和敏感度元数据。</string>
|
||||
<string name="media_max_inbound">最大入站附件大小</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">超过此大小的文件在下载后被拒绝。</string>
|
||||
@@ -2158,7 +2166,8 @@
|
||||
<string name="session_path_signin_for_gateway">请在管理页面登录以使用实时思考 Gateway。</string>
|
||||
<string name="session_path_gateway_api_server">Gateway 传输可用——此会话通过 API 服务器传输。</string>
|
||||
<string name="session_path_relay_not_connected">Relay 已配对但未连接。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay 以发送和接收媒体。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay,以兼容较旧 Hermes 主机上的媒体。</string>
|
||||
<string name="session_path_media_not_ready">更新 Hermes 以使用标准媒体传输,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="session_path_pair_relay_terminal">配对 Relay 以使用终端。</string>
|
||||
<string name="session_path_voice_not_ready">此连接的语音未就绪。</string>
|
||||
<string name="session_path_threads_pair_relay">配对 Relay 并开启"让 Hermes 联系我",代理才能打开话题。</string>
|
||||
@@ -2783,6 +2792,8 @@
|
||||
<string name="inbound_attach_downloading">正在下载…%1$s</string>
|
||||
<string name="inbound_attach_failed">附件失败</string>
|
||||
<string name="inbound_attach_tap_retry">点击重试</string>
|
||||
<string name="inbound_attach_host_only">文件位于你的 Hermes 主机上</string>
|
||||
<string name="inbound_attach_host_only_help">更新 Hermes 以使用标准下载,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="inbound_attach_open">外部打开</string>
|
||||
<string name="inbound_attach_share">分享</string>
|
||||
<string name="inbound_attach_save">保存到设备</string>
|
||||
@@ -3242,6 +3253,8 @@
|
||||
<string name="diag_check_ready_with">已就绪(%s)</string>
|
||||
<string name="diag_check_relay_active">Relay 活跃</string>
|
||||
<string name="diag_check_relay_not_configured">Relay 未配置</string>
|
||||
<string name="diag_relay_tools_optional">Relay 工具(可选)</string>
|
||||
<string name="diag_relay_tools_not_paired">未配对</string>
|
||||
<string name="diag_check_relay_server">检查 Relay 服务器</string>
|
||||
<string name="diag_check_relay_plugin">Relay 插件</string>
|
||||
<string name="diag_plugin_not_configured">未配置可选插件</string>
|
||||
@@ -3271,8 +3284,8 @@
|
||||
<string name="inbound_attach_cd_cancel">取消</string>
|
||||
<string name="inbound_attach_open_failed">无法打开附件</string>
|
||||
<string name="inbound_attach_share_failed">无法分享附件</string>
|
||||
<string name="injected_context_media_no_relay">媒体需要活跃的 Relay 连接</string>
|
||||
<string name="injected_context_media_relay_active">Relay 已为媒体激活</string>
|
||||
<string name="injected_context_media_no_relay">没有额外媒体指令——标准传输仍由服务器负责</string>
|
||||
<string name="injected_context_media_relay_active">Relay 媒体增强可用</string>
|
||||
<string name="injected_context_media_title">媒体共享</string>
|
||||
<string name="injected_context_persona_not_set">未设置角色</string>
|
||||
<string name="injected_context_persona_server_side">服务端角色</string>
|
||||
@@ -3339,7 +3352,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 +3455,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 +3521,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>
|
||||
@@ -4405,7 +4418,7 @@
|
||||
<string name="chat_git_deletions">删除 %1$d 行</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 个更改</item></plurals>
|
||||
<string name="settings_git_workspace">Git 工作区</string>
|
||||
<string name="settings_git_workspace_desc">查看更改、分支、提交和远程仓库</string>
|
||||
<string name="settings_git_workspace_desc">优先使用当前会话的 Git,可选择发现主机仓库</string>
|
||||
<string name="current_chat_activity_title">当前聊天活动</string>
|
||||
<string name="current_chat_activity_subtitle">此聊天中的只读实时详情</string>
|
||||
<string name="current_chat_activity_open">预览当前聊天活动</string>
|
||||
@@ -4440,7 +4453,7 @@
|
||||
<string name="agent_activity_child_role_task">任务</string>
|
||||
<string name="agent_activity_child_role_agent">代理</string>
|
||||
<string name="agent_activity_child_role_system">系统</string>
|
||||
<string name="settings_git_workspace_off_desc">关闭 · 主机仓库扫描需手动启用</string>
|
||||
<string name="settings_git_workspace_off_desc">仅会话仓库 · 主机发现需手动启用</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4451,7 +4464,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,12 +706,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">Dem Agenten erlauben, Unterhaltungen mit dir zu beginnen (standardmäßig aus)</string>
|
||||
<string name="settings_power_tools">Profiwerkzeuge</string>
|
||||
<string name="settings_threads_desc">Vom Relay gestartete Unterhaltungen und proaktive Zustellung (standardmäßig aus)</string>
|
||||
<string name="settings_power_tools">Relay-Werkzeuge</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Zugriff auf die Server-Shell über eine gekoppelte Relay-Sitzung</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -714,7 +723,7 @@
|
||||
<string name="settings_notification_companion">Benachrichtigungsassistent</string>
|
||||
<string name="settings_notification_companion_desc">Geteilte Smartphone-Benachrichtigungen für gekoppelte Relay-Werkzeuge</string>
|
||||
<string name="settings_media">Medien</string>
|
||||
<string name="settings_media_desc">Eingehende Relay-Anhänge, automatischer Abruf, Cache-Limit</string>
|
||||
<string name="settings_media_desc">Chat-Anhänge, Downloadverhalten, Datenschutz und Cache</string>
|
||||
<string name="settings_bridge_safety">Bridge-Sicherheit</string>
|
||||
<string name="settings_bridge_safety_desc">Sperrliste, Bestätigung destruktiver Verben, automatische Deaktivierung</string>
|
||||
<string name="settings_sideload">Sideload</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>
|
||||
@@ -1209,8 +1218,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Medien</string>
|
||||
<string name="media_back">Zurück</string>
|
||||
<string name="media_intro_1">Legt fest, wie die App über das Relay gesendete Dateien aus Werkzeugergebnissen (Screenshots, PDFs usw.) behandelt.</string>
|
||||
<string name="media_intro_2">Nur Relay — diese Einstellungen betreffen weder Bilder, die du im Chat anhängst, noch Inhalte einer Standardverbindung ohne Relay.</string>
|
||||
<string name="media_intro_1">Legt fest, wie die App von Hermes im Chat gesendete Dateien herunterlädt, schützt und zwischenspeichert.</string>
|
||||
<string name="media_intro_2">Standardmäßig werden Dashboard-Medien bevorzugt. Wenn Relay gekoppelt ist, kann es Kompatibilitätszustellung und Vertraulichkeitsmetadaten ergänzen.</string>
|
||||
<string name="media_max_inbound">Max. Größe eingehender Anhänge</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Größere Dateien werden nach dem Download abgelehnt.</string>
|
||||
@@ -2163,7 +2172,8 @@
|
||||
<string name="session_path_signin_for_gateway">Melde dich unter Verwalten für das Live-Denken-Gateway an.</string>
|
||||
<string name="session_path_gateway_api_server">Auf dem Gateway-Transport verfügbar — diese Sitzung streamt über den API-Server.</string>
|
||||
<string name="session_path_relay_not_connected">Relay gekoppelt, aber nicht verbunden.</string>
|
||||
<string name="session_path_pair_relay_media">Kopple das Relay, um Medien zu senden und zu empfangen.</string>
|
||||
<string name="session_path_pair_relay_media">Kopple Relay für Medienkompatibilität mit älteren Hermes-Hosts.</string>
|
||||
<string name="session_path_media_not_ready">Aktualisiere Hermes für die standardmäßige Medienzustellung oder kopple Relay für Kompatibilität.</string>
|
||||
<string name="session_path_pair_relay_terminal">Kopple das Relay für Terminalzugriff.</string>
|
||||
<string name="session_path_voice_not_ready">Sprache ist bei dieser Verbindung nicht bereit.</string>
|
||||
<string name="session_path_threads_pair_relay">Kopple das Relay und aktiviere „Hermes darf mir schreiben“, damit der Agent Threads öffnen kann.</string>
|
||||
@@ -2788,6 +2798,8 @@
|
||||
<string name="inbound_attach_downloading">Download läuft…%1$s</string>
|
||||
<string name="inbound_attach_failed">Anhang fehlgeschlagen</string>
|
||||
<string name="inbound_attach_tap_retry">Zum erneuten Versuch tippen</string>
|
||||
<string name="inbound_attach_host_only">Datei befindet sich auf deinem Hermes-Host</string>
|
||||
<string name="inbound_attach_host_only_help">Aktualisiere Hermes für Standarddownloads oder kopple Relay für Kompatibilität.</string>
|
||||
<string name="inbound_attach_open">Extern öffnen</string>
|
||||
<string name="inbound_attach_share">Teilen</string>
|
||||
<string name="inbound_attach_save">Auf Gerät speichern</string>
|
||||
@@ -3310,6 +3322,8 @@
|
||||
<string name="diag_check_ready_with">Bereit mit %s</string>
|
||||
<string name="diag_check_relay_active">Relay aktiv</string>
|
||||
<string name="diag_check_relay_not_configured">Relay nicht konfiguriert</string>
|
||||
<string name="diag_relay_tools_optional">Relay-Werkzeuge (optional)</string>
|
||||
<string name="diag_relay_tools_not_paired">Nicht gekoppelt</string>
|
||||
<string name="diag_check_relay_server">Relay-Server prüfen</string>
|
||||
<string name="diag_check_relay_plugin">Relay-Plugin</string>
|
||||
<string name="diag_plugin_not_configured">Optionales Plugin ist nicht konfiguriert</string>
|
||||
@@ -3339,8 +3353,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Abbrechen</string>
|
||||
<string name="inbound_attach_open_failed">Anhang konnte nicht geöffnet werden</string>
|
||||
<string name="inbound_attach_share_failed">Anhang konnte nicht geteilt werden</string>
|
||||
<string name="injected_context_media_no_relay">Medien erfordern eine aktive Relay-Verbindung</string>
|
||||
<string name="injected_context_media_relay_active">Relay für Medien aktiv</string>
|
||||
<string name="injected_context_media_no_relay">Keine zusätzliche Medienanweisung — die Standardzustellung bleibt Aufgabe des Servers</string>
|
||||
<string name="injected_context_media_relay_active">Relay-Medienerweiterung verfügbar</string>
|
||||
<string name="injected_context_media_title">Medienfreigabe</string>
|
||||
<string name="injected_context_persona_not_set">Keine Persona festgelegt</string>
|
||||
<string name="injected_context_persona_server_side">Serverseitige Persona</string>
|
||||
@@ -3407,7 +3421,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 +3525,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 +3589,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>
|
||||
@@ -4480,7 +4494,7 @@
|
||||
<string name="chat_git_deletions">%1$d Löschungen</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d Änderung</item><item quantity="other">%1$d Änderungen</item></plurals>
|
||||
<string name="settings_git_workspace">Git-Arbeitsbereich</string>
|
||||
<string name="settings_git_workspace_desc">Änderungen, Branches, Commits und Remotes prüfen</string>
|
||||
<string name="settings_git_workspace_desc">Zuerst Git der aktuellen Sitzung, mit optionaler Host-Erkennung</string>
|
||||
<string name="current_chat_activity_title">Aktuelle Chat-Aktivität</string>
|
||||
<string name="current_chat_activity_subtitle">Schreibgeschützte Live-Details aus diesem Chat</string>
|
||||
<string name="current_chat_activity_open">Aktuelle Chat-Aktivität ansehen</string>
|
||||
@@ -4515,7 +4529,7 @@
|
||||
<string name="agent_activity_child_role_task">Aufgabe</string>
|
||||
<string name="agent_activity_child_role_agent">Agent</string>
|
||||
<string name="agent_activity_child_role_system">System</string>
|
||||
<string name="settings_git_workspace_off_desc">Aus · Repository-Scan auf dem Host ist optional</string>
|
||||
<string name="settings_git_workspace_off_desc">Nur Sitzungs-Repository · Host-Erkennung ist optional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4526,7 +4540,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 +4557,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>
|
||||
@@ -628,8 +637,8 @@
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Panel de voz, opciones relay en tiempo real, proveedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Permita que el agente inicie conversaciones con usted (desactivado de forma predeterminada)</string>
|
||||
<string name="settings_power_tools">herramientas eléctricas</string>
|
||||
<string name="settings_threads_desc">Conversaciones iniciadas por Relay y entrega proactiva (desactivado de forma predeterminada)</string>
|
||||
<string name="settings_power_tools">Herramientas de Relay</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Acceso al shell del servidor a través de una sesión relay emparejada</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -641,7 +650,7 @@
|
||||
<string name="settings_notification_companion">Compañero de notificación</string>
|
||||
<string name="settings_notification_companion_desc">Notificaciones telefónicas compartidas para herramientas relay emparejadas</string>
|
||||
<string name="settings_media">Medios de comunicación</string>
|
||||
<string name="settings_media_desc">Relay archivos adjuntos entrantes, búsqueda automática, límite de caché</string>
|
||||
<string name="settings_media_desc">Adjuntos del chat, descargas, privacidad y caché</string>
|
||||
<string name="settings_bridge_safety">seguridad Bridge</string>
|
||||
<string name="settings_bridge_safety_desc">Lista de bloqueo, confirmación de verbo destructivo, desactivación automática</string>
|
||||
<string name="settings_sideload">Carga lateral</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>
|
||||
@@ -1110,8 +1119,8 @@
|
||||
<string name="about_credits">Axiom Labs ❤️ Agente Hermes · Nous Research</string>
|
||||
<string name="media_title">Medios de comunicación</string>
|
||||
<string name="media_back">Atrás</string>
|
||||
<string name="media_intro_1">Controla cómo la aplicación maneja los archivos enviados por los resultados de la herramienta (capturas de pantalla, PDF, etc.) a través del relay.</string>
|
||||
<string name="media_intro_2">Solo Relay: esta configuración no afecta a las imágenes que adjunte en el chat ni a nada en una conexión estándar (no-Relay).</string>
|
||||
<string name="media_intro_1">Controla cómo la aplicación descarga, protege y almacena en caché los archivos que Hermes envía en el chat.</string>
|
||||
<string name="media_intro_2">Se priorizan los archivos multimedia del Dashboard estándar. Cuando está emparejado, Relay puede añadir entrega de compatibilidad y metadatos de confidencialidad.</string>
|
||||
<string name="media_max_inbound">Tamaño máximo del archivo adjunto entrante</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Los archivos de mayor tamaño se rechazan después de la descarga.</string>
|
||||
@@ -1980,7 +1989,8 @@
|
||||
<string name="session_path_signin_for_gateway">Inicie sesión en Administrar para el gateway que piensa en vivo.</string>
|
||||
<string name="session_path_gateway_api_server">Disponible en el transporte gateway: esta sesión se transmite a través del servidor API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay emparejado pero no conectado.</string>
|
||||
<string name="session_path_pair_relay_media">Empareje el relay para enviar y recibir medios.</string>
|
||||
<string name="session_path_pair_relay_media">Empareja Relay para obtener compatibilidad multimedia en hosts Hermes antiguos.</string>
|
||||
<string name="session_path_media_not_ready">Actualiza Hermes para la entrega multimedia estándar o empareja Relay por compatibilidad.</string>
|
||||
<string name="session_path_pair_relay_terminal">Empareje el relay para acceder al terminal.</string>
|
||||
<string name="session_path_voice_not_ready">La voz no está lista en esta conexión.</string>
|
||||
<string name="session_path_threads_pair_relay">Empareje el relay y active "Dejar que Hermes me envíe un mensaje" para que el agente pueda abrir Threads.</string>
|
||||
@@ -2547,6 +2557,8 @@
|
||||
<string name="inbound_attach_downloading">Descargando…%1$s</string>
|
||||
<string name="inbound_attach_failed">Error al adjuntar</string>
|
||||
<string name="inbound_attach_tap_retry">Toca para volver a intentarlo</string>
|
||||
<string name="inbound_attach_host_only">El archivo está en tu host de Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Actualiza Hermes para las descargas estándar o empareja Relay por compatibilidad.</string>
|
||||
<string name="inbound_attach_open">Abierto externamente</string>
|
||||
<string name="inbound_attach_share">Compartir</string>
|
||||
<string name="inbound_attach_save">Guardar en dispositivo</string>
|
||||
@@ -2974,6 +2986,8 @@
|
||||
<string name="diag_check_ready_with">Listo con %s</string>
|
||||
<string name="diag_check_relay_active">Relay activo</string>
|
||||
<string name="diag_check_relay_not_configured">Relay no configurado</string>
|
||||
<string name="diag_relay_tools_optional">Herramientas de Relay (opcionales)</string>
|
||||
<string name="diag_relay_tools_not_paired">Sin emparejar</string>
|
||||
<string name="diag_check_relay_server">Verifique el servidor relay</string>
|
||||
<string name="diag_check_relay_plugin">Plugin de Relay</string>
|
||||
<string name="diag_plugin_not_configured">El plugin opcional no está configurado</string>
|
||||
@@ -3003,8 +3017,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancelar</string>
|
||||
<string name="inbound_attach_open_failed">No se pudo abrir el archivo adjunto</string>
|
||||
<string name="inbound_attach_share_failed">No se pudo compartir el archivo adjunto</string>
|
||||
<string name="injected_context_media_no_relay">Los medios requieren una conexión Relay activa</string>
|
||||
<string name="injected_context_media_relay_active">Relay activo para medios</string>
|
||||
<string name="injected_context_media_no_relay">Sin instrucciones multimedia adicionales: la entrega estándar sigue a cargo del servidor</string>
|
||||
<string name="injected_context_media_relay_active">Mejora multimedia de Relay disponible</string>
|
||||
<string name="injected_context_media_title">Compartir medios</string>
|
||||
<string name="injected_context_persona_not_set">No se ha definido ninguna persona</string>
|
||||
<string name="injected_context_persona_server_side">Persona del lado del servidor</string>
|
||||
@@ -3071,7 +3085,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>
|
||||
@@ -4171,7 +4185,7 @@
|
||||
<string name="chat_git_deletions">%1$d eliminaciones</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d cambio</item><item quantity="other">%1$d cambios</item></plurals>
|
||||
<string name="settings_git_workspace">Espacio de Git</string>
|
||||
<string name="settings_git_workspace_desc">Revisa cambios, ramas, commits y remotos</string>
|
||||
<string name="settings_git_workspace_desc">Primero el Git de la sesión actual, con detección opcional del host</string>
|
||||
<string name="current_chat_activity_title">Actividad actual del chat</string>
|
||||
<string name="current_chat_activity_subtitle">Detalles en vivo de solo lectura de este chat</string>
|
||||
<string name="current_chat_activity_open">Ver la actividad actual del chat</string>
|
||||
@@ -4206,7 +4220,7 @@
|
||||
<string name="agent_activity_child_role_task">Tarea</string>
|
||||
<string name="agent_activity_child_role_agent">Agente</string>
|
||||
<string name="agent_activity_child_role_system">Sistema</string>
|
||||
<string name="settings_git_workspace_off_desc">Desactivado · El análisis de repositorios del host es opcional</string>
|
||||
<string name="settings_git_workspace_off_desc">Solo el repositorio de la sesión · La detección del host es opcional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4217,7 +4231,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,12 +703,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">エージェントがあなたと会話を開始できるようにします (デフォルトではオフ)</string>
|
||||
<string name="settings_power_tools">パワーツール</string>
|
||||
<string name="settings_threads_desc">Relay が開始する会話とプロアクティブ配信(デフォルトではオフ)</string>
|
||||
<string name="settings_power_tools">Relay ツール</string>
|
||||
<string name="settings_terminal">ターミナル</string>
|
||||
<string name="settings_terminal_desc">ペアリングされたRelayセッションを介したサーバーシェルアクセス</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -712,7 +720,7 @@
|
||||
<string name="settings_notification_companion">通知コンパニオン</string>
|
||||
<string name="settings_notification_companion_desc">ペアリングされたRelayツールの共有電話通知</string>
|
||||
<string name="settings_media">メディア</string>
|
||||
<string name="settings_media_desc">Relay 受信添付ファイル、自動取得、キャッシュキャップ</string>
|
||||
<string name="settings_media_desc">チャットの添付ファイル、ダウンロード動作、プライバシー、キャッシュ</string>
|
||||
<string name="settings_bridge_safety">Bridge 安全性</string>
|
||||
<string name="settings_bridge_safety_desc">ブロックリスト、破壊的な動詞の確認、自動無効化</string>
|
||||
<string name="settings_sideload">サイドロード</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>
|
||||
@@ -1220,8 +1228,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">メディア</string>
|
||||
<string name="media_back">戻る</string>
|
||||
<string name="media_intro_1">ツールの結果 (スクリーンショット、PDF など) によってRelay経由で送信されたファイルをアプリが処理する方法を制御します。</string>
|
||||
<string name="media_intro_2">Relay のみ — これらの設定は、チャットに添付した画像や標準 (Relay なし) 接続上のものには影響しません。</string>
|
||||
<string name="media_intro_1">Hermes がチャットで送信したファイルのダウンロード、保護、キャッシュ方法を設定します。</string>
|
||||
<string name="media_intro_2">標準の Dashboard メディアが優先されます。Relay をペアリングすると、互換配信と機密性メタデータを追加できます。</string>
|
||||
<string name="media_max_inbound">受信添付ファイルの最大サイズ</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">これより大きいファイルはダウンロード後に拒否されます。</string>
|
||||
@@ -2174,7 +2182,8 @@
|
||||
<string name="session_path_signin_for_gateway">Live Thinking Gateway の [管理] でサインインします。</string>
|
||||
<string name="session_path_gateway_api_server">Gateway トランスポートで利用可能 — このセッションは API サーバー経由でストリーミングされます。</string>
|
||||
<string name="session_path_relay_not_connected">Relay はペアリングされていますが、接続されていません。</string>
|
||||
<string name="session_path_pair_relay_media">Relayをペアリングしてメディアを送受信します。</string>
|
||||
<string name="session_path_pair_relay_media">古い Hermes ホストとのメディア互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="session_path_media_not_ready">標準メディア配信には Hermes を更新するか、互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="session_path_pair_relay_terminal">ターミナルアクセス用にRelayをペアリングします。</string>
|
||||
<string name="session_path_voice_not_ready">この接続では音声の準備ができていません。</string>
|
||||
<string name="session_path_threads_pair_relay">Relayをペアリングし、「Hermes にメッセージを送信する」をオンにすると、エージェントが Threads を開けるようになります。</string>
|
||||
@@ -2797,6 +2806,8 @@
|
||||
<string name="inbound_attach_downloading">ダウンロード中…%1$s</string>
|
||||
<string name="inbound_attach_failed">添付に失敗しました</string>
|
||||
<string name="inbound_attach_tap_retry">タップして再試行してください</string>
|
||||
<string name="inbound_attach_host_only">ファイルは Hermes ホスト上にあります</string>
|
||||
<string name="inbound_attach_host_only_help">標準ダウンロードには Hermes を更新するか、互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="inbound_attach_open">外部に開く</string>
|
||||
<string name="inbound_attach_share">共有</string>
|
||||
<string name="inbound_attach_save">デバイスに保存</string>
|
||||
@@ -3318,6 +3329,8 @@
|
||||
<string name="diag_check_ready_with">%s で準備完了</string>
|
||||
<string name="diag_check_relay_active">Relay アクティブ</string>
|
||||
<string name="diag_check_relay_not_configured">Relay が構成されていません</string>
|
||||
<string name="diag_relay_tools_optional">Relay ツール(オプション)</string>
|
||||
<string name="diag_relay_tools_not_paired">未ペアリング</string>
|
||||
<string name="diag_check_relay_server">中継サーバーを確認する</string>
|
||||
<string name="diag_check_relay_plugin">Relay プラグイン</string>
|
||||
<string name="diag_plugin_not_configured">オプションのプラグインが設定されていません</string>
|
||||
@@ -3347,8 +3360,8 @@
|
||||
<string name="inbound_attach_cd_cancel">キャンセル</string>
|
||||
<string name="inbound_attach_open_failed">添付ファイルを開けませんでした</string>
|
||||
<string name="inbound_attach_share_failed">添付ファイルを共有できませんでした</string>
|
||||
<string name="injected_context_media_no_relay">メディアにはアクティブな Relay 接続が必要です</string>
|
||||
<string name="injected_context_media_relay_active">Relay はメディア向けにアクティブです</string>
|
||||
<string name="injected_context_media_no_relay">追加のメディア指示なし — 標準配信は引き続きサーバーが担当します</string>
|
||||
<string name="injected_context_media_relay_active">Relay メディア拡張を利用できます</string>
|
||||
<string name="injected_context_media_title">メディア共有</string>
|
||||
<string name="injected_context_persona_not_set">ペルソナ設定なし</string>
|
||||
<string name="injected_context_persona_server_side">サーバー側のペルソナ</string>
|
||||
@@ -3415,7 +3428,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 +3519,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 +3585,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>
|
||||
@@ -4476,7 +4489,7 @@
|
||||
<string name="chat_git_deletions">%1$d 件の削除</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 件の変更</item></plurals>
|
||||
<string name="settings_git_workspace">Git ワークスペース</string>
|
||||
<string name="settings_git_workspace_desc">変更、ブランチ、コミット、リモートを確認</string>
|
||||
<string name="settings_git_workspace_desc">現在のセッションの Git を優先し、必要に応じてホストを検出</string>
|
||||
<string name="current_chat_activity_title">現在のチャットのアクティビティ</string>
|
||||
<string name="current_chat_activity_subtitle">このチャットからの読み取り専用ライブ詳細</string>
|
||||
<string name="current_chat_activity_open">現在のチャットのアクティビティを表示</string>
|
||||
@@ -4511,7 +4524,7 @@
|
||||
<string name="agent_activity_child_role_task">タスク</string>
|
||||
<string name="agent_activity_child_role_agent">エージェント</string>
|
||||
<string name="agent_activity_child_role_system">システム</string>
|
||||
<string name="settings_git_workspace_off_desc">オフ · ホストのリポジトリスキャンはオプトインです</string>
|
||||
<string name="settings_git_workspace_off_desc">セッションのリポジトリのみ · ホスト検出はオプトインです</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4522,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">この端末で使う Dashboard と Gateway のアドレスを設定します。プライベート LAN と Tailscale ルートは HTTP または HTTPS を使用でき、公開ルートには HTTPS が必要です。</string>
|
||||
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
|
||||
@@ -4539,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、公開ルートはこの 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,12 +682,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">Позволяет агенту начинать разговоры с вами (по умолчанию выключено)</string>
|
||||
<string name="settings_power_tools">Мощные инструменты</string>
|
||||
<string name="settings_threads_desc">Разговоры, начатые Relay, и проактивная доставка (по умолчанию выключено)</string>
|
||||
<string name="settings_power_tools">Инструменты Relay</string>
|
||||
<string name="settings_terminal">Терминал</string>
|
||||
<string name="settings_terminal_desc">Доступ к оболочке сервера через сопряженный сеанс Relay</string>
|
||||
<string name="settings_bridge">Мост</string>
|
||||
@@ -688,7 +699,7 @@
|
||||
<string name="settings_notification_companion">Сопровождение уведомлений</string>
|
||||
<string name="settings_notification_companion_desc">Общие уведомления телефона для сопряженных инструментов Relay</string>
|
||||
<string name="settings_media">Медиа</string>
|
||||
<string name="settings_media_desc">Передача входящих вложений, автозагрузка, кэш</string>
|
||||
<string name="settings_media_desc">Вложения чата, загрузка, конфиденциальность и кэш</string>
|
||||
<string name="settings_bridge_safety">Безопасность моста</string>
|
||||
<string name="settings_bridge_safety_desc">Черный список, подтверждение деструктивных действий, автоотключение</string>
|
||||
<string name="settings_sideload">Установка из APK</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>
|
||||
@@ -1222,8 +1233,8 @@
|
||||
<string name="about_credits">Axiom Labs ❤️ Агент Гермес · Nous Research</string>
|
||||
<string name="media_title">Медиа</string>
|
||||
<string name="media_back">Назад</string>
|
||||
<string name="media_intro_1">Управляет тем, как приложение обрабатывает файлы, отправленные результатами инструментов (скриншоты, PDF и т. д.) через Relay.</string>
|
||||
<string name="media_intro_2">Только Relay — эти настройки не влияют на изображения, которые вы прикрепляете в чате, или что-либо на стандартном (без Relay) соединении.</string>
|
||||
<string name="media_intro_1">Определяет, как приложение скачивает, защищает и кэширует файлы, отправленные Hermes в чате.</string>
|
||||
<string name="media_intro_2">Предпочтение отдаётся стандартным медиа Dashboard. После сопряжения Relay может добавить совместимую доставку и метаданные конфиденциальности.</string>
|
||||
<string name="media_max_inbound">Максимальный размер входящего вложения</string>
|
||||
<string name="media_max_inbound_value">%1$d МБ</string>
|
||||
<string name="media_max_inbound_desc">Файлы, превышающие этот размер, отклоняются после загрузки.</string>
|
||||
@@ -2174,7 +2185,8 @@
|
||||
<string name="session_path_signin_for_gateway">Войдите в систему под управлением для шлюза живого мышления.</string>
|
||||
<string name="session_path_gateway_api_server">Доступно на транспортном шлюзе — этот сеанс передается через сервер API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay сопряжён, но не подключен.</string>
|
||||
<string name="session_path_pair_relay_media">Сопрягите Relay для отправки и получения медиа.</string>
|
||||
<string name="session_path_pair_relay_media">Сопрягите Relay для совместимости медиа со старыми хостами Hermes.</string>
|
||||
<string name="session_path_media_not_ready">Обновите Hermes для стандартной доставки медиа или сопрягите Relay для совместимости.</string>
|
||||
<string name="session_path_pair_relay_terminal">Сопрягите Relay для доступа к терминалу.</string>
|
||||
<string name="session_path_voice_not_ready">Голос не готов на этом подключении.</string>
|
||||
<string name="session_path_threads_pair_relay">Сопрягите Relay и включите "Позволить Гермесу отправлять мне сообщения", чтобы агент мог открывать потоки.</string>
|
||||
@@ -2771,6 +2783,8 @@
|
||||
<string name="inbound_attach_downloading">Скачивание\&#8230;%1$s</string>
|
||||
<string name="inbound_attach_failed">Ошибка вложения</string>
|
||||
<string name="inbound_attach_tap_retry">Нажмите для повторной попытки</string>
|
||||
<string name="inbound_attach_host_only">Файл находится на вашем хосте Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Обновите Hermes для стандартных загрузок или сопрягите Relay для совместимости.</string>
|
||||
<string name="inbound_attach_open">Открыть внешне</string>
|
||||
<string name="inbound_attach_share">Поделиться</string>
|
||||
<string name="inbound_attach_save">Сохранить на устройство</string>
|
||||
@@ -3176,6 +3190,8 @@
|
||||
<string name="diag_check_ready_with">Готово с %s</string>
|
||||
<string name="diag_check_relay_active">Relay активен</string>
|
||||
<string name="diag_check_relay_not_configured">Relay не настроен</string>
|
||||
<string name="diag_relay_tools_optional">Инструменты Relay (необязательно)</string>
|
||||
<string name="diag_relay_tools_not_paired">Не сопряжено</string>
|
||||
<string name="diag_check_relay_server">Проверить сервер Relay</string>
|
||||
<string name="diag_check_relay_plugin">Плагин Relay</string>
|
||||
<string name="diag_plugin_not_configured">Дополнительный плагин не настроен</string>
|
||||
@@ -3207,8 +3223,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Отмена</string>
|
||||
<string name="inbound_attach_open_failed">Не удалось открыть вложение</string>
|
||||
<string name="inbound_attach_share_failed">Не удалось поделиться вложением</string>
|
||||
<string name="injected_context_media_no_relay">Для мультимедиа требуется активное подключение Relay</string>
|
||||
<string name="injected_context_media_relay_active">плагин Relay активен для мультимедиа</string>
|
||||
<string name="injected_context_media_no_relay">Нет дополнительных инструкций для медиа — стандартная доставка остаётся на стороне сервера</string>
|
||||
<string name="injected_context_media_relay_active">Доступно расширение Relay для медиа</string>
|
||||
<string name="injected_context_media_title">Обмен мультимедиа</string>
|
||||
<string name="injected_context_persona_not_set">Персона не установлена</string>
|
||||
<string name="injected_context_persona_server_side">Персона на стороне сервера</string>
|
||||
@@ -3275,7 +3291,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>
|
||||
@@ -4217,7 +4233,7 @@
|
||||
<string name="chat_git_deletions">Удалено строк: %1$d</string>
|
||||
<plurals name="chat_git_change_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="settings_git_workspace">Рабочая область Git</string>
|
||||
<string name="settings_git_workspace_desc">Изменения, ветки, коммиты и удалённые репозитории</string>
|
||||
<string name="settings_git_workspace_desc">Сначала Git текущего сеанса, с дополнительным обнаружением на хосте</string>
|
||||
<string name="current_chat_activity_title">Текущая активность чата</string>
|
||||
<string name="current_chat_activity_subtitle">Доступные только для чтения сведения в реальном времени из этого чата</string>
|
||||
<string name="current_chat_activity_open">Просмотреть текущую активность чата</string>
|
||||
@@ -4252,7 +4268,7 @@
|
||||
<string name="agent_activity_child_role_task">Задача</string>
|
||||
<string name="agent_activity_child_role_agent">Агент</string>
|
||||
<string name="agent_activity_child_role_system">Система</string>
|
||||
<string name="settings_git_workspace_off_desc">Выкл. · Сканирование репозиториев на хосте включается вручную</string>
|
||||
<string name="settings_git_workspace_off_desc">Только репозиторий сеанса · Обнаружение на хосте включается вручную</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4263,7 +4279,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,12 +751,12 @@
|
||||
<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>
|
||||
<string name="settings_threads_desc">Let the agent start conversations with you (off by default)</string>
|
||||
<string name="settings_power_tools">Power tools</string>
|
||||
<string name="settings_threads_desc">Relay-started conversations and proactive delivery (off by default)</string>
|
||||
<string name="settings_power_tools">Relay tools</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Server shell access through a paired relay session</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -759,7 +768,7 @@
|
||||
<string name="settings_notification_companion">Notification companion</string>
|
||||
<string name="settings_notification_companion_desc">Shared phone notifications for paired relay tools</string>
|
||||
<string name="settings_media">Media</string>
|
||||
<string name="settings_media_desc">Relay inbound attachments, auto-fetch, cache cap</string>
|
||||
<string name="settings_media_desc">Chat attachments, download behavior, privacy, and cache</string>
|
||||
<string name="settings_bridge_safety">Bridge safety</string>
|
||||
<string name="settings_bridge_safety_desc">Blocklist, destructive-verb confirmation, auto-disable</string>
|
||||
<string name="settings_sideload">Sideload</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>
|
||||
@@ -1374,8 +1383,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Media</string>
|
||||
<string name="media_back">Back</string>
|
||||
<string name="media_intro_1">Controls how the app handles files sent by tool results (screenshots, PDFs, etc.) over the relay.</string>
|
||||
<string name="media_intro_2">Relay only — these settings don\'t affect images you attach in chat or anything on a standard (no-Relay) connection.</string>
|
||||
<string name="media_intro_1">Controls how the app downloads, protects, and caches files Hermes sends in chat.</string>
|
||||
<string name="media_intro_2">Standard Dashboard media is preferred. When paired, Relay can add compatibility delivery and sensitivity metadata.</string>
|
||||
<string name="media_max_inbound">Max inbound attachment size</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Files larger than this are rejected after download.</string>
|
||||
@@ -2504,7 +2513,8 @@
|
||||
<string name="session_path_signin_for_gateway">Sign in under Manage for the live-thinking gateway.</string>
|
||||
<string name="session_path_gateway_api_server">Available on the gateway transport — this session streams over the API server.</string>
|
||||
<string name="session_path_relay_not_connected">Relay paired but not connected.</string>
|
||||
<string name="session_path_pair_relay_media">Pair the relay to send and receive media.</string>
|
||||
<string name="session_path_pair_relay_media">Pair Relay for media compatibility on older Hermes hosts.</string>
|
||||
<string name="session_path_media_not_ready">Update Hermes for standard media delivery, or pair Relay for compatibility.</string>
|
||||
<string name="session_path_pair_relay_terminal">Pair the relay for terminal access.</string>
|
||||
<string name="session_path_voice_not_ready">Voice not ready on this connection.</string>
|
||||
<string name="session_path_threads_pair_relay">Pair the relay and turn on "Let Hermes message me" so the agent can open Threads.</string>
|
||||
@@ -3152,6 +3162,8 @@
|
||||
<string name="inbound_attach_downloading">Downloading…%1$s</string>
|
||||
<string name="inbound_attach_failed">Attachment failed</string>
|
||||
<string name="inbound_attach_tap_retry">Tap to retry</string>
|
||||
<string name="inbound_attach_host_only">File is on your Hermes host</string>
|
||||
<string name="inbound_attach_host_only_help">Update Hermes for standard downloads, or pair Relay for compatibility.</string>
|
||||
<string name="inbound_attach_open">Open externally</string>
|
||||
<string name="inbound_attach_share">Share</string>
|
||||
<string name="inbound_attach_save">Save to device</string>
|
||||
@@ -3680,6 +3692,8 @@
|
||||
<string name="diag_check_ready_with">Ready with %s</string>
|
||||
<string name="diag_check_relay_active">Relay active</string>
|
||||
<string name="diag_check_relay_not_configured">Relay not configured</string>
|
||||
<string name="diag_relay_tools_optional">Relay tools (optional)</string>
|
||||
<string name="diag_relay_tools_not_paired">Not paired</string>
|
||||
<string name="diag_check_relay_server">Check relay server</string>
|
||||
<string name="diag_check_relay_plugin">Relay plugin</string>
|
||||
<string name="diag_plugin_not_configured">Optional plugin is not configured</string>
|
||||
@@ -3711,8 +3725,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancel</string>
|
||||
<string name="inbound_attach_open_failed">Couldn\u0027t open attachment</string>
|
||||
<string name="inbound_attach_share_failed">Couldn\u0027t share attachment</string>
|
||||
<string name="injected_context_media_no_relay">Media requires an active Relay connection</string>
|
||||
<string name="injected_context_media_relay_active">Relay active for media</string>
|
||||
<string name="injected_context_media_no_relay">No extra media instruction — standard delivery stays server-owned</string>
|
||||
<string name="injected_context_media_relay_active">Relay media enhancement available</string>
|
||||
<string name="injected_context_media_title">Media sharing</string>
|
||||
<string name="injected_context_persona_not_set">No persona set</string>
|
||||
<string name="injected_context_persona_server_side">Server-side persona</string>
|
||||
@@ -3781,7 +3795,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 +4260,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>
|
||||
@@ -4577,6 +4591,6 @@
|
||||
<string name="provider_usage_capability_basic_title">Basic usage from Hermes</string>
|
||||
<string name="provider_usage_capability_basic_body">Install or update the Relay plugin for credential pools, structured Nous balances, and OpenCode Go.</string>
|
||||
<string name="settings_git_workspace">Git workspace</string>
|
||||
<string name="settings_git_workspace_desc">Review changes, branches, commits, and remotes</string>
|
||||
<string name="settings_git_workspace_off_desc">Off · Host repository scanning is opt-in</string>
|
||||
<string name="settings_git_workspace_desc">Current-session Git first, with optional host discovery</string>
|
||||
<string name="settings_git_workspace_off_desc">Session repository only · Host discovery is opt-in</string>
|
||||
</resources>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,70 @@ class VoicePreferencesRepositoryTest {
|
||||
repository.setStopPhrases(emptyList())
|
||||
assertTrue(repository.settings.first().stopPhrases.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_normalizesOnlyRelayOwnedSelectionsInExpectedScope() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
val scope = repository.activeScope.value
|
||||
|
||||
assertTrue(repository.reconcileRelayRemoval(scope))
|
||||
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.HermesVoiceOutput.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Auto.storageValue, settings.audioRoute)
|
||||
assertFalse(repository.reconcileRelayRemoval(scope))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_doesNotMutateAProfileThatNoLongerOwnsTheScope() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
val staleScope = repository.activeScope.value
|
||||
|
||||
repository.setActiveScope("connection-a", "writer")
|
||||
assertFalse(repository.reconcileRelayRemoval(staleScope))
|
||||
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_doesNotRewriteGlobalDefaultSelectionSharedByAnotherConnection() = runTest {
|
||||
repository.setActiveScope("connection-a", null)
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
assertFalse(repository.reconcileRelayRemoval(repository.activeScope.value))
|
||||
|
||||
repository.setActiveScope("connection-b", null)
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_normalizesNamedProfileWithoutChangingSameProfileOnAnotherConnection() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
repository.setActiveScope("connection-b", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
assertTrue(repository.reconcileRelayRemoval(repository.activeScope.value))
|
||||
|
||||
repository.setActiveScope("connection-b", "coder")
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
}
|
||||
|
||||
private class InMemoryVoicePreferencesDataStore : DataStore<Preferences> {
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.hermesandroid.relay.network.relay
|
||||
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class RelayHttpClientMediaDownloadTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fetchMediaByPathStopsChunkedResponseAtCallerLimit() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/octet-stream")
|
||||
.setChunkedBody("x".repeat(64), 8),
|
||||
)
|
||||
val client = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = {
|
||||
server.url("/").toString().replaceFirst("http://", "ws://").trimEnd('/')
|
||||
},
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
)
|
||||
|
||||
val result = client.fetchMediaByPath("/tmp/large.bin", maxBytes = 16)
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("download limit"))
|
||||
assertEquals("/media/by-path", server.takeRequest().requestUrl?.encodedPath)
|
||||
}
|
||||
}
|
||||
@@ -1530,6 +1530,122 @@ class ChatHandlerTest {
|
||||
assertTrue(handler.messages.value.single().attachments.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_carriesHydratedMarkerAttachmentWithoutReloading() {
|
||||
var requestCount = 0
|
||||
val path = "/tmp/voice-note.mp3"
|
||||
handler.onMediaBarePathRequested = { messageId, requestedPath ->
|
||||
requestCount++
|
||||
handler.mutateMessage(messageId) { message ->
|
||||
message.copy(
|
||||
attachments = message.attachments + Attachment(
|
||||
contentType = "audio/mpeg",
|
||||
content = "",
|
||||
fileName = "voice-note.mp3",
|
||||
relayToken = requestedPath,
|
||||
cachedUri = "content://media/voice-note.mp3",
|
||||
state = AttachmentState.LOADED,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val history = listOf(
|
||||
MessageItem(
|
||||
id = "assistant-media",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Voice note\nMEDIA:$path"),
|
||||
),
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(history)
|
||||
handler.loadMessageHistory(history)
|
||||
|
||||
val attachment = handler.messages.value.single().attachments.single()
|
||||
assertEquals(1, requestCount)
|
||||
assertEquals(AttachmentState.LOADED, attachment.state)
|
||||
assertEquals("content://media/voice-note.mp3", attachment.cachedUri)
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
+63
-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())
|
||||
}
|
||||
|
||||
@@ -2025,6 +2032,61 @@ class DashboardApiClientTest {
|
||||
assertEquals("/api/messaging/whatsapp/onboarding/pair-1/apply", apply.requestUrl!!.encodedPath)
|
||||
assertTrue(apply.body.readUtf8().contains(""""profile":"worker""""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downloadManagedFile_usesUpstreamPathRouteAndPreservesMetadata() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "audio/mpeg")
|
||||
.setHeader("Content-Disposition", "attachment; filename*=UTF-8''voice%20reply.mp3")
|
||||
.setBody("audio-bytes"),
|
||||
)
|
||||
|
||||
val fetched = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.downloadManagedFile("/tmp/Hermes audio/voice reply.mp3", 1024)
|
||||
.getOrThrow()
|
||||
|
||||
assertEquals("audio/mpeg", fetched.contentType)
|
||||
assertEquals("voice reply.mp3", fetched.fileName)
|
||||
assertEquals("audio-bytes", fetched.bytes.decodeToString())
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/files/download", request.requestUrl!!.encodedPath)
|
||||
assertEquals("/tmp/Hermes audio/voice reply.mp3", request.requestUrl!!.queryParameter("path"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downloadManagedFile_rejectsDeclaredLengthAboveCallerCap() = runTest {
|
||||
server.enqueue(MockResponse().setHeader("Content-Length", 2048))
|
||||
|
||||
val result = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.downloadManagedFile("/tmp/large.bin", 1024)
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun managedFileFallbackClassificationDistinguishesMissingRouteFromMissingFile() {
|
||||
assertTrue(
|
||||
DashboardHttpException(
|
||||
404,
|
||||
"Dashboard media download failed - HTTP 404: {\"detail\":\"Not Found\"}",
|
||||
).isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(
|
||||
404,
|
||||
"Dashboard media download failed - HTTP 404: {\"detail\":\"File not found\"}",
|
||||
).isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(403, "Access to sensitive files is not allowed")
|
||||
.isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(500, "Managed file read failed")
|
||||
.isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun messagePageResponse(
|
||||
|
||||
+333
-1
@@ -227,6 +227,13 @@ class GatewayClientHarness(
|
||||
@Volatile
|
||||
var profileGetAssetPayload: JsonObject = buildJsonObject { put("found", false) }
|
||||
|
||||
@Volatile
|
||||
var usageBarsPayload: JsonObject = buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", true)
|
||||
put("plan_name", "Pro")
|
||||
}
|
||||
|
||||
/** Methods answered with JSON-RPC -32601 — exercises the legacy-name fallback. */
|
||||
val methodNotFound: MutableSet<String> = ConcurrentHashMap.newKeySet()
|
||||
|
||||
@@ -436,6 +443,7 @@ class GatewayClientHarness(
|
||||
"profiles.list" -> profilesListPayload
|
||||
"profiles.create" -> profileCreatePayload
|
||||
"profiles.get_asset" -> profileGetAssetPayload
|
||||
"usage.bars" -> usageBarsPayload
|
||||
"profiles.set_asset" -> buildJsonObject {
|
||||
put("ok", true)
|
||||
put("asset", "avatar")
|
||||
@@ -772,6 +780,7 @@ class GatewayChatClientTest {
|
||||
val moaReferences = ConcurrentLinkedQueue<GatewayMoaReference>()
|
||||
val usages = ConcurrentLinkedQueue<UsageInfo>()
|
||||
val reconcileRequests = AtomicInteger(0)
|
||||
val completions = AtomicInteger(0)
|
||||
val completeLatch = CountDownLatch(1)
|
||||
val preflightFailures = ConcurrentLinkedQueue<String>()
|
||||
|
||||
@@ -785,7 +794,7 @@ class GatewayChatClientTest {
|
||||
onToolCallFailed = { _, _ -> },
|
||||
onTurnComplete = { },
|
||||
onReconcileRequired = { reconcileRequests.incrementAndGet() },
|
||||
onComplete = { completeLatch.countDown() },
|
||||
onComplete = { completions.incrementAndGet(); completeLatch.countDown() },
|
||||
onUsage = { it?.let(usages::add) },
|
||||
onError = { errors += it; completeLatch.countDown() },
|
||||
onToolGenerating = { toolGenerating += it ?: "" },
|
||||
@@ -803,6 +812,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
callbackDispatcher: (block: () -> Unit) -> Unit = { it() },
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) = GatewayChatClient(
|
||||
@@ -824,6 +834,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
)
|
||||
|
||||
private fun awaitCondition(
|
||||
@@ -837,6 +848,21 @@ class GatewayChatClientTest {
|
||||
assertTrue("condition did not settle within ${timeoutMs}ms", condition())
|
||||
}
|
||||
|
||||
private fun exactActiveSessionPayload(
|
||||
status: String,
|
||||
liveSessionId: String = "live-1",
|
||||
storedSessionId: String = "20260612_120000_abc123",
|
||||
): JsonObject = buildJsonObject {
|
||||
put("sessions", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("id", liveSessionId)
|
||||
put("session_key", storedSessionId)
|
||||
put("status", status)
|
||||
put("last_active", 1_777_000_000.0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap in a client with shortened timeout seams. Mints a FRESH scope:
|
||||
* shutdown() cancels the scope's Job, and the replacement client must
|
||||
@@ -846,6 +872,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) {
|
||||
client.shutdown()
|
||||
@@ -854,6 +881,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
ticketTimeoutMs = ticketTimeoutMs,
|
||||
)
|
||||
}
|
||||
@@ -884,6 +912,21 @@ class GatewayChatClientTest {
|
||||
harness.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `provider usage calls official upstream usage bars method`() = runBlocking {
|
||||
harness.usageBarsPayload = buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", true)
|
||||
put("plan_name", "Pro")
|
||||
}
|
||||
|
||||
val response = client.usageBars().getOrThrow()
|
||||
|
||||
assertEquals("Pro", (response["plan_name"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("usage.bars", harness.rpcLog.last().first)
|
||||
assertTrue(harness.rpcLog.none { it.first == "account.usage" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `profile editor describes exact profile and maps upstream shape`() = runBlocking {
|
||||
val description = client.describeProfile("operator").getOrThrow()
|
||||
@@ -3445,6 +3488,42 @@ class GatewayChatClientTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session info exposes exact model callable tool catalog`() {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn("stored-1", "hi", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("session.resume")
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"session.info",
|
||||
buildJsonObject {
|
||||
put("tools", buildJsonObject {
|
||||
put("android", buildJsonArray {
|
||||
add(JsonPrimitive("android_phone_status"))
|
||||
add(JsonPrimitive("android_tap"))
|
||||
})
|
||||
put("terminal", buildJsonArray { add(JsonPrimitive("terminal")) })
|
||||
})
|
||||
},
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
waitUntil { client.serverTools.value?.size == 3 }
|
||||
assertEquals(
|
||||
setOf("android_phone_status", "android_tap", "terminal"),
|
||||
client.serverTools.value,
|
||||
)
|
||||
|
||||
client.clearSession()
|
||||
assertNull(client.serverTools.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session info without provider clears prior session identity`() {
|
||||
val recorder = Recorder()
|
||||
@@ -4710,6 +4789,180 @@ class GatewayChatClientTest {
|
||||
assertTrue(harness.ticketMints.get() >= 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle settles exact Android turn without interrupt`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn(null, "finish without terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "durable partial") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
|
||||
assertTrue(client.listActiveSessions() is GatewayActiveSessionsResult.Success)
|
||||
assertTrue("idle snapshot did not settle turn", recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertEquals(1, recorder.reconcileRequests.get())
|
||||
assertTrue(recorder.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle never settles passively observed turn`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.setUnsolicitedTurnProvider {
|
||||
GatewayInboundTurnRegistration(recorder.callbacks) { true }
|
||||
}
|
||||
assertTrue(client.prewarmAwait("stored-session"))
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload(
|
||||
status = "idle",
|
||||
liveSessionId = "live-resumed",
|
||||
storedSessionId = "stored-session",
|
||||
)
|
||||
|
||||
client.listActiveSessions()
|
||||
assertFalse(recorder.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale active session snapshot cannot settle newer turn generation`() = runBlocking {
|
||||
val first = Recorder()
|
||||
client.sendTurn(null, "first", null, first.callbacks) { first.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "first") }, "live-1"),
|
||||
)
|
||||
awaitCondition { first.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val staleSnapshot = scope.async { client.listActiveSessions() }
|
||||
val staleAck = harness.awaitPendingAck()
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "first") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(first.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
val second = Recorder()
|
||||
client.sendTurn(
|
||||
"20260612_120000_abc123",
|
||||
"second",
|
||||
null,
|
||||
second.callbacks,
|
||||
) { second.preflightFailures += it }
|
||||
harness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "second") }, "live-1"),
|
||||
)
|
||||
awaitCondition { second.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.releaseAck(staleAck, exactActiveSessionPayload("idle"))
|
||||
assertTrue(staleSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertFalse(second.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertEquals(0, second.reconcileRequests.get())
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "second") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(second.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancellation wins over delayed active session idle snapshot`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val handle = client.sendTurn(null, "cancel me", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "partial") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val delayedSnapshot = scope.async { client.listActiveSessions() }
|
||||
val delayedAck = harness.awaitPendingAck()
|
||||
handle.cancel()
|
||||
harness.awaitRpc("session.interrupt")
|
||||
harness.releaseAck(delayedAck, exactActiveSessionPayload("idle"))
|
||||
|
||||
assertTrue(delayedSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertEquals(0, recorder.completions.get())
|
||||
assertEquals(0, recorder.reconcileRequests.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late terminal after active session settle is consumed once`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val unmatched = ConcurrentLinkedQueue<GatewayBackgroundTurnCompletion>()
|
||||
client.setUnmatchedTurnCompleteListener(unmatched::add)
|
||||
client.sendTurn(null, "late terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
client.listActiveSessions()
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "done") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(150)
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertTrue(unmatched.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog does not fire while events keep arriving slowly`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 1_000L)
|
||||
@@ -4738,6 +4991,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,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user