Compare commits
244
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cd18f8607 | ||
|
|
46faddbad6 | ||
|
|
8683b84653 | ||
|
|
0d35d549f9 | ||
|
|
a6d86b0110 | ||
|
|
d8f343bf50 | ||
|
|
5408ec8d30 | ||
|
|
ba12c8354e | ||
|
|
28b4bd9d8d | ||
|
|
7bd493816f | ||
|
|
aa2c719aea | ||
|
|
a8830a37b3 | ||
|
|
66b15524f0 | ||
|
|
50afb4eed9 | ||
|
|
11787f0eab | ||
|
|
9b88ea2680 | ||
|
|
708d27e4ea | ||
|
|
cc197b1598 | ||
|
|
356f370a4f | ||
|
|
25a206ca04 | ||
|
|
92a06478cb | ||
|
|
4f25ab02e3 | ||
|
|
6324ee4fff | ||
|
|
ec7f33d337 | ||
|
|
f6ee586bc2 | ||
|
|
f1106112b8 | ||
|
|
26841fb002 | ||
|
|
926ffedee9 | ||
|
|
889c2fb316 | ||
|
|
260c21737c | ||
|
|
7036219f90 | ||
|
|
d741acab27 | ||
|
|
8d9970449c | ||
|
|
be50f9a726 | ||
|
|
f21923d39b | ||
|
|
27970d4020 | ||
|
|
94992ff37f | ||
|
|
a25de7fe31 | ||
|
|
2006d552e2 | ||
|
|
ab532d0696 | ||
|
|
66971cb0e2 | ||
|
|
9ae8de2c9d | ||
|
|
b5174d6279 | ||
|
|
7ac5a48e18 | ||
|
|
ea6cb5a6a7 | ||
|
|
d5cccd664a | ||
|
|
a48349e3cf | ||
|
|
d476704c3f | ||
|
|
f7a070ecfe | ||
|
|
37084566a0 | ||
|
|
c43f22f18d | ||
|
|
6244ab3781 | ||
|
|
9b1852a986 | ||
|
|
99f853c98e | ||
|
|
39782a5ff1 | ||
|
|
0d660c0e41 | ||
|
|
6b14ac0e0e | ||
|
|
59b5424c49 | ||
|
|
0f83af76f6 | ||
|
|
6a39e8dc1a | ||
|
|
e8473e14c8 | ||
|
|
e05018bd0b | ||
|
|
97231eb291 | ||
|
|
f7c707be03 | ||
|
|
331fad0827 | ||
|
|
f131fa08cc | ||
|
|
cbc81513bd | ||
|
|
3ad5ad8dc7 | ||
|
|
d695553c0b | ||
|
|
6b324fa822 | ||
|
|
52ee97f2b5 | ||
|
|
76bfe97c78 | ||
|
|
c8a3072704 | ||
|
|
a7612d7f05 | ||
|
|
e82ed47573 | ||
|
|
c6e4a2877d | ||
|
|
79335fea16 | ||
|
|
9c8b6c30bf | ||
|
|
4cf89df627 | ||
|
|
ad98ca9486 | ||
|
|
9d50f401ad | ||
|
|
2bc62c84e0 | ||
|
|
c3011e286c | ||
|
|
9458fea4f7 | ||
|
|
94b29c4a01 | ||
|
|
3d11cfb5f2 | ||
|
|
0f589d030f | ||
|
|
af96579e06 | ||
|
|
f0167ee00f | ||
|
|
a5798e5e6c | ||
|
|
479d788967 | ||
|
|
3f6723da6f | ||
|
|
c1cd376d8b | ||
|
|
87e2fb710d | ||
|
|
5a617f9482 | ||
|
|
13152a4fab | ||
|
|
7f31c88f46 | ||
|
|
3e857b54a2 | ||
|
|
163e3341da | ||
|
|
a5419df579 | ||
|
|
e834c603d0 | ||
|
|
a31d715569 | ||
|
|
c6b8d891ac | ||
|
|
8996f34347 | ||
|
|
f5f1a4c7d4 | ||
|
|
31eccc631e | ||
|
|
64ba979816 | ||
|
|
5be0979d74 | ||
|
|
80b1a3b6df | ||
|
|
257a11ffa2 | ||
|
|
62f3572e11 | ||
|
|
621e526c7d | ||
|
|
a5afec36d9 | ||
|
|
29bf9a08ac | ||
|
|
342e977594 | ||
|
|
24e767e7ae | ||
|
|
fdf210ec2b | ||
|
|
d05ab31296 | ||
|
|
0e0cc16f47 | ||
|
|
e90be03f2e | ||
|
|
f1e4fdcc91 | ||
|
|
5b8b3da350 | ||
|
|
447ec356d7 | ||
|
|
ab359e5efb | ||
|
|
86b8161cb7 | ||
|
|
e401fdb0c7 | ||
|
|
d4325d5aab | ||
|
|
c734d75484 | ||
|
|
0411804780 | ||
|
|
8f89c2841d | ||
|
|
933c1842a0 | ||
|
|
dfe1b53327 | ||
|
|
d36580a983 | ||
|
|
2d178ff884 | ||
|
|
d61955f82a | ||
|
|
adec6ed2c0 | ||
|
|
e9e44c8bb2 | ||
|
|
c6b0732a02 | ||
|
|
d919115788 | ||
|
|
49da085ae8 | ||
|
|
889b6f0858 | ||
|
|
5100c524f6 | ||
|
|
c609ae867f | ||
|
|
107f8c7720 | ||
|
|
8963e4fafd | ||
|
|
5d9624e2ef | ||
|
|
4b063d3fd7 | ||
|
|
9b9d7b654c | ||
|
|
a26e17e72c | ||
|
|
a3a6a9bb13 | ||
|
|
169bd09559 | ||
|
|
45d631e7ac | ||
|
|
eb6a6c95d2 | ||
|
|
3b102663c2 | ||
|
|
0e5fc4c606 | ||
|
|
c3189f2cbb | ||
|
|
0d6c3bd6b0 | ||
|
|
06d88ad40a | ||
|
|
8ae5b3fbc2 | ||
|
|
39b7a8f108 | ||
|
|
af6e167692 | ||
|
|
274bd6ae98 | ||
|
|
9fc55b379a | ||
|
|
559a0ffdc8 | ||
|
|
75bcd9180f | ||
|
|
9c995a443d | ||
|
|
7440ef2948 | ||
|
|
a88539bc59 | ||
|
|
b2ccfdc500 | ||
|
|
481c62ac59 | ||
|
|
5d415fbaf0 | ||
|
|
074b715055 | ||
|
|
f63ee8721e | ||
|
|
777bc80bcc | ||
|
|
9539975bb5 | ||
|
|
2863a1bc8f | ||
|
|
b0a7cf0494 | ||
|
|
76b4084310 | ||
|
|
2ace70c4fc | ||
|
|
4f52f371ba | ||
|
|
064c89bda4 | ||
|
|
0cb1e3642f | ||
|
|
cf4bf87242 | ||
|
|
9cbed21014 | ||
|
|
ce75c0fa01 | ||
|
|
bf2aece6e6 | ||
|
|
198da78fc8 | ||
|
|
986ce3b12b | ||
|
|
b53f757830 | ||
|
|
cdeccd69e4 | ||
|
|
bb72516bb5 | ||
|
|
3a51644342 | ||
|
|
51c0c7dee9 | ||
|
|
7ef2420c85 | ||
|
|
6a810c850b | ||
|
|
d383002583 | ||
|
|
e3aae829e1 | ||
|
|
5207ed4193 | ||
|
|
b46bb00ea8 | ||
|
|
b8dde409c5 | ||
|
|
ca7ded3939 | ||
|
|
db85a26c68 | ||
|
|
aa2595629d | ||
|
|
d79146dc90 | ||
|
|
eabc4dd328 | ||
|
|
e165bfeff3 | ||
|
|
40bcd796d1 | ||
|
|
57ae0c9456 | ||
|
|
9b31a16c89 | ||
|
|
f97bbdd395 | ||
|
|
722a294947 | ||
|
|
bbfb57b462 | ||
|
|
6db12a0bec | ||
|
|
f1de957848 | ||
|
|
cc01d9c8ad | ||
|
|
d574182d84 | ||
|
|
a328763da3 | ||
|
|
f53db68e7d | ||
|
|
eb9e570fc0 | ||
|
|
260f119637 | ||
|
|
d0fa2ea39d | ||
|
|
a1c74b1567 | ||
|
|
7c45acd38d | ||
|
|
4605b87c10 | ||
|
|
6a91d6ee7e | ||
|
|
95a2813efe | ||
|
|
2ecf521c8c | ||
|
|
7752c5c404 | ||
|
|
e1d3764cd2 | ||
|
|
e34171b5ad | ||
|
|
8040cac39a | ||
|
|
aab70520ca | ||
|
|
5a0cd8123c | ||
|
|
4370d9a925 | ||
|
|
726308d2ef | ||
|
|
1acc3a4c80 | ||
|
|
11ccbd6e5c | ||
|
|
d13af35357 | ||
|
|
e3752d43f3 | ||
|
|
97293b62c3 | ||
|
|
454e770648 | ||
|
|
e18572e8e3 | ||
|
|
de9211b7c5 | ||
|
|
7ca5c61be5 |
@@ -67,7 +67,7 @@ jobs:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
run: npm run build
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
working-directory: website
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
version_code: ${{ steps.version.outputs.version_code }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
@@ -56,8 +57,14 @@ jobs:
|
||||
REF_VERSION="${GITHUB_REF#refs/tags/android-v}"
|
||||
fi
|
||||
VERSION_CODE=$(grep -oP 'appVersionCode\s*=\s*"\K[^"]+' gradle/libs.versions.toml)
|
||||
if [[ "$REF_VERSION" == *-* ]]; then
|
||||
PRERELEASE=true
|
||||
else
|
||||
PRERELEASE=false
|
||||
fi
|
||||
echo "version=$REF_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify version sync
|
||||
run: |
|
||||
@@ -81,14 +88,24 @@ jobs:
|
||||
- name: Verify public privacy policy URLs
|
||||
run: python3 scripts/check-privacy-policy.py --live
|
||||
|
||||
- name: Verify tagged commit belongs to main
|
||||
- name: Verify tag belongs to the correct integration branch
|
||||
env:
|
||||
PRERELEASE: ${{ steps.version.outputs.prerelease }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin main --no-tags
|
||||
tag_commit="$(git rev-parse HEAD)"
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Android releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
if [ "$PRERELEASE" = "true" ]; then
|
||||
git fetch origin dev --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
||||
echo "Android prereleases must be tagged from dev; $tag_commit is not in origin/dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
git fetch origin main --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Stable Android releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Require successful Play preflight for this exact release tree
|
||||
@@ -175,7 +192,8 @@ jobs:
|
||||
echo "$HERMES_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
|
||||
echo "HERMES_KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build release artifacts (APK + AAB)
|
||||
- name: Build stable release artifacts (APK + AAB)
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
env:
|
||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||
@@ -191,10 +209,27 @@ jobs:
|
||||
# app/build/outputs/bundle/sideloadRelease/hermes-relay-<version>-sideload-release.aab
|
||||
run: ./gradlew bundleRelease assembleRelease
|
||||
|
||||
- name: Build side-by-side release candidate APK
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
env:
|
||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
SOURCE_SHA="$(git rev-parse HEAD)"
|
||||
./gradlew :app:assembleSideloadCandidate \
|
||||
-Pcandidate.kind=rc \
|
||||
-Pcandidate.label="Android ${VERSION}" \
|
||||
-Pcandidate.sourceRef="android-v${VERSION}" \
|
||||
-Pcandidate.sourceSha="$SOURCE_SHA" \
|
||||
--console=plain
|
||||
|
||||
# The Play AAB carries its mapping for Play Console deobfuscation, but
|
||||
# sideload issue reports need the exact mapping from this immutable build.
|
||||
# Keep both variants as a workflow artifact (not a public release asset).
|
||||
- name: Retain R8 mappings for retrace
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ github.sha }}
|
||||
@@ -204,12 +239,28 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
- name: Scan release DEX for unsupported collection APIs
|
||||
- name: Retain candidate R8 mapping for retrace
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: android-rc-r8-mapping-${{ needs.validate.outputs.version }}-${{ github.sha }}
|
||||
path: app/build/outputs/mapping/sideloadCandidate/mapping.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
- name: Scan stable release DEX for unsupported collection APIs
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
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: Scan candidate DEX for unsupported collection APIs
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
run: |
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
--apk app/build/outputs/apk/sideload/candidate/*.apk
|
||||
|
||||
- name: List produced artifacts (debug aid)
|
||||
run: |
|
||||
echo "=== APK outputs ==="
|
||||
@@ -217,7 +268,8 @@ jobs:
|
||||
echo "=== AAB outputs ==="
|
||||
find app/build/outputs/bundle -name '*.aab' -print 2>/dev/null || true
|
||||
|
||||
- name: Generate checksums
|
||||
- name: Generate stable checksums
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
# Flavor dimension adds an extra path segment to the AGP output layout.
|
||||
# APKs live under `apk/<flavor>/release/`, AABs under `bundle/<flavor>Release/`
|
||||
# (note the concatenated camelCase — AGP path quirk, documented but
|
||||
@@ -229,6 +281,13 @@ jobs:
|
||||
sha256sum apk/sideload/release/*.apk bundle/googlePlayRelease/*.aab > SHA256SUMS.txt
|
||||
cat SHA256SUMS.txt
|
||||
|
||||
- name: Generate candidate checksums
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
run: |
|
||||
cd app/build/outputs
|
||||
sha256sum apk/sideload/candidate/*.apk > SHA256SUMS.txt
|
||||
cat SHA256SUMS.txt
|
||||
|
||||
- name: Require Play credentials for stable release
|
||||
env:
|
||||
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||
@@ -255,13 +314,14 @@ jobs:
|
||||
# Public distribution happens only after Play accepts the production
|
||||
# submission above. This keeps a Play-detected release blocker from
|
||||
# appearing after the sideload APK is already public.
|
||||
- name: Create GitHub Release
|
||||
- name: Create stable GitHub Release
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Hermes-Relay-Android v${{ needs.validate.outputs.version }}
|
||||
tag_name: android-v${{ needs.validate.outputs.version }}
|
||||
body_path: RELEASE_NOTES.md
|
||||
prerelease: ${{ contains(needs.validate.outputs.version, '-') }}
|
||||
prerelease: false
|
||||
# Deliberate 2-asset policy (#144): attach ONLY the installable
|
||||
# sideload APK and Play AAB, plus checksums covering those files.
|
||||
files: |
|
||||
@@ -269,13 +329,31 @@ jobs:
|
||||
app/build/outputs/bundle/googlePlayRelease/*.aab
|
||||
app/build/outputs/SHA256SUMS.txt
|
||||
|
||||
- name: Create candidate GitHub prerelease
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Hermes-Relay-Android v${{ needs.validate.outputs.version }}
|
||||
tag_name: android-v${{ needs.validate.outputs.version }}
|
||||
body_path: RELEASE_NOTES.md
|
||||
prerelease: true
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
app/build/outputs/apk/sideload/candidate/*.apk
|
||||
app/build/outputs/SHA256SUMS.txt
|
||||
|
||||
- name: Release summary
|
||||
env:
|
||||
HERMES_KEYSTORE_BASE64: ${{ secrets.HERMES_KEYSTORE_BASE64 }}
|
||||
PRERELEASE: ${{ needs.validate.outputs.prerelease }}
|
||||
run: |
|
||||
echo "## Hermes-Relay-Android v${{ needs.validate.outputs.version }}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
if [ "$PRERELEASE" = "true" ] && [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Release-signed Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ "$PRERELEASE" = "true" ]; then
|
||||
echo "⚠️ **Debug-signed Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Signed with release keystore** — suitable for Play Store upload" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "⚠️ **Debug-signed** (no \`HERMES_KEYSTORE_BASE64\` secret) — NOT suitable for Play Store. Add the secret in repo settings to enable release signing." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
@@ -48,16 +48,25 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify tagged commit belongs to main
|
||||
- name: Verify tag belongs to the correct integration branch
|
||||
shell: bash
|
||||
working-directory: .
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin main --no-tags
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
tag_commit="$(git rev-parse "${GITHUB_REF_NAME}^{commit}")"
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Desktop releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
if [[ "$version" == *-* ]]; then
|
||||
git fetch origin dev --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
||||
echo "Desktop prereleases must be tagged from dev; $tag_commit is not in origin/dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
git fetch origin main --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Stable Desktop releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
build-cli-binaries:
|
||||
@@ -80,7 +89,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: '1.3.x'
|
||||
bun-version-file: 'desktop/.bun-version'
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci
|
||||
@@ -153,6 +162,40 @@ jobs:
|
||||
desktop/dist/bin/hermes-relay-darwin-arm64
|
||||
retention-days: 7
|
||||
|
||||
smoke-windows-cli-release-asset:
|
||||
name: Smoke exact Windows CLI release asset
|
||||
runs-on: windows-latest
|
||||
needs:
|
||||
- validate-release
|
||||
- build-cli-binaries
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: cli-binaries
|
||||
path: release-assets
|
||||
|
||||
- name: Repeated launch and process cleanup gate
|
||||
shell: pwsh
|
||||
env:
|
||||
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$exe = (Resolve-Path 'release-assets/hermes-relay-win-x64.exe').Path
|
||||
1..20 | ForEach-Object {
|
||||
$output = & $exe --version
|
||||
if ($LASTEXITCODE -ne 0) { throw "Windows CLI smoke failed with exit $LASTEXITCODE" }
|
||||
if ($output -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
||||
throw "Unexpected Windows CLI version output: $output"
|
||||
}
|
||||
}
|
||||
Start-Sleep -Milliseconds 500
|
||||
$leftovers = Get-CimInstance Win32_Process | Where-Object {
|
||||
$_.ExecutablePath -eq $exe
|
||||
}
|
||||
if ($leftovers) {
|
||||
throw "Windows CLI smoke left $(@($leftovers).Count) process(es) behind"
|
||||
}
|
||||
|
||||
build-windows-tray-installer:
|
||||
name: Build Windows tray installer
|
||||
runs-on: windows-latest
|
||||
@@ -175,7 +218,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: '1.3.x'
|
||||
bun-version-file: 'desktop/.bun-version'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
@@ -231,6 +274,20 @@ jobs:
|
||||
return (@($Value -split ';' | Where-Object { $_ }) -join ';')
|
||||
}
|
||||
|
||||
function Get-RawUserPath {
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
|
||||
if ($null -eq $environmentKey) { return '' }
|
||||
try {
|
||||
return [string]$environmentKey.GetValue(
|
||||
'Path',
|
||||
'',
|
||||
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
|
||||
)
|
||||
} finally {
|
||||
$environmentKey.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$setup = (Resolve-Path 'dist/tray/hermes-relay-windows-x64-setup.exe').Path
|
||||
$smokeRoot = Join-Path $env:RUNNER_TEMP 'hermes-installer-lifecycle-smoke'
|
||||
$smokeProfile = Join-Path $smokeRoot 'profile'
|
||||
@@ -244,7 +301,12 @@ jobs:
|
||||
$startMenuDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Hermes-Relay CLI'
|
||||
$oldUserProfile = $env:USERPROFILE
|
||||
$oldHomeEnv = $env:HOME
|
||||
$userPathBefore = Normalize-UserPath ([Environment]::GetEnvironmentVariable('Path', 'User'))
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$hadUserPath = $environmentKey.GetValueNames() -contains 'Path'
|
||||
$originalUserPath = Get-RawUserPath
|
||||
$originalUserPathKind = if ($hadUserPath) { $environmentKey.GetValueKind('Path') } else { $null }
|
||||
$userPathBefore = 'C:\Windows\System32'
|
||||
$environmentKey.Dispose()
|
||||
$startupBefore = (Get-ItemProperty -Path $startupKey -Name HermesRelayTray -ErrorAction SilentlyContinue).HermesRelayTray
|
||||
|
||||
if (Test-Path $uninstallKey) { throw 'installer smoke requires a clean HermesRelay uninstall registry key' }
|
||||
@@ -256,6 +318,10 @@ jobs:
|
||||
$env:USERPROFILE = $smokeProfile
|
||||
$env:HOME = $smokeProfile
|
||||
try {
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$environmentKey.SetValue('Path', $userPathBefore, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$environmentKey.Dispose()
|
||||
|
||||
$installProcess = Start-Process -FilePath $setup -ArgumentList @('/S', "/D=$installDir") -Wait -PassThru
|
||||
if ($installProcess.ExitCode -ne 0) { throw "installer exited with code $($installProcess.ExitCode)" }
|
||||
|
||||
@@ -308,11 +374,9 @@ jobs:
|
||||
throw 'installer lifecycle modified preserved profile session data'
|
||||
}
|
||||
|
||||
# User PATH may contain expandable %USERPROFILE% entries. Restore the
|
||||
# runner profile before comparing the unchanged registry value.
|
||||
$env:USERPROFILE = $oldUserProfile
|
||||
$env:HOME = $oldHomeEnv
|
||||
$userPathAfter = Normalize-UserPath ([Environment]::GetEnvironmentVariable('Path', 'User'))
|
||||
# Compare the raw registry value so expandable entries such as
|
||||
# %USERPROFILE% are not resolved against the isolated smoke profile.
|
||||
$userPathAfter = Normalize-UserPath (Get-RawUserPath)
|
||||
if ($userPathAfter -ne $userPathBefore) {
|
||||
throw "uninstaller did not restore user PATH (before='$userPathBefore', after='$userPathAfter')"
|
||||
}
|
||||
@@ -330,6 +394,13 @@ jobs:
|
||||
}
|
||||
$env:USERPROFILE = $oldUserProfile
|
||||
$env:HOME = $oldHomeEnv
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
if ($hadUserPath) {
|
||||
$environmentKey.SetValue('Path', $originalUserPath, $originalUserPathKind)
|
||||
} else {
|
||||
$environmentKey.DeleteValue('Path', $false)
|
||||
}
|
||||
$environmentKey.Dispose()
|
||||
if (Test-Path -LiteralPath $smokeRoot) {
|
||||
Remove-Item -LiteralPath $smokeRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
@@ -347,6 +418,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build-cli-binaries
|
||||
- smoke-windows-cli-release-asset
|
||||
- build-windows-tray-installer
|
||||
steps:
|
||||
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
|
||||
|
||||
@@ -27,21 +27,31 @@ jobs:
|
||||
- name: Verify Server version sync and changelog
|
||||
run: |
|
||||
python scripts/check-plugin-version-sync.py --expect "$TAG_VERSION"
|
||||
if ! grep -Fq "## [$TAG_VERSION]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no release heading for $TAG_VERSION"
|
||||
if ! grep -Eq "^## \[Server ${TAG_VERSION}\]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no Server release heading for $TAG_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
env:
|
||||
TAG_VERSION: ${{ steps.version.outputs.version }}
|
||||
|
||||
- name: Verify tagged commit belongs to main
|
||||
- name: Verify tag belongs to the correct integration branch
|
||||
env:
|
||||
TAG_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin main --no-tags
|
||||
tag_commit="$(git rev-parse HEAD)"
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Server releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
if [[ "$TAG_VERSION" == *-* ]]; then
|
||||
git fetch origin dev --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
||||
echo "Server prereleases must be tagged from dev; $tag_commit is not in origin/dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
git fetch origin main --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
|
||||
echo "Stable Server releases must be tagged from main; $tag_commit is not in origin/main" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
test:
|
||||
@@ -53,7 +63,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
@@ -77,7 +87,9 @@ jobs:
|
||||
python -m pytest \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py
|
||||
plugin/tests/test_session_grants.py \
|
||||
plugin/tests/test_proactive_channel.py \
|
||||
plugin/tests/test_android_phone_status.py
|
||||
|
||||
package:
|
||||
name: Build and publish Plugin package
|
||||
@@ -88,7 +100,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v6
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
name: Build Review Bundle
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- dev
|
||||
types:
|
||||
- labeled
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: review-bundle-pr-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
if: ${{ github.event.label.name == 'review-candidate' }}
|
||||
name: Resolve exact source
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
repository: ${{ steps.source.outputs.repository }}
|
||||
sha: ${{ steps.source.outputs.sha }}
|
||||
short_sha: ${{ steps.source.outputs.short_sha }}
|
||||
label: ${{ steps.source.outputs.label }}
|
||||
artifact_slug: ${{ steps.source.outputs.artifact_slug }}
|
||||
source_kind: ${{ steps.source.outputs.source_kind }}
|
||||
source_value: ${{ steps.source.outputs.source_value }}
|
||||
steps:
|
||||
- name: Resolve pull request or exact SHA
|
||||
id: source
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const kind = "pull_request";
|
||||
const source = process.env.PR_NUMBER;
|
||||
const repository = process.env.PR_HEAD_REPOSITORY;
|
||||
const sha = process.env.PR_HEAD_SHA;
|
||||
if (!repository || !sha) {
|
||||
core.setFailed("the PR head repository is no longer available");
|
||||
return;
|
||||
}
|
||||
const label = `PR #${source}`;
|
||||
const slug = `pr-${source}`;
|
||||
|
||||
core.setOutput("repository", repository);
|
||||
core.setOutput("sha", sha);
|
||||
core.setOutput("short_sha", sha.slice(0, 12));
|
||||
core.setOutput("label", label);
|
||||
core.setOutput("artifact_slug", slug);
|
||||
core.setOutput("source_kind", kind);
|
||||
core.setOutput("source_value", source);
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
PR_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
|
||||
build:
|
||||
name: Build matched Android + Relay bundle
|
||||
needs: resolve
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: Checkout exact review source
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: ${{ needs.resolve.outputs.repository }}
|
||||
ref: ${{ needs.resolve.outputs.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Verify immutable source
|
||||
env:
|
||||
EXPECTED_SHA: ${{ needs.resolve.outputs.sha }}
|
||||
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: true
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
- name: Build side-by-side candidate APK
|
||||
env:
|
||||
SOURCE_LABEL: ${{ needs.resolve.outputs.label }}
|
||||
SOURCE_REF: ${{ needs.resolve.outputs.source_kind }}:${{ needs.resolve.outputs.source_value }}
|
||||
SOURCE_SHA: ${{ needs.resolve.outputs.sha }}
|
||||
run: |
|
||||
./gradlew :app:assembleSideloadCandidate \
|
||||
-Pcandidate.kind=review \
|
||||
-Pcandidate.label="$SOURCE_LABEL" \
|
||||
-Pcandidate.sourceRef="$SOURCE_REF" \
|
||||
-Pcandidate.sourceSha="$SOURCE_SHA" \
|
||||
--console=plain
|
||||
|
||||
- name: Build Relay packages
|
||||
run: |
|
||||
python -m pip install build
|
||||
python -m build
|
||||
|
||||
- name: Verify candidate application identity
|
||||
run: |
|
||||
apk="$(find app/build/outputs/apk/sideload/candidate -name '*.apk' -print -quit)"
|
||||
test -n "$apk"
|
||||
aapt="$(find "$ANDROID_HOME/build-tools" -type f -name aapt -print | sort -V | tail -1)"
|
||||
test -x "$aapt"
|
||||
"$aapt" dump badging "$apk" | grep -F "package: name='com.axiomlabs.hermesrelay.sideload.candidate'"
|
||||
"$aapt" dump badging "$apk" | grep -F "application-label:'Hermes Candidate'"
|
||||
|
||||
- name: Assemble review bundle
|
||||
env:
|
||||
SOURCE_KIND: ${{ needs.resolve.outputs.source_kind }}
|
||||
SOURCE_VALUE: ${{ needs.resolve.outputs.source_value }}
|
||||
SOURCE_REPOSITORY: ${{ needs.resolve.outputs.repository }}
|
||||
SOURCE_SHA: ${{ needs.resolve.outputs.sha }}
|
||||
SOURCE_LABEL: ${{ needs.resolve.outputs.label }}
|
||||
SHORT_SHA: ${{ needs.resolve.outputs.short_sha }}
|
||||
run: |
|
||||
mkdir -p review-bundle/android review-bundle/relay
|
||||
cp app/build/outputs/apk/sideload/candidate/*.apk review-bundle/android/
|
||||
cp dist/*.whl dist/*.tar.gz review-bundle/relay/
|
||||
git archive \
|
||||
--format=tar.gz \
|
||||
--output="review-bundle/relay/hermes-relay-source-${SHORT_SHA}.tar.gz" \
|
||||
HEAD plugin pyproject.toml relay_server
|
||||
cp docs/review-candidates.md review-bundle/INSTALL.md
|
||||
python - <<'PY'
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
manifest = {
|
||||
"schema_version": 1,
|
||||
"kind": "review",
|
||||
"label": os.environ["SOURCE_LABEL"],
|
||||
"source": {
|
||||
"kind": os.environ["SOURCE_KIND"],
|
||||
"value": os.environ["SOURCE_VALUE"],
|
||||
"repository": os.environ["SOURCE_REPOSITORY"],
|
||||
"sha": os.environ["SOURCE_SHA"],
|
||||
},
|
||||
"android": {
|
||||
"application_id": "com.axiomlabs.hermesrelay.sideload.candidate",
|
||||
"stable_install_affected": False,
|
||||
},
|
||||
"relay": {
|
||||
"side_by_side_in_same_hermes_process": False,
|
||||
"staging_or_snapshot_rollback_required": True,
|
||||
},
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
Path("review-bundle/REVIEW_MANIFEST.json").write_text(
|
||||
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
PY
|
||||
cd review-bundle
|
||||
find android relay -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS.txt
|
||||
|
||||
- name: Upload matched review bundle
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: hermes-relay-review-${{ needs.resolve.outputs.artifact_slug }}-${{ needs.resolve.outputs.short_sha }}
|
||||
path: review-bundle/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
- name: Review summary
|
||||
env:
|
||||
SOURCE_LABEL: ${{ needs.resolve.outputs.label }}
|
||||
SOURCE_SHA: ${{ needs.resolve.outputs.sha }}
|
||||
run: |
|
||||
echo "## Hermes-Relay review bundle" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Source: **$SOURCE_LABEL**" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Commit: \`$SOURCE_SHA\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Android package: \`com.axiomlabs.hermesrelay.sideload.candidate\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Stable Android installs are not replaced." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Relay review requires a staging Hermes instance or an explicit snapshot/rollback window." >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -12,6 +12,7 @@ not redefine the branch, release, or hotfix policy 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_*` 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)
|
||||
|
||||
@@ -21,7 +22,8 @@ not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
|
||||
|---|---|
|
||||
| Integration branch | `dev`; normal feature, fix, docs, and chore PRs target `dev` |
|
||||
| Release branch | `main`; release history and hotfix integration only |
|
||||
| Tag source | The new `main` tip after an approved `dev` → `main` release PR, or after an approved hotfix PR to `main` |
|
||||
| Production tag source | The new `main` tip after an approved `dev` → `main` release PR, or after an approved hotfix PR to `main` |
|
||||
| Candidate tag source | An exact release-prepared and tested `dev` SHA; prerelease suffix required (`-alpha`, `-beta`, or `-rc.N`) |
|
||||
| Staging source | An exact tested `dev` SHA or release-candidate tag; staging is an environment, never a branch |
|
||||
| Production source | Immutable `android-v*`, `server-v*`, or `desktop-v*` tags, selected by surface |
|
||||
| Hotfix base | The immutable production tag for the affected surface |
|
||||
@@ -44,6 +46,15 @@ a staging branch.
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
`tui_gateway/server.py` in hermes-agent) before assuming a route exists.
|
||||
- **Use the Gateway contract lab when its boundary changes.** Changes to
|
||||
Gateway chat events, session identity/resume/activation, streaming completion,
|
||||
queue ownership, reconnect/lifecycle recovery, or authoritative history must
|
||||
reuse or extend the declarative fixture scenarios, run the relevant Android
|
||||
instrumentation when rendered/lifecycle behavior is affected, and run the
|
||||
scenario manifest through current-upstream conformance. Physical ADB
|
||||
certification is required only when device/runtime behavior is claimed. All
|
||||
of these lanes are on demand; do not add scheduled execution without explicit
|
||||
approval.
|
||||
- **Conventional Commits + `main`/`dev` branching.** Normal branches start at
|
||||
`dev` and PR back to `dev`; merge commits/no-ff are the repository policy.
|
||||
Version bumps happen only during release preparation on `dev`, and production
|
||||
|
||||
+220
-1
@@ -6,6 +6,225 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [Android 1.12.0] - 2026-08-21
|
||||
|
||||
### Added
|
||||
|
||||
- **Android can create and save custom themes.** The Custom workshop provides a live chat preview, editable Background, Surface, Accent, and Text roles, Light or Dark ownership, saved Soft/Balanced/Sharp shape, and bounded rename, duplicate, and delete actions. Up to 20 presets remain local to the device.
|
||||
- **Maintainers can build matched Android and Relay review candidates without cutting a release.** Candidate artifacts share exact source provenance and checksums, install beside stable builds with isolated data, and remain excluded from stable update prompts.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Appearance shape now applies consistently across the app.** Soft, Balanced, and Sharp styling reaches chat, settings, sheets, dialogs, terminal, voice, Bridge, and other shared surfaces, while accent and shape changes apply immediately. (#385)
|
||||
- **Selecting an All Profiles session now activates its owning agent.** Header identity, avatar, transcript, drafts, routing, and persistence move together. Merely browsing All Profiles changes nothing, and a profile lock hides All Profiles and rejects cross-profile opens.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Language changes preserve the active profile and session.** Activity recreation retains the exact connection, agent, session, and All Profiles browser state without replacing them with stale persisted values. The persistent connection notification also relocalizes without reconnecting. (#381)
|
||||
- **Gateway chats recover when a terminal frame is missed.** An authoritative idle state settles the active turn, retains its durable session, and reconciles history without resubmitting through fallback transport. (#365)
|
||||
- **Relay endpoint forms normalize to the correct sibling routes.** Saved base, `/ws`, and `/health` URLs resolve idempotently without producing paths such as `/relay/ws/health`; malformed or ambiguous routes still fail closed. (#380)
|
||||
|
||||
## [Server 1.9.0] - 2026-08-21
|
||||
|
||||
### Added
|
||||
|
||||
- **Reconnect-delivered phone messages carry explicit backlog context.** Relay marks messages flushed from its bounded offline queue and emits one ordered completion event so compatible clients can label delayed messages and summarize the batch without generating one banner per item.
|
||||
- **Phone status reports granular Bridge capability grants.** Human-readable status and the `android_phone_status` tool distinguish permanent, timed, and unlimited capabilities while retaining the existing Android permission and safety state.
|
||||
|
||||
## [1.11.0] - 2026-08-20
|
||||
|
||||
### Added
|
||||
|
||||
- **Sideload Bridge access is explicitly capability-scoped.** Read-only, read-and-confirm, and custom presets grant only selected powers for the active connection. Screen inspection and control can be allowed for a bounded period or explicitly left unlimited, and Relay status reports the resulting permanent, timed, and unlimited grants.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The sideload Bridge screen is a summary-first access cockpit.** Agent access, unattended mode, selected Android requirements, and advanced safety controls are separated clearly while the complete permission matrix and power-user controls remain available one tap deeper.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android keeps failed session resumes visible and in context.** Continuing a stored Gateway session no longer falls through to a fresh session when Hermes rejects or mis-scopes the resume. Failed turns remain error-marked and expose a composer-adjacent recovery panel with route-aware details, explicit retry/dismiss actions, and sanitized Diagnostics evidence.
|
||||
- **Software-keyboard Return inserts a newline across both common Android IME paths.** Keyboards that commit text directly and keyboards that synthesize `KEYCODE_ENTER` now keep multiline composition separate from physical-keyboard Send behavior. (#367)
|
||||
- **Cancelled answer recovery retains its Stopped status.** Empty recovery placeholders with a persistent status badge are no longer discarded during stream finalization.
|
||||
- **Android screen-on idle no longer continuously redraws the ASCII sphere.** Idle holds a stable frame while thinking, streaming, and voice states retain full-rate motion; inactive voice waveforms and closed session drawers also stop their frame loops.
|
||||
- **Android capture and audio effects release power-sensitive resources at their actual lifecycle boundaries.** Screen capture attaches its MediaProjection surface only for a requested frame, unattended Bridge wake locks release when the command finishes, and barge-in AEC/noise suppression attach to the microphone capture session instead of playback.
|
||||
- **Experimental wake-word listening reuses its PCM normalization buffer.** Continuous opt-in listening no longer allocates a new float frame for every inference call.
|
||||
|
||||
## [1.10.0] - 2026-08-18
|
||||
|
||||
### Added
|
||||
|
||||
- **Android preserves composer drafts across app restarts.** Text, quote/edit context, and pending attachments remain scoped to their exact connection, profile, and session in bounded app-private no-backup storage, and successful sends remove the saved draft.
|
||||
- **Android can turn large pastes into reviewable text attachments.** The default-on Chat setting converts inserts of at least 5,000 characters into a compact attachment while preserving surrounding text; Gateway uploads the file through upstream Hermes and fallback transports retain the pasted content as text.
|
||||
- **Android renders Markdown incrementally while replies stream.** The native streaming parser retains stable message, selection, and AST identities from the first token through completion, including provisional paragraphs, lists, links, fenced code, and tables.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The Android software keyboard exposes Return in the multiline composer.** The dedicated composer button sends, while physical Enter, Shift+Enter, and caret-arrow behavior remain unchanged. (#367)
|
||||
- **Open chats reattach after Android returns to the foreground.** Gateway reconnect restores the visible session subscription and reconciles missed work without requiring the user to leave and reopen the conversation. (#365)
|
||||
- **Imported credentials fail closed before network or secure-state mutation.** Control characters and malformed values are rejected before header construction or encrypted-state replacement without logging credential material.
|
||||
- **Streaming follow remains stable through completion.** Deliberate scrollback stays untouched, bottom-follow uses one bounded owner, and Markdown, voice actions, timestamps, and token metadata settle without rebuilding the bubble or resetting its scroll anchor. (#341)
|
||||
|
||||
## [1.9.1] - 2026-08-16
|
||||
|
||||
### Added
|
||||
|
||||
- **Android adopts Hermes-owned profile creation, shared avatars, and animated pets.** Current Gateways provide the profile roster, explicit shared/copied/isolated authentication choices, partial create outcomes, validated avatar upload/fetch/clear, and profile-scoped pet selection that follows the agent across supported Hermes clients. Older hosts retain authenticated Dashboard creation plus Relay/local presentation fallbacks, and profile deletion remains Dashboard-only.
|
||||
- **Android identifies proactive messages delivered after reconnect.** Relay marks messages flushed from its bounded offline queue, Thread bubbles label them as received “While away,” and Android shows one accessible localized summary for the completed batch.
|
||||
- **Android can create finite recurring schedules from Manage.** The native editor uses the authenticated Hermes Gateway `cron.manage` contract, optionally stops after 1–999 runs, and rejects invalid counts rather than silently creating unlimited work.
|
||||
- **Chat resets retain content-free local evidence.** New-chat and Thread transitions save a bounded app-private checkpoint for user-reviewed Diagnostics without prompts, message text, IDs, profile names, paths, URLs, media, tool payloads, secrets, or telemetry.
|
||||
- **Android surfaces host resource risk before chat state is lost.** Current Hermes Dashboard memory and disk pressure signals render as a persistent, capability-gated warning; older hosts remain unchanged and no telemetry is added.
|
||||
- **Android honors Hermes model-selection safeguards.** Every Gateway model transition, including fresh-chat and Server-default choices, now avoids raw session overrides; picks requiring cost or data-training consent show Hermes' exact warning and apply only after a confirmed second request.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Profile identity sources are explicit in Agent Passport.** Server-owned static avatars and upstream pets follow the Hermes profile, while phone picks, Relay-host imports, phone-only animated icons, and Sphere skins remain separate local presentation choices.
|
||||
- **Interactive Gateway asks remain resolver-bound.** Android continues to use upstream clarify, approval, sudo, and secret response RPCs; connector-only prompt/reaction operations are not copied into Relay cards as a second approval protocol.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Shared avatar picks now persist from Android's filesystem picker.** The app accepts any image Android can decode, applies display orientation, and safely resizes or re-encodes it to the upstream PNG/JPEG/WebP and 2,000,000-byte contract. Successful writes update the local shared cache immediately, and upload failures remain visible beside the control.
|
||||
|
||||
- **Nous-hosted Android sign-in follows the official native broker contract.** The gateway now selects its native provider exactly as Hermes Desktop does, callback attempts retain the upstream five-minute window, and post-callback failures explain whether the one-time code, hosted gateway, network, response, or secure storage prevented session creation without exposing auth material.
|
||||
- **Android edit-and-regenerate fails closed on incomplete durable history.** Mixed Gateway transcripts now require the selected message's durable row identity instead of attempting an ordinal-only rewind, while older Hermes histories with no row identities remain editable.
|
||||
- **Android fails closed when a Gateway does not confirm the selected profile.** Named-profile session creation and recovery now require Hermes to echo the exact owning profile, preventing stale or older gateways from silently running the launch profile under another agent's identity. Profile inspection also keeps read-only Gateway data available when `profiles.configure` is unsupported while disabling further write attempts without discarding drafts.
|
||||
- **Android attachment sends are bounded and fail closed.** Picked files are size-limited while streaming into the encoder, cold and queued Gateway sends upload only after the exact session is ready, and an unsupported or interrupted document upload no longer falls through to a text-only route while its file card implies delivery. Every attachment type retains the same compact collapse/expand affordance.
|
||||
|
||||
## [0.4.0-beta.4] - 2026-08-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The Windows management UI remains available while the daemon is stopped.** Missing, stale, malformed, or temporarily unavailable daemon status now resolves to an explicit stopped state instead of trapping the tray on its loading screen, so configuration, diagnostics, host management, and daemon controls remain accessible.
|
||||
|
||||
## [1.9.0] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Android session browsing matches Hermes Desktop's recent organization model.** The primary session drawer can toggle between the active profile and all profiles, group by recency, project, status, or profile, order by supported session metrics, and narrow rows by status, project, profile, or pull-request state without collapsing duplicate IDs across profile stores. Named profiles receive stable identity-color badges with locally persisted color overrides.
|
||||
- **Android can edit current Hermes profiles through the standard Gateway.** The Profile Inspector capability-gates `profiles.describe` and `profiles.configure`, keeps Relay-only memory editing and older-Hermes fallback intact, and reports partial section saves without discarding failed drafts.
|
||||
- **Android sessions show their coding context when Hermes supplies it.** Session rows can display repository, Git branch, and the current state of the pull request created by that session while older hosts remain unchanged.
|
||||
- Android Manage can now finish host-owned backup workflows, edit or remove learning nodes with explicit recovery guidance, configure and activate memory providers, and complete profile-scoped WhatsApp QR onboarding through the authenticated upstream Dashboard contracts.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android network clients shut down safely during route changes.** Replacing an authenticated Dashboard client now moves OkHttp connection-pool eviction off the main thread, preventing a live TLS socket close from crashing the app with `NetworkOnMainThreadException`. (#334)
|
||||
- **Android preserves authoritative Gateway outcomes.** Protected-file cards cannot offer forbidden persistent scopes, compression no-ops show the server result, bounded resume failures do not create context-free replacement sessions, and edit/regenerate retains durable row identities across consecutive rewinds.
|
||||
- **Android routes and uploads against live upstream truth.** Multiplex API fallback trusts `served_profiles` instead of installed profiles, and generic documents carry the Gateway-issued `@file:` reference into ordinary and queued prompts.
|
||||
- **Android clarify cards preserve upstream decision semantics.** Multi-select prompts keep independent selections and submit one exact list, while server expiry events—not an invented local deadline—retire unanswered cards.
|
||||
- **Android keeps profile management and retained automation truthful.** Custom Endpoint list and mutation routes now follow the selected Hermes profile, while completed one-shot cron jobs show their retained outcome and expose only valid Runs/Delete actions.
|
||||
- **Android and Relay recover more generated media reliably.** Android accepts upstream-valid wrapped, punctuated, adjacent, spaced, and Windows `MEDIA:` markers without consuming fenced examples, and Relay translates Docker-visible workspace, home, cache, and configured-mount paths before applying its existing credential, sandbox, and size checks.
|
||||
- **Android keeps cross-profile sessions with their owning agent.** Opening a session from All Profiles hydrates, resumes, sends, and renders with that session's profile without changing the global profile selection; New Chat from that view starts with the default profile.
|
||||
- **Android reactions and standard voice follow the active conversation.** Reactions resolve durable rows for both user and assistant messages, while Vanilla Hermes voice remains on the authenticated Gateway instead of requiring the optional API fallback.
|
||||
- **Android session navigation behaves predictably.** The drawer closes on outside taps, uses an ungrouped recent-session list by default, retains project grouping as an explicit option, and exposes secondary actions in All Profiles mode.
|
||||
|
||||
## [0.4.0-beta.3] - 2026-08-14
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows tray polling can no longer accumulate unbounded helper processes.** Grant discovery now uses lightweight local state, management refreshes are single-flight and visibility-aware, and child probes have hard timeouts, bounded output, tree cleanup, caching, and backoff. A dedicated bounded `tray.log` records sanitized operational failures without mixing them into daemon logs.
|
||||
- **Concurrent Desktop lifecycle requests cannot start duplicate daemons.** Cross-process lifecycle and runtime ownership locks serialize startup and recovery while preserving stale-owner cleanup.
|
||||
|
||||
## [1.8.0] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Official Hermes Desktop can surface Relay through its supported runtime Plugin SDK.** The unified plugin package now includes an opt-in, profile-scoped Desktop pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management. Loading, startup, reconnects, profile changes, and updates never open it; only labeled sidebar, status-bar, or command-palette actions register and reveal the movable native pane.
|
||||
|
||||
## [0.4.0-beta.2] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Desktop Activity now keeps inspectable local evidence.** Commands, files, devices, connection lifecycle, and computer control share a truthful event stepper with dedicated failure details; screenshot events can retain bounded local PNG evidence and open it in a larger borderless viewer. Settings controls retention as Off, 1 day, 7 days, or 30 days and shows local file usage.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Tunnel state stays responsive through interruption and retry.** The CLI UI distinguishes connected, reconnecting, and stopped states, exposes retry attempt/timing and a Retry now action, records connection failures and recovery in Activity, and shows compact connection cards only while the main UI is hidden.
|
||||
- **Windows CUA readiness no longer depends on the flaky whole-desktop health scan.** Hermes-Relay verifies the canonical runtime, manifest, required tools, daemon, and safe permission mode before starting structured sessions, while accessibility health remains an explicit CLI/UI diagnostic that can be rechecked without forcing the compatibility backend. This temporary workaround is scoped to the upstream fixed-timeout issue and keeps individual actions fail-closed.
|
||||
|
||||
## [0.4.0-beta.1] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **CUA Driver is the preferred Windows structured-control engine.** New local settings prefer a verified CUA runtime for window-targeted background actions, fresh snapshot tokens, and optional per-session animated agent cursors without moving the physical pointer; Windows Input is the explicit compatibility backend and backend choice is fixed for each control session. Full-display observation remains on the read-only system capture path. CLI and UI can explicitly install, check, or update the canonical CUA package after verifying the upstream release manifest and installer checksum; nothing is bundled or updated automatically, driver telemetry stays off for Hermes sessions, and activity records contain only bounded, redacted control metadata.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows bundle updates fail closed when installed processes retain a binary lock.** Setup waits for the invoking CLI, quiesces the tray and its short-lived CLI children, checks every payload extraction before writing release metadata, preserves custom install directories, and returns a failure instead of reporting a mixed-version installation.
|
||||
- **CUA readiness follows the published driver contract.** Hermes accepts the documented `ok` health state, distinguishes an installed-but-degraded runtime from a missing installation, and constructs trusted Windows installer paths consistently across verification environments.
|
||||
|
||||
## [1.7.0] - 2026-08-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Hermes Secure Link provides self-hosted pinned TLS ingress.** Relay, API, and Dashboard namespaces share one operator-owned TLS endpoint while retaining their native authentication boundaries, QR-carried certificate continuity, explicit rotation, and fail-closed route validation.
|
||||
- **Hermes Reach is available for explicit experimentation.** The optional self-hosted rendezvous broker carries opaque Secure Link TLS records over outbound-only connections with bounded multiplexing, hashed credentials, replay protection, persistence, revocation, and no access to Hermes payloads.
|
||||
- **Remote-access management exposes supported reachability clearly.** Dashboard status and pairing metadata distinguish Tailscale reachability, Secure Link transport protection, direct routes, and experimental Reach without presenting the broker as a replacement for authentication.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Tailscale is the recommended remote route.** Pairing, Dashboard, documentation, and public site guidance present Tailscale as the easiest supported remote-access path; Reach remains disabled by default, advanced, and lower priority than supported routes.
|
||||
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients honor custom headers, custom CA bundles, standard CA environment precedence, and an explicitly warned development-only verification override.
|
||||
- **Voice Lab xAI sign-in uses device authorization.** The standalone login shows a verification URL and user code and polls for approval without requiring a loopback callback.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Phone delivery remains compatible with strict Hermes targets.** Version-tolerant parser and validator hooks retain older-host registration and exactly-once standalone delivery.
|
||||
- **Profile-owned Relay registrations stay isolated.** Current Hermes uses profile-scoped ownership and context-local profile homes while legacy hosts retain a guarded compatibility path.
|
||||
- **Phone is discoverable before its first historical session.** The Relay phone adapter publishes its configured home destination through Hermes' standard channel directory.
|
||||
|
||||
## [0.4.0-alpha.8] - 2026-08-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Windows management separates each Relay host from this PC.** Host detail owns identity, pairing, access, capabilities, authorized clients, re-pairing, and guarded removal; Settings owns local daemon lifecycle, startup, privilege, terminal, logs, diagnostics, updates, and Help & About.
|
||||
- **Desktop access uses clear host-scoped presets and capabilities.** Restricted, Ask Every Time, Standard, Full Access, and Custom remain explicit across commands, files, screen/input, USB, microphone, and camera controls.
|
||||
- **Activity drilldown preserves bounded execution evidence.** Overview shows the latest three events and detail views expose request, output, result, exit, duration, and truncation metadata without copying sensitive inputs.
|
||||
- **Connection presentation shows the live Agent-to-PC path.** Host selection, bidirectional packet motion, transition feedback, route details, and connection testing stay compact, responsive, and reduced-motion aware.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Connect and disconnect remain responsive during daemon work.** Lifecycle calls and snapshot collection run outside the UI thread, transition status polls quickly without overlapping probes, and progress remains visible until authoritative daemon state arrives.
|
||||
- **Tailscale is recommended for remote access.** Secure Link and direct TLS routes remain supported, while Hermes Reach is visibly experimental and lower priority.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Connection tests classify legacy private routes correctly.** A saved generic role is inferred from its actual endpoint, so LAN and Tailscale routes no longer appear as Custom VPN; results include reachability, latency, security, endpoint, and route count.
|
||||
- **Ask-mode approval cards show the requested action.** A bounded preview appears in the compact card with full context and an Open in UI action.
|
||||
- **Mixed capability policies are labeled Custom.** Overview no longer claims a preset when individual capability controls differ.
|
||||
- **Tray placement follows the notification-area monitor and DPI.** Responsive popup geometry stays anchored above the tray icon across compact and high-DPI desktops.
|
||||
- **PowerShell success output is complete and self-describing.** Scalar, pipeline, JSON, native stdout/stderr, exit status, and truncation metadata survive the desktop RPC response.
|
||||
|
||||
## [1.6.4] - 2026-08-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Desktop tools support explicit host targeting.** Every client-routed desktop tool accepts a stable device ID or unambiguous computer name, and `/desktop/health` enumerates connected targets and their advertised tools.
|
||||
- **USB operations retain both routing scopes.** Raw USB and ADB tools use `device` to select the desktop PC, while ADB operations continue to use `serial` to select hardware attached to that PC.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Multiple desktop clients remain connected simultaneously.** The Relay no longer replaces the previous desktop when another heartbeat arrives; concurrent requests are bound to their selected WebSockets, responses from another PC are ignored, and an untargeted call fails closed when several desktops are online.
|
||||
- **Pairing another desktop preserves existing credentials.** Legacy placeholder device identifiers are treated as absent instead of shared ownership, preventing an unrelated PC from revoking the first desktop's session.
|
||||
|
||||
## [1.6.3] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay diagnostics distinguish a prior clean stop from a crash.** Doctor and `/relay/info` expose only bounded clean, unclean, or unknown gateway-exit state with an optional suspected out-of-memory hint, without returning raw log evidence.
|
||||
- **Relay reconnects spread out after shared gateway restarts.** Ordinary exponential reconnect delays use full jitter while explicit reconnects and server-directed retry timing retain their exact behavior.
|
||||
|
||||
## [0.4.0-alpha.7] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installer lifecycle validation uses an isolated Windows PATH fixture.** Release smoke tests now verify add/remove cleanup against a fixed registry value and restore the runner's original value afterward, independently of the temporary profile used for session-preservation checks.
|
||||
|
||||
## [0.4.0-alpha.6] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installer cleanup validation compares the unexpanded Windows PATH.** Release smoke tests now read the raw user registry value, ensuring `%USERPROFILE%` entries are verified without temporary-profile expansion changing their apparent value.
|
||||
|
||||
## [0.4.0-alpha.5] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
@@ -557,7 +776,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
- **Spoken-turn badges (chat).** Voice-mode replies now carry a "Voice" chip and realtime replies a "Realtime Agent" chip — both with a speaker glyph — so spoken turns are distinguishable from typed ones in the scrollback.
|
||||
- **App themes.** A new theme picker in Settings → Appearance ships eight looks: the signature Hermes Relay brand (with full light/dark) plus ports of the Nous Hermes baselines — Hermes Teal, Nous Blue (light), Midnight, Ember, Mono, Cyberpunk, and Rosé. The whole app — brand chrome, accents, and chat background — follows the chosen theme. Light/Dark/Auto applies to themes that ship both modes; fixed-mode themes show their own complete look.
|
||||
- **Hot-swappable agent sphere.** The orb is now a pluggable "skin": an Adaptive skin that recolors to match your theme, built-in Classic / Aurora / Solar / Mono looks, and support for **user-authored skins** loaded from a small JSON spec. Each skin declares which live signals it reacts to (voice, tool bursts, activity), shown as capability badges in the picker. See `docs/sphere-spec.md`.
|
||||
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. A plugin-provided **Secure proxy** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
|
||||
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. The optional plugin-provided **Hermes Secure Link** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
|
||||
- **Enhanced voice control (Gemini & xAI).** When the relay uses a Gemini or xAI voice provider, Voice Settings can now steer it: pick a Gemini voice and model and turn on expressive tone tags (with optional natural-language voice direction), or set an xAI voice with expressive speech tags. Expressive tags also apply to xAI on the streaming voice-output renderer. Standard (no-plugin) voice stays configured server-side.
|
||||
- **Voice render-path visibility.** Voice Settings shows which path is rendering speech (streaming vs. basic), and Diagnostics records it each session, making voice issues easier to troubleshoot.
|
||||
- **Agent pets — a living, swappable avatar.** The orb can be replaced with an animated "pet" that reacts to what the agent is doing: idle / thinking / writing / speaking / listening states, a distinct **working** pose during tool calls, one-shot **greet** / **celebrate** reactions, and a loop that quickens as output streams. Add or remove pets right in Settings → Appearance (no `adb` needed), with a live state preview, a playback-speed slider, and optional frame auto-stabilization; capability badges (Voice · Tools · Activity) show honestly what each pet actually reacts to. Pets are pure data — an AI authoring kit and a JSON schema let you generate one from sprite art. See `docs/pet-spec.md` and the custom-avatars guide.
|
||||
|
||||
@@ -193,6 +193,10 @@ This is a **public, distributed repo** — every committed file (CHANGELOG, DEVL
|
||||
### 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.
|
||||
@@ -204,6 +208,7 @@ This is a **public, distributed repo** — every committed file (CHANGELOG, DEVL
|
||||
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `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** | |
|
||||
@@ -235,9 +240,10 @@ This is a **public, distributed repo** — every committed file (CHANGELOG, DEVL
|
||||
| **App — Bridge** | |
|
||||
| `network/handlers/BridgeCommandHandler.kt` | Routes `bridge.command` → ActionExecutor; full path inventory + safety-rail integration |
|
||||
| `viewmodel/BridgeViewModel.kt` | BridgeScreen VM — masterToggle, bridgeStatus, permissionStatus, activityLog |
|
||||
| `bridge/BridgeSafetyManager.kt` | Blocklist + destructive-verb confirmation + auto-disable timer; fails-closed on /call and /send_sms |
|
||||
| `data/BridgeSafetyPreferences.kt` | DataStore for blocklist, destructive verbs, auto-disable minutes, confirmation timeout |
|
||||
| `ui/screens/BridgeScreen.kt` | Bridge UI — master → permission checklist → [Advanced] → unattended → safety → activity log (v0.4.1 reorder) |
|
||||
| `bridge/BridgeSafetyManager.kt` | Connection-scoped capabilities + timed screen expiry + blocklist + destructive confirmation; unknown, denied, and expired commands fail closed |
|
||||
| `bridge/BridgeCapabilities.kt` / `data/BridgeCapabilityPolicyRepository.kt` | Closed method/path registry + no-backup-bound per-Connection Always/Never/Timed policy; global safety vocabulary and timer duration remain in `BridgeSafetyPreferences.kt` |
|
||||
| `ui/screens/BridgeScreen.kt` | Bridge cockpit — master → Agent access posture/setup → single Unattended Access control → capability-scoped Android readiness (expandable full matrix) → Advanced safety/full editor → activity log |
|
||||
| `ui/components/BridgeAccessCards.kt` | Native access cockpit + first-use preset and screen-lease sheets (renewable idle limits or warned Until-off dedicated-device mode); preserves full permission/safety drilldowns while keeping selected policy/readiness above the fold |
|
||||
| `ui/components/UnattendedAccessRow.kt` | Unattended toggle card (sideload); `enabled=masterEnabled`; inline `KeyguardDetectedAlert` |
|
||||
| `ui/components/UnattendedGlobalBanner.kt` | 28dp amber strip at scaffold top when master+unattended on (sideload); tap → Bridge tab |
|
||||
| `bridge/BridgeStatusOverlay.kt` | WindowManager overlay; `ConfirmationOverlayHost`; requires `SavedStateRegistryOwner` init order (CREATED→restore→RESUMED) |
|
||||
|
||||
+5
-22
@@ -1,34 +1,17 @@
|
||||
# Hermes-Relay CLI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-11
|
||||
**Release Date:** 2026-08-15
|
||||
|
||||
This alpha replaces the right-click-only Windows tray with the compact **Hermes-Relay CLI UI** popup while keeping Hermes-Relay's desktop boundary narrow. Chat, the remote TUI, plugins, voice, and agent sessions remain CLI or upstream desktop concerns.
|
||||
This patch keeps the Windows management UI usable when the Relay daemon is stopped or its status cannot be read.
|
||||
|
||||
**Experimental phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the management tray is Windows-only.
|
||||
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the management UI is Windows-only.
|
||||
|
||||
## What's changed
|
||||
|
||||
### Added
|
||||
|
||||
- **Compact Windows management tray.** The popup provides connection status, host selection, per-host access, pending approval dialogs, recent activity, daemon controls, startup settings, and authorized-client revocation.
|
||||
- **Host-aware desktop access.** `hermes-relay hosts` lists and selects paired Hermes instances and stores independent Ask, Trusted, or Full Access policy for each canonical relay URL.
|
||||
- **In-window grant decisions.** New computer-use requests bring the tray forward and show the requesting host, scope, reason, and duration with explicit Approve and Reject actions.
|
||||
- **Supported UI lifecycle from the CLI.** `hermes-relay ui install|open|status` lets a CLI-only Windows installation add, reveal, or inspect the optional management UI without rerunning setup by hand.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Daemon startup is connectivity-first.** Ask mode can keep an authenticated daemon connected with zero desktop tools attached, so starting the daemon does not itself grant authority.
|
||||
- **Full Access is explicit and host-scoped.** Trusted hosts may use command and file tools while screen/input remains task-granted. Full Access also removes task prompts for screen, input, and file patches for that host, while authentication, audit, revocation, emergency stop, and UAC boundaries remain enforced.
|
||||
- **Host changes apply immediately.** Selecting a different host or changing its access mode restarts an already-running daemon and the UI verifies that the daemon URL matches the selected host before showing it as connected.
|
||||
- **PowerShell remains first-class.** Agents should prefer the dedicated `desktop_powershell` RPC for native Windows work; `desktop_terminal` remains cmd-compatible for existing callers.
|
||||
- **CLI and UI updates share one verified installer.** Bundle updates coordinate shutdown and restart, allow same-version UI repair, and refuse accidental downgrade unless explicitly forced.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Detached daemon start reports real readiness.** `daemon start` waits for the spawned PID to authenticate and connect, and reports configuration, authentication, early-exit, and timeout diagnostics instead of returning a false success.
|
||||
- **Normal tray operation no longer requires opening a CLI for grants.** Pending requests are resolved directly in the focused management dialog.
|
||||
- **Release checks match the management tray.** CI builds the React assets, validates Tauri metadata, and smoke-tests the packaged tray without obsolete menu-only size or window assertions.
|
||||
- **Installed tray builds no longer depend on a localhost development server.** Local and packaged builds embed their UI assets, eliminating the `127.0.0.1 refused to connect` failure.
|
||||
- **Stopped daemons no longer block the management UI.** Missing, stale, malformed, or temporarily unavailable daemon status falls back to an explicit stopped state while hosts, settings, activity, CLI details, diagnostics, and daemon controls continue loading normally.
|
||||
- **Starting the daemon restores live status without reopening the UI.** A valid running status continues through the same bounded, single-flight snapshot path introduced in beta.3.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -29,6 +29,20 @@ scripts/dev.bat version # Show current version
|
||||
scripts/dev.bat relay # Start relay server (dev, no TLS)
|
||||
```
|
||||
|
||||
### Review bundles
|
||||
|
||||
Maintainers can produce a matched Android + Relay handoff for one pull request
|
||||
without cutting a release. Run **Actions → Build Review Bundle** with the PR
|
||||
number or an exact 40-character SHA. The short-lived artifact contains a
|
||||
side-by-side Candidate APK, Relay packages/source from the same commit,
|
||||
provenance, checksums, and install/rollback guidance.
|
||||
|
||||
Review bundles never bump versions, create tags, upload to Play, or replace the
|
||||
stable Android app. Relay review still requires a staging Hermes instance or an
|
||||
explicit immutable snapshot/rollback window because two Relay plugins cannot
|
||||
own the same tools and hooks in one Hermes process. See
|
||||
[Review builds and release candidates](docs/review-candidates.md).
|
||||
|
||||
Linux/macOS equivalent lives at `scripts/dev.sh`.
|
||||
|
||||
### Fast Android iteration
|
||||
@@ -200,6 +214,10 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
|
||||
cycle; hosted CI remains the exhaustive all-variant gate.
|
||||
- **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)
|
||||
covers the on-demand vanilla-Gateway fixture, Android instrumentation,
|
||||
upstream conformance, and physical-device ADB certification. No contract or
|
||||
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.
|
||||
|
||||
@@ -1,5 +1,85 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-08-20 — Android 1.11.0 Bridge access and lower idle power
|
||||
|
||||
Hermes-Relay Android 1.11.0 is published from the immutable
|
||||
`android-v1.11.0` tag, with Google Play versionCode 46 submitted to the
|
||||
Production track. The release adds per-connection Bridge capability presets,
|
||||
custom grants, and explicit bounded or unlimited screen access while preserving
|
||||
the master kill switch and Android permission requirements.
|
||||
|
||||
Stored-session resume failures now remain visible without silently changing
|
||||
conversation context, software-keyboard Return works across direct-text and
|
||||
synthesized-Enter IMEs, and cancelled recovery keeps its Stopped state. Idle
|
||||
render loops, screen-capture surfaces, audio effects, wake-word buffers, and
|
||||
unattended wake locks now follow tighter lifecycle boundaries to reduce power
|
||||
use without removing persistent Relay reachability.
|
||||
|
||||
## 2026-08-20 — Android stored-session resume failures stay visible
|
||||
|
||||
Android now treats a failed Gateway `session.resume` as authoritative for the
|
||||
selected stored conversation. The client no longer creates a replacement
|
||||
session and submits the continuation after a resume rejection or profile-scope
|
||||
mismatch, preventing a context-free turn from silently selecting different
|
||||
runtime state.
|
||||
|
||||
Gateway terminal failures and pre-submit transport failures now share a
|
||||
session-scoped panel immediately above the composer. The panel keeps the failed
|
||||
transcript row intact, shows only confirmed route/model/provider identity,
|
||||
offers explicit Details, Retry, and Dismiss actions, and records bounded,
|
||||
redacted evidence in the existing Diagnostics review/share flow. No route or
|
||||
model is changed automatically.
|
||||
|
||||
## 2026-08-18 — Android 1.10.0 chat continuity and streaming Markdown
|
||||
|
||||
Hermes-Relay Android 1.10.0 is published from the immutable
|
||||
`android-v1.10.0` tag, with the production Play submission committed as
|
||||
versionCode 45. The release preserves exact-session composer drafts across
|
||||
restarts, converts large pastes into reviewable attachments, and keeps standard
|
||||
chat compatible with unmodified upstream Hermes.
|
||||
|
||||
Assistant replies now render completed Markdown structures incrementally while
|
||||
holding an incomplete streaming tail stable. Stable message identity and a
|
||||
bounded bottom-follow controller prevent completion-time replacement, stacked
|
||||
scroll animations, and transcript-distance velocity from moving a reader who
|
||||
has deliberately scrolled away. Foreground reconnect reattaches the visible
|
||||
Gateway session, malformed imported credentials fail closed, and software
|
||||
keyboard Return remains distinct from the dedicated Send action.
|
||||
|
||||
## 2026-08-17 — Android composer continuity and large-paste review
|
||||
|
||||
Android's multiline composer now leaves the software IME action as Return while
|
||||
the dedicated trailing button sends. Physical keyboard Enter, Shift+Enter, and
|
||||
directional caret behavior retain their existing contracts.
|
||||
|
||||
Composer drafts now persist in bounded app-private no-backup storage using
|
||||
small owner metadata plus content-addressed attachment blobs. Draft ownership
|
||||
follows the exact connection, opened session profile, session, and draft slot;
|
||||
profile and connection switches save before restoring, lifecycle stop flushes
|
||||
the latest state, and successful sends remove the saved draft.
|
||||
|
||||
A default-on Chat setting converts a single insertion of at least 5,000
|
||||
characters into a reviewable text attachment. Preparation runs off the UI
|
||||
thread behind a visible loading card. Current Gateways send it through upstream
|
||||
`file.attach`; API-server SSE and proactive Thread paths materialize the same
|
||||
UTF-8 content into the prompt so no route silently loses the paste.
|
||||
|
||||
## 2026-08-14 — Android 1.9.0 session identity and conversation controls
|
||||
|
||||
Hermes-Relay Android 1.9.0 is published from the immutable
|
||||
`android-v1.9.0` tag. Multi-profile session browsing now keeps the aggregate
|
||||
drawer scope selected while transcript hydration, resume, sending, and header
|
||||
identity follow the session's owning profile. New Chat from All Profiles uses
|
||||
the default profile, and the session list starts ungrouped while retaining
|
||||
project grouping and the other desktop-style views as explicit options.
|
||||
|
||||
Message reactions now resolve durable rows for both user and assistant
|
||||
messages. Vanilla Hermes voice remains on the authenticated Gateway instead of
|
||||
requiring the optional API fallback. Session rows can expose profile, project,
|
||||
branch, and pull-request context without crowding the chat header, secondary
|
||||
drawer actions remain available in All Profiles, and outside taps dismiss the
|
||||
drawer.
|
||||
|
||||
## 2026-08-09 — Gateway activity recovery and chat speech
|
||||
|
||||
Successful Android Gateway turns now reconcile against their profile-owned,
|
||||
|
||||
+10
-8
@@ -1,19 +1,21 @@
|
||||
# Hermes-Relay-Server v__VERSION__
|
||||
|
||||
**Release Date:** August 11, 2026
|
||||
**Release Date:** August 21, 2026
|
||||
|
||||
This patch makes paired sessions easier to identify and their expiry easier to understand across Relay clients and the Dashboard.
|
||||
## Summary
|
||||
|
||||
This release makes delayed phone delivery and active Bridge access easier to understand. Relay now identifies messages flushed after reconnect, emits one completion signal for the backlog, and reports permanent, timed, and unlimited phone capabilities through status surfaces.
|
||||
|
||||
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
|
||||
|
||||
## What's changed
|
||||
## Added
|
||||
|
||||
### Fixed
|
||||
- **Reconnect backlog context.** Messages flushed from the bounded offline queue carry an explicit delayed-delivery marker, followed by one ordered completion event with the delivered count.
|
||||
- **Granular phone capability status.** Relay status and `android_phone_status` report permanent, timed, and unlimited Bridge capabilities alongside existing Android permissions and safety state.
|
||||
|
||||
- **Recognizable device names.** Relay uses the client hostname as the primary paired-session name when available while preserving compatibility with existing clients.
|
||||
- **Persisted device details.** Model and platform metadata survive refresh, reconnect, and Relay restart and appear in the authorized-session API and Dashboard detail view.
|
||||
- **Reconnect enrichment without re-pairing.** A valid paired client can fill missing identity metadata during reconnect without changing its authentication state.
|
||||
- **Human-readable expiry.** Long paired-session lifetimes use days, weeks, or a calendar date, with the exact local deadline retained for inspection.
|
||||
## Changed
|
||||
|
||||
- **Phone surfacing semantics are explicit.** Default delivery persists to Threads and notifies, Inbox delivery remains silent, and Session delivery targets an available active conversation before falling back to a notification.
|
||||
|
||||
## Install / update
|
||||
|
||||
|
||||
@@ -70,6 +70,21 @@ an HTTPS reverse proxy. The [full walkthrough](https://hermes-relay.dev/docs/gui
|
||||
covers Windows, remote access, and dashboard authentication. You do not need to
|
||||
enable the separate API server or invent an API key for the standard path.
|
||||
|
||||
For plugin-enabled setups, optional **Hermes Secure Link** presents Relay, API,
|
||||
and Dashboard routes through one pairing-pinned TLS origin. It protects traffic
|
||||
to the paired endpoint while each service keeps its own authentication; it does
|
||||
not provide reachability or independently identify the physical host. You still
|
||||
use LAN routing, Tailscale or another VPN, or an operator-managed public route
|
||||
to reach the listener. Secure Link is off by default and requires a fresh QR
|
||||
pairing after it is enabled. See the
|
||||
[remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
||||
|
||||
**Hermes Reach** is an experimental, advanced outbound-broker route. It remains
|
||||
available for development and self-hosted evaluation, but it is disabled by
|
||||
default, ordered after supported routes, and not recommended for normal remote
|
||||
access. Use Tailscale for the easiest supported remote setup, or a public TLS
|
||||
domain / Direct Secure Link when you want to own the complete network path.
|
||||
|
||||
### 3 · Connect and talk
|
||||
|
||||
Open the app, choose **Connect to Hermes**, and enter or discover the dashboard
|
||||
@@ -204,6 +219,14 @@ It pairs against the **same relay and credential store** as the Android app —
|
||||
|
||||
On Windows, the default installer adds the optional compact **Hermes-Relay CLI UI** tray popup for host selection and pairing, connection and daemon state, per-host Ask/Trusted/Full Access, local grant dialogs, authorized-client revocation, activity, settings, and emergency stop. It is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
|
||||
|
||||
Structured Windows computer control prefers a compatible local CUA Driver
|
||||
runtime for window-targeted background actions and virtual per-session agent
|
||||
cursors. It remains behind Hermes host policy, grants, targeting, audit, and
|
||||
emergency stop; Windows input is an explicit compatibility backend. CUA is not
|
||||
bundled or updated automatically, but the local CLI/UI can explicitly install,
|
||||
check, or update its verified canonical package. It is never exposed as a raw
|
||||
remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs/desktop/tools.html#computer-use-engines).
|
||||
|
||||
- **Docs:** [CLI guide](https://hermes-relay.dev/docs/desktop/) · [`desktop/README.md`](desktop/README.md)
|
||||
- **AI-agent setup recipe:** `/hermes-relay-desktop-setup`
|
||||
|
||||
@@ -279,6 +302,12 @@ scripts/dev.bat version # Show current version
|
||||
scripts/dev.bat relay # Start the relay server (dev, no TLS)
|
||||
```
|
||||
|
||||
Gateway, session, streaming, reconnect, or authoritative-history changes use
|
||||
the reusable, on-demand [Gateway contract lab](docs/gateway-contract-testing.md).
|
||||
It includes deterministic protocol scenarios, current-upstream conformance,
|
||||
Android instrumentation, and opt-in physical-device certification; none of
|
||||
those lanes is scheduled automatically.
|
||||
|
||||
### Tech Stack
|
||||
|
||||
| Component | Stack |
|
||||
|
||||
+32
-19
@@ -128,6 +128,7 @@ optional Windows installer.
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `desktop/package.json` | canonical CLI version |
|
||||
| `desktop/.bun-version` | exact Bun compiler/runtime for standalone binaries |
|
||||
| `desktop/package-lock.json` | npm root/workspace package metadata |
|
||||
| `desktop/src/version.ts` | compiled CLI runtime version |
|
||||
| `desktop/tray/Cargo.toml` | native systray package version |
|
||||
@@ -152,6 +153,8 @@ manually, run `npm run sync:version` before checking. `npm run verify` is the
|
||||
single Windows release-parity gate: version sync, type-check, tests, TypeScript
|
||||
build, compiled CLI smoke, and tray formatting, Clippy, check, and tests. CI runs
|
||||
the portable portions on every desktop change and the Windows tray gates separately.
|
||||
Release jobs read `desktop/.bun-version`; cross-built and Windows-built artifacts
|
||||
must not silently embed different Bun runtime versions.
|
||||
|
||||
## Branching policy
|
||||
|
||||
@@ -174,10 +177,11 @@ then tagging `main`. Feature completion means merged and verified on `dev`; it
|
||||
does not mean released.
|
||||
|
||||
**Staging is an environment, not a branch.** Deploy an exact tested `dev` SHA or
|
||||
an immutable release-candidate tag to staging. Record that source in the Forge
|
||||
release issue/session. Never deploy a moving branch name as the source of record
|
||||
and never create a staging branch. Production deploys only immutable
|
||||
`android-v*`, `server-v*`, or `desktop-v*` tags cut from `main`.
|
||||
an immutable prerelease tag (`-alpha`, `-beta`, or `-rc.N`) cut from a
|
||||
release-prepared `dev` commit. Record that source in the Forge release
|
||||
issue/session. Never deploy a moving branch name as the source of record and
|
||||
never create a staging branch. Stable production tags are cut only from the new
|
||||
`main` tip after the approved `dev` → `main` release merge.
|
||||
|
||||
### Normal contribution and release flow
|
||||
|
||||
@@ -415,10 +419,17 @@ it sit alongside in `[Unreleased]`, and ship them together. A release
|
||||
is a statement to users that "this is a thing worth updating to," so
|
||||
the threshold is intent-driven, not event-driven.
|
||||
|
||||
If you want to dogfood accumulated `main` state without declaring GA,
|
||||
tag a **pre-release** (`android-vX.Y.Z-rc.N`). Users can opt in via
|
||||
`hermes-relay-update --branch rc/vX.Y.Z-rc.N` without being auto-pushed
|
||||
the unstable build.
|
||||
If you want to dogfood a frozen `dev` release candidate without declaring GA,
|
||||
tag the exact release-prepared `dev` commit with a **prerelease** tag such as
|
||||
`android-vX.Y.Z-rc.N` or `server-vX.Y.Z-rc.N`. Android prereleases publish the
|
||||
side-by-side Candidate app and never upload to Play. Server prereleases publish
|
||||
opt-in packages for staging and do not automatically replace production.
|
||||
See [Review builds and release candidates](docs/review-candidates.md).
|
||||
|
||||
For one-PR review, do not bump versions or create a tag. Run **Build Review
|
||||
Bundle** for the PR number or exact SHA. It produces one short-lived matched
|
||||
Android + Relay artifact; the Candidate app uses a separate application ID and
|
||||
the Relay package requires an explicit staging or snapshot/rollback install.
|
||||
|
||||
## Release train ownership
|
||||
|
||||
@@ -825,19 +836,20 @@ plugin changes from forcing an Android app `versionCode` bump.
|
||||
|
||||
On every push of a tag matching `android-v*`, `.github/workflows/release-android.yml`:
|
||||
|
||||
1. Verifies the stable tag resolves to a commit contained in `main` and that the
|
||||
tag matches `appVersionName` in
|
||||
1. Verifies a stable tag resolves to a commit contained in `main`, or a
|
||||
prerelease tag resolves to a commit contained in `dev`, and that the tag matches `appVersionName` in
|
||||
`gradle/libs.versions.toml` (mismatches fail the workflow).
|
||||
2. Runs the Android debug build and the stable sideload pairing/connection
|
||||
regression slice with explicit timeouts.
|
||||
3. Decodes `HERMES_KEYSTORE_BASE64` into `$RUNNER_TEMP/release.keystore`
|
||||
and exports `HERMES_KEYSTORE_PATH` (skipped if the secret is unset).
|
||||
4. Builds all four flavored release artifacts
|
||||
4. For stable releases, builds all four flavored release artifacts
|
||||
(`./gradlew bundleRelease assembleRelease`); only the sideload APK and
|
||||
googlePlay AAB are attached (see §Release assets).
|
||||
googlePlay AAB are attached. For prereleases, builds only the side-by-side
|
||||
`sideloadCandidate` APK.
|
||||
5. Generates `SHA256SUMS.txt` covering the two attached files.
|
||||
6. Promotes the exact preflighted Production draft to `completed`; a missing
|
||||
credential or rejected Play edit fails before public GitHub publication.
|
||||
6. For stable releases only, promotes the exact preflighted Production draft to
|
||||
`completed`; prereleases never upload to Play.
|
||||
7. Creates a GitHub Release named `Hermes-Relay-Android v<version>` with `RELEASE_NOTES.md` as
|
||||
the body. Attaches the APK, AAB, and `SHA256SUMS.txt`. Tags any version
|
||||
containing a dash (e.g. `android-v0.2.0-beta.1`) as a prerelease automatically.
|
||||
@@ -846,8 +858,8 @@ On every push of a tag matching `android-v*`, `.github/workflows/release-android
|
||||
On every push of a tag matching `server-v*`,
|
||||
`.github/workflows/release-plugin.yml`:
|
||||
|
||||
1. Verifies the tag commit is contained in `main`, validates the tag against
|
||||
all server/plugin-owned version metadata checked by
|
||||
1. Verifies a stable tag commit is contained in `main`, or a prerelease tag is
|
||||
contained in `dev`, then validates the tag against all server/plugin-owned version metadata checked by
|
||||
`scripts/check-plugin-version-sync.py`, and requires the matching release
|
||||
heading in `CHANGELOG.md`.
|
||||
2. Runs plugin syntax checks and the focused route/auth/session test slice.
|
||||
@@ -861,9 +873,10 @@ On every push of a tag matching `desktop-v*`,
|
||||
Windows tray installer. Its GitHub Release body comes from `CLI_RELEASE_NOTES.md`
|
||||
(rewritten per release — the CLI counterpart of `RELEASE_NOTES.md`); the workflow
|
||||
substitutes `__VERSION__` (bare, e.g. `0.3.0`) and `__TAG__` (full, e.g.
|
||||
`desktop-v0.3.0`) so the install/pin commands stay accurate. It rejects tags
|
||||
whose commit is not contained in `main`, whose version differs from
|
||||
`desktop/package.json`, or whose version has no `CHANGELOG.md` release heading.
|
||||
`desktop-v0.3.0`) so the install/pin commands stay accurate. It requires stable
|
||||
tags to be contained in `main` and prerelease tags to be contained in `dev`,
|
||||
with a version matching `desktop/package.json` and a corresponding
|
||||
`CHANGELOG.md` release heading.
|
||||
Fill its Summary and
|
||||
Added/Changed/Fixed groups at CLI release-prep and apply the §2 public scrub.
|
||||
Dashboard-only changes are covered by
|
||||
|
||||
+21
-17
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay-Android v1.8.1
|
||||
# Hermes-Relay-Android v1.12.0
|
||||
|
||||
**Release Date:** August 9, 2026
|
||||
**Release Date:** August 21, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.8.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.12.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,23 +12,27 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This patch keeps long Hermes conversations complete and aligns Android's
|
||||
Gateway behavior with current upstream turn contracts.
|
||||
This release adds saved custom themes and makes appearance shape consistent throughout Android. It also keeps profile and session identity intact across All Profiles navigation and language changes, recovers Gateway chats when a completion frame is missed, and accepts common Relay endpoint forms without producing invalid routes.
|
||||
|
||||
## Added
|
||||
|
||||
- Create up to 20 local custom themes with editable palette roles, Light or Dark ownership, saved shape, live chat preview, rename, duplicate, and delete controls.
|
||||
|
||||
## Changed
|
||||
|
||||
- Apply Soft, Balanced, or Sharp styling consistently across chat, settings, sheets, dialogs, terminal, voice, Bridge, and other shared surfaces.
|
||||
- Activate a session's owning agent when selecting it from All Profiles; profile locks hide that browser and reject cross-profile opens.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Complete transcript reads page explicitly across both API-server and
|
||||
profile-scoped Dashboard routes, so sessions beyond Hermes' latest-500
|
||||
default retain stable history, sharing, retry, edit, and recovery anchors.
|
||||
- Gateway submit rejections preserve the authoritative server message without
|
||||
silently falling through to SSE.
|
||||
- Gateway event envelopes reconcile consistently, and edit-and-regenerate
|
||||
requests send the required truncation confirmation.
|
||||
- Preserve the exact connection, agent, session, transcript, draft, and All Profiles state through an app-language change.
|
||||
- Relocalize the persistent connection notification without restarting the active connection.
|
||||
- Settle and reconcile active Gateway turns when the terminal completion frame was missed.
|
||||
- Normalize Relay base, `/ws`, and `/health` endpoint forms without producing duplicate route segments.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.8.1** (versionCode **42**).
|
||||
- Standard Chat, sessions, Manage, and Vanilla Hermes voice continue to work
|
||||
against unmodified upstream Hermes.
|
||||
- The optional Relay plugin is not required for standard Android chat or hosted
|
||||
Dashboard authentication.
|
||||
- App version: **1.12.0** (versionCode **47**).
|
||||
- Standard Chat, sessions, Manage, profile switching, custom themes, and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
|
||||
- Granular Device Control remains sideload-only; the Google Play build continues to ship Hermes Bridge Core without AccessibilityService Device Control.
|
||||
- The optional Relay plugin is not required for standard Android chat, session continuity, themes, or Gateway recovery.
|
||||
|
||||
@@ -6,26 +6,91 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Certify Android Gateway missing-terminal recovery on physical devices
|
||||
|
||||
Deterministic fake-Gateway coverage now proves that a foreground turn with
|
||||
rapid deltas and tool activity can lose its WebSocket before
|
||||
`message.complete`, reactivate the exact live runtime, observe authoritative
|
||||
`running=false`, and reconcile persisted history without navigation, API
|
||||
fallback, duplicate submission, or a silent streaming latch. Complete the
|
||||
remaining hardware matrix before treating issue #365 as device-certified:
|
||||
|
||||
On-demand contract-lab certification passed on an Android 16 SM-S938U using
|
||||
the sideload app and instrumentation APK. The embedded device test exercised
|
||||
Activity `STARTED` to `RESUMED` while streaming; the external fixture test then
|
||||
proved prompt submission, controlled socket loss, exact activation,
|
||||
authoritative HTTP history, idle settlement, and no API fallback. The ADB
|
||||
runner separately completed launch, Home/foreground, force-stop, and process
|
||||
recreation without enabling radio mutation. This is deterministic fixture
|
||||
proof, not certification against the reporter's host/device or a live provider.
|
||||
|
||||
- Re-run long multi-turn/tool-heavy chats against current vanilla upstream on
|
||||
the originally reported Android/device family and one Android 14+ device.
|
||||
- Exercise foreground-open chat, background/foreground, Wi-Fi/cellular loss,
|
||||
socket replacement, queued follow-ups, profile/session switches, and process
|
||||
recreation while capturing the content-free Gateway recovery diagnostic.
|
||||
- Confirm selection, user-owned scrollback, streaming Markdown, and follow
|
||||
behavior remain stable while authoritative history catches up.
|
||||
|
||||
---
|
||||
|
||||
## Certify Android power fixes across the reported device matrix
|
||||
|
||||
Issue #377's static estimates are not device measurements. The code now keeps
|
||||
the idle Sphere static, gates inactive waveform/drawer animation, detaches the
|
||||
MediaProjection surface between requested frames, binds AEC/NS to the capture
|
||||
session, releases unattended wake locks at command completion, and reuses the
|
||||
wake-word normalization buffer. Complete the remaining physical proof before
|
||||
assigning battery percentages or declaring the report closed:
|
||||
|
||||
- Re-run the reported Android 13 / Pixel 4 XL workload with screen-on and
|
||||
screen-off intervals separated, and with experimental wake listening both
|
||||
disabled and explicitly enabled. Capture scoped CPU/thread/network/wakelock
|
||||
evidence plus Battery Historian or Perfetto without resetting batterystats
|
||||
unless the device owner approves the reset.
|
||||
- On Android 14+ and a foldable/rotation path, request two screenshots around a
|
||||
geometry change and verify the existing VirtualDisplay resizes, its surface
|
||||
is detached between requests, and the projection token is not reused.
|
||||
- On at least one device with platform AEC, run Standard and Realtime barge-in
|
||||
through playback and confirm the effect is enabled on the AudioRecord session,
|
||||
the microphone remains single-owner, interruption still works, and teardown
|
||||
leaves no audio effect or capture session active.
|
||||
- Compare Wi-Fi and cellular separately. Treat radio-tail claims as unproven
|
||||
until packet timing and mobile-radio active time reproduce them on hardware.
|
||||
|
||||
---
|
||||
|
||||
## Certify the official Desktop Relay plugin
|
||||
|
||||
The unified `plugin/desktop/plugin.js` implementation is covered by source-level
|
||||
SDK contract, packaging, explicit-open, no-auto-open, close, unload, and profile
|
||||
cache-isolation tests. A physical official Hermes Desktop session is still
|
||||
required before calling the UX live-certified:
|
||||
|
||||
- Test default and named local profiles, ordinary authenticated remote mode,
|
||||
and SSH mode with differently named local/remote profile mapping.
|
||||
- In two full app windows, prove enabling, registration, explicit open,
|
||||
requests, close/reopen, hot reload, and disable/unload remain window-local.
|
||||
- Prove startup, reconnect, profile change, layout restore/reset, update, and
|
||||
background events never open or focus Relay.
|
||||
- Drag and dock the pane across native zones, close it, reopen it from all three
|
||||
labeled actions, and verify no private-hook fallback is needed.
|
||||
- Exercise Relay running/unreachable, zero/one/multiple devices, pairing,
|
||||
revocation, bridge activity, media, remote access, and renderer error logging
|
||||
without exposing credentials, pairing payloads, filesystem paths, or tokens.
|
||||
|
||||
---
|
||||
|
||||
## Structured desktop hardware capabilities
|
||||
|
||||
Desktop command, PowerShell, process, and job tools currently execute with the
|
||||
desktop daemon's OS-user authority. Add typed hardware operations for reliable
|
||||
schemas, audit detail, and task-scoped approval, but do not present hardware
|
||||
toggles as isolation while an enabled general shell can reach the same device.
|
||||
|
||||
- Define per-host capabilities for commands, files, processes, clipboard,
|
||||
screen, input, connected devices, microphone, and camera. Disabled must win,
|
||||
hardware-sensitive capabilities must default off, and unavailable backends
|
||||
must appear unavailable rather than as inert toggles.
|
||||
- Add a **Structured only** access profile that withholds shell/process escape
|
||||
hatches so individual capability toggles become enforceable boundaries.
|
||||
- Implement connected-device support first with typed, serial-bound ADB
|
||||
operations (`list`, `shell`, `push`, `pull`, `install`, and bounded logcat)
|
||||
instead of a generic device-exec wrapper.
|
||||
Structured access and per-host USB policy now ship with typed, serial-bound ADB
|
||||
list, shell, push, pull, install, and bounded logcat operations. Remaining work:
|
||||
- Add microphone and camera only with backend readiness detection, bounded local
|
||||
grants, active-use indicators, audit events, and immediate cancellation.
|
||||
- Reconcile legacy `desktop_screenshot` with the task-granted computer screenshot
|
||||
path so screen capture follows one policy.
|
||||
- Extend capability policy beyond hardware only where a typed broker provides a
|
||||
meaningfully stronger boundary than Structured mode already provides.
|
||||
|
||||
---
|
||||
|
||||
@@ -932,7 +997,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
|
||||
- Live gateway must discover the plugin (`~/.hermes/plugins/hermes-relay` → `plugin/`) and `plugins.enabled` must include `hermes-relay` for the `phone` platform to register. Confirm `phone` appears in `hermes gateway status` with `PHONE_ENABLED=1`.
|
||||
- End-to-end: with the app paired + "Let Hermes message me" on, run `send_message target=phone text=...` (and a cron `deliver=phone`) and confirm a notification on the device. Verify 503 (no phone) and the off-by-default gates.
|
||||
- **Phase 2c reply round-trip — ✅ DONE (verified on-device 2026-06-29).** Confirmed: agent → phone notification → inline reply → drained through the relay's loopback `GET /phone/replies` (different process) → `handle_message` (`role_authorized=True`, no `PHONE_ALLOW_ALL_USERS`) → agent answer back in the *same* thread. Both fixes required (see DEVLOG / the Phase 2c bullet above).
|
||||
- **FIX: cron `deliver=phone` / standalone send is broken.** Live testing: `hermes send --to phone` returns `{"error": "Unknown platform: phone"}`. The standalone (non-gateway) send path doesn't run a `kind=standalone` plugin's programmatic `ctx.register_platform`, so it never learns `phone` — only the running gateway (which loads `register()` at startup) does. The agent path (`send_message target=phone` in the gateway) works and was verified end-to-end on-device; the standalone/cron path needs the platform discoverable there too (declare it so the standalone loader picks it up, or route cron through the gateway). Until then `cron deliver=phone` won't work.
|
||||
- **Cron `deliver=phone` live certification pending.** The plugin now registers its standalone sender and enumerates the canonical phone home through the upstream adapter channel-directory hook. Re-run the device scenario above on the deployed plugin to certify scheduled delivery, including the offline queue and opt-in gates.
|
||||
- **FIX SHIPPED (2026-07-07) — installer + doctor guard against stale duplicate plugin copies; live-host verify pending.** Root cause of the 2026-06-29 round-trip failure: the gateway loader dedups discovered plugins by manifest `name`, so a second directory declaring `name: hermes-relay` (an old-installer backup copy, or a stray native install) could win the dedup and make the gateway load stale code — silently ignoring every later deploy. `plugin/doctor.py` now emits a `plugin-name-unique` warning when more than one directory under `~/.hermes/plugins/` declares the same plugin name (distinct real targets only — two links to the same target are deduped), and `install.sh` sweeps any such duplicate so only the canonical `hermes-relay` symlink survives. (Current `install.sh` already `rm -rf`s the old link rather than backing it up inside the plugins dir, so the original "back up outside the plugins dir" half is moot.) **Verify on the live host:** `hermes relay doctor` reports the `plugin-name-unique` check, and a reinstall leaves exactly one `hermes-relay` entry under `~/.hermes/plugins/`.
|
||||
|
||||
## Phone platform — usability roadmap (post device-verification, 2026-06-29)
|
||||
@@ -943,9 +1008,9 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
|
||||
|
||||
**Refinement (2026-06-29) — unified-session model: "Threads."** Going further on "unified surface": the agent conversation is **not a separate tab/segment** at all — it is a **source-tagged session inside the one Chat surface**, a **Thread** (`source=phone`). What makes a Thread special vs. a normal gateway chat are *session properties*, not a separate UI: (a) the agent can initiate, (b) relay `proactive` transport + relay-gated, (c) standing/named DM. **Scrollback = the gateway session store** (same read path Chat uses); **live receive = relay `proactive` push** (→ notification); **send = `proactive.reply`**. `ProactiveInboxStore` is demoted to a live-push cache + outbox (no parallel history). The Thread capability shows in the **best-path/capability UI** (relay tier, like terminal/bridge/voice) and as a clean **Threads** entry — thread-spool icon, NOT a phone glyph — pinned atop the session drawer when active; never a connection-wizard step. Degrades cleanly (no plugin → no `source=phone` sessions → Chat unchanged). **Supersedes the "separate Agent lane / 4th nav segment" sketch** and merges with the "source attribution in Chat" goal below. Keep the two "gateway" senses straight: *platform layer* (the Thread's `source`) ≠ *dashboard `/api/ws` transport* (how live bytes flow). Full re-cut: docs/decisions.md ADR 12.
|
||||
|
||||
- **Outbound buffering — ✅ relay-side DONE (2026-06-29).** `ProactiveChannel.push()` now queues agent→phone messages in a bounded deque (drop-oldest, 24 h TTL) when no phone is subscribed and returns `{queued: true}` (not 503); `_flush_outbound` delivers FIFO on the next subscribe (stale pruned). Inspect/cancel via `peek_outbound`/`cancel_outbound` + loopback `GET`/`DELETE /phone/outbound`. **UI surfacing of the queued state** (host-side, since the queue exists while the phone is OFFLINE): (a) ✅ **desktop CLI `relay queue` / `relay queue --clear` / `--cancel <id>` DONE (2026-06-29)** over the new endpoints (loopback-only — run on the relay host); a dashboard Relay-tab view is the optional GUI equivalent; (b) **remaining** — in the threaded agent surface, mark messages that arrived-while-away, and show the user's OWN pending replies (the Phase 3 reply queue) with a sending/Cancel affordance — that's where phone-side "queued + cancel" belongs.
|
||||
- **Outbound buffering — ✅ relay-side + arrived-while-away receive UX DONE.** `ProactiveChannel.push()` queues agent→phone messages in a bounded deque (drop-oldest, 24 h TTL) when no phone is subscribed and returns `{queued: true}`. `_flush_outbound` delivers FIFO on the next subscribe (stale pruned), marks flushed messages, and sends one batch-complete count; Android labels those Thread bubbles “While away” and shows one accessible batch summary without changing unread behavior. Inspect/cancel remains available through `peek_outbound`/`cancel_outbound`, loopback `GET`/`DELETE /phone/outbound`, and desktop `relay queue`. **Remaining:** show the user's OWN pending replies (the Phase 3 reply queue) with an honest Queued/Cancel affordance; a dashboard queue view remains optional.
|
||||
- **Threads surface (unified-session model — see ADR 12 + the Refinement above).** Build order, each shippable: **(1)** source tags in the session drawer (`source=phone` → clean **Threads** chip + thread-spool icon, NOT a phone glyph) — also delivers the "source attribution in Chat" goal; **(2)** open a Thread in Chat from its session-store history (reuse the existing message-history path); **(3)** route the live `proactive` push into the session view + notification + unread, demoting `ProactiveInboxStore` to cache/outbox; **(4)** reply from the Chat composer via `proactive.reply` + persist the user turn + local `Sending/Queued/Failed` status — **MVP**; **(5)** a **Threads capability row** in the best-path UI + a pinned **Threads** entry atop the drawer (thread-spool icon, shown only when relay-paired + opted-in) + retire `HermesInboxScreen`, re-point the notification deep-link + Settings "View messages"; **(6)** outbox/retry on reconnect; **(7)** relay `proactive.reply.ack` (honest Delivered) + `proactive.cancel`; **(8)** multi-thread `chat_id` (named/project Threads). **Verify gate before (1):** confirm the app's session-list/history path surfaces a `source=phone` session cleanly (upstream `session.list` returns all sources flat, so it should — but check whether the drawer currently filters it out). Honesty call: do NOT show "Delivered" until (7) lands (can't confirm it client-side before the ack).
|
||||
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering** (an agent reply lands in the open Thread as an ASSISTANT bubble, suppressing the notification/inbox — `injectIntoThread`); **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`** (deleted; route + nav removed; notification tap + Settings "View messages" re-pointed to Chat; surface renamed "Hermes messages" → **"Threads"**); relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DEFERRED (reasons):** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **exact-Thread deep-link** from the notification (opens Chat today, not the specific thread — needs select-session-on-entry); **remove the now-orphaned `ProactiveInboxStore`** (viewer-less write-only log); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
|
||||
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering**; **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`**; relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DONE (2026-08-14):** notification taps survive cold start and open the exact `chat_id`; agent-initiated outbound messages appear as connection-scoped provisional Threads backed by the bounded proactive store, then promote to the real `source=phone` session after the first reply. **DEFERRED:** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
|
||||
- **User-created Threads (slice 8, Discord-style) — CODE-COMPLETE on `dev` (built + installed 2026-06-29; on-device behavior pending).** "+ New Thread" in the drawer's Threads view → name dialog → `ChatViewModel.startNewThread` mints a fresh `chat_id`; the first composer message opens it over `proactive.reply` (gateway auto-creates the `source=phone` session) → `switchToCreatedThread` polls + switches to the real session + applies the name. Existing-thread replies route by the `chat_id` parsed from the session id (`…:dm:<chat_id>`; opaque id → home fallback). **On-device verifies:** (1) a fresh-`chat_id` no-`reply_to` inbound creates a new `source=phone` session; (2) the phone session id carries the `…:dm:<chat_id>` form the client parses; (3) `renameSession` titles a phone session. **Remaining slice-8:** AGENT-initiated named Threads (the upstream `send_message` thread/chat_id param so the agent can open its own named Threads).
|
||||
- **`chat_id` not exposed by `/api/sessions` (root cause of the 2026-06-29 on-device create-flow bugs — fixed client-side).** Confirmed on the host: a phone session's `id` is a timestamp (e.g. `20260629_204755_94f391d6`); the real `chat_id` lives in the `session_key` (`agent:main:phone:dm:<chat_id>`) and a `chat_id` column — but `/api/sessions` returns **neither `chat_id` nor `session_key`**, only `source` + the timestamp `id`. So the client could not map a session ↔ its `chat_id`, which broke create-thread switch/rename + reply routing + in-thread injection. **Client workaround shipped:** find a created thread by session-list **diff** (the new `source=phone` session), keep an in-memory `sessionId → chat_id` map (learned at creation + from incoming `phone.message`s) for reply routing, and inject by source (+ learned chat_id) rather than a parsed id. **Limitation:** for a thread the app didn't create *this* session (agent-created, another device, or after an app restart) `chat_id` is unknown until a message arrives while viewing it → its replies fall back to the home channel until then. **RESOLVED via the plugin (2026-06-29, per upstream-or-plugin policy):** the relay now exposes `GET /phone/threads` (`plugin/relay/session_store.py` reads the gateway store read-only → `[{session_id, chat_id, title}]`; `server.py` `handle_phone_threads`, bearer for the app / loopback for diag; 5 unit tests). The app (`RelayHttpClient.fetchPhoneThreads` → `ConnectionViewModel.phoneThreadChatIds` on every `auth.ok` → `ChatViewModel.seedThreadChatIds`, authoritative over the learned map) now routes replies correctly for **any** Thread — incl. ones it didn't create + after restart. Deployed + verified live. **Still-nice-to-have (lower priority): the upstream PR** to add `chat_id`/`session_key` to `/api/sessions` (the standard-path proper fix; the relay route then becomes redundant + the client prefers upstream when present).
|
||||
- **Threads as named/project conversations (Discord-parity — folds into multi-thread #8).** A stable *named* `chat_id` per project = a persistent, agent-reachable project Thread (Discord named-thread parity for "persist a session for a project"). Enables: the agent **opening** a new named Thread for a background job/topic (a relay/gateway "open thread" affordance + a `send_message`-adjacent tool); cron/job updates landing in their own Thread; and replying to a Thread from any surface (desktop CLI / dashboard) since it is just a gateway session. Also evaluate per-Thread profile binding (a project Thread uses the "work" profile — ties to profile=contact).
|
||||
@@ -965,7 +1030,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
|
||||
The gateway-platform model is the *correct + sufficient architecture* (the phone is a registered platform peer, so anything that routes to a platform — `send_message`, cron `deliver=`, channel directory, background jobs — can reach the phone). These are the concrete gaps between "architecturally a peer" and "I never open Discord":
|
||||
|
||||
- **Guaranteed background delivery (the biggest gap; no push today).** Delivery is **live-WSS-only** + a 24 h relay buffer; there is **no FCM/UnifiedPush** wake-up. If the app process is dead AND not holding a socket, a message waits for the next reconnect, and the relay buffer is ephemeral (lost on relay restart). Discord/Telegram feel instant because they wake the device via push even when the app is dead. Decide a **push transport**: **UnifiedPush/ntfy** (recommended — self-hostable, no Google dependency, upstream *already* ships an `ntfy` platform, on-brand for self-hosted) vs **FCM** (simplest UX but adds Play Services + a push relay; clashes with self-hosted ethos — at most the `googlePlay` flavor) vs **persistent foreground keep-alive service** holding the relay WSS (zero new infra, like `GatewayKeepAliveService`, but battery cost + Doze-fragile). Likely: UnifiedPush primary + foreground-keepalive fallback.
|
||||
- **Cron / background-job delivery is BROKEN** (already tracked above): `deliver=phone` standalone path → `Unknown platform: phone`. This is load-bearing for "receiver of crons/background jobs" — fix is required, not optional, for the replacement goal.
|
||||
- **Cron / background-job delivery needs live certification.** The standalone sender and channel-directory enumeration are implemented; certify `deliver=phone` against a deployed Relay and paired device, including reconnect delivery from the bounded offline queue.
|
||||
- **Agent-initiated multi-thread creation remains.** The app already renders N
|
||||
`source=phone` sessions, user-created Threads vary `chat_id`, and replies route
|
||||
by `chat_id` + `reply_to`. The missing parity is letting the agent open/name a
|
||||
@@ -974,7 +1039,7 @@ The gateway-platform model is the *correct + sufficient architecture* (the phone
|
||||
session store; the relay buffer is only the live/offline-delivery layer, not a
|
||||
parallel history database.
|
||||
- **Profile = contact mapping (new idea, fold in).** Multiple Hermes **profiles** (distinct agent personas/configs) could each be a distinct thread *source*/"contact" — DMing different agents. Maps cleanly onto the per-thread `chat_id` + source-attribution work; lets the app feel like a contact list of agents.
|
||||
- **Per-thread notification controls + deep-link (Discord-parity affordances).** Per-thread notification channels, mute/DND/quiet-hours (Phase 3 partially), and a notification that **deep-links into the exact thread** (tap → land in that conversation) so dipping in/out while multitasking is frictionless.
|
||||
- **Per-thread notification controls (Discord-parity affordances).** Exact-thread notification deep-linking is shipped. Remaining: per-thread notification channels and mute/DND/quiet-hours controls (Phase 3 partially).
|
||||
- **Agent-initiated rich content.** Agent → phone thread with **images/cards** (relay media infra + `InboundAttachmentCard`/`HermesCardBubble` already exist on the chat side — reuse). Inbound (phone → agent) reply media stays deferred (text-first), but outbound rich content is low-cost parity.
|
||||
- **In-thread "agent is working" indicator.** A typing/working state in the thread while the agent thinks/runs tools (Discord typing-dots parity) — the chat surface already has thinking indicators to reuse.
|
||||
|
||||
@@ -1240,8 +1305,27 @@ When the answer becomes clearer, this section becomes either an ADR in `docs/dec
|
||||
|
||||
## Smaller deferred items
|
||||
|
||||
- **Certify the preferred CUA Driver backend (ADR 56).** The canonical-runtime
|
||||
probe, bounded adapter, server-owned control-session envelope, per-session
|
||||
grant state, local engine/status controls, telemetry-off process environment,
|
||||
and Hermes snapshot-token primitives now exist. Before graduating the engine,
|
||||
finish end-to-end enforcement of app/display/folder scopes and sensitive
|
||||
pixel/accessibility denial or redaction, harden the grant-bridge ACL and nonce
|
||||
lifecycle, and complete live Windows certification proving the physical cursor and
|
||||
foreground app stay unchanged, stale or cross-window tokens fail, two remote
|
||||
control sessions receive isolated animated cursors, and foreground escalation
|
||||
never happens implicitly. Exercise revoke on grant expiry, disconnect,
|
||||
re-pair, policy downgrade, emergency stop, Windows-session change, and daemon
|
||||
shutdown. The explicit local CUA install/update surface now verifies upstream
|
||||
manifest identity and installer SHA-256; add Windows publisher verification
|
||||
when upstream signs the installer. Keep raw CUA tools, configuration,
|
||||
recording, replay, and JavaScript outside the remote agent surface.
|
||||
Remove the temporary Windows readiness/health split once
|
||||
[trycua/cua#3103](https://github.com/trycua/cua/issues/3103) ships in the
|
||||
supported CUA range; restore a mandatory health gate only if the upstream
|
||||
probe is bounded and cannot leave UI Automation falsely busy.
|
||||
- **MediaProjection consent flow** — wired in MainActivity (2026-04-12), needs end-to-end test on a real device
|
||||
- **WorkManager upgrade for auto-disable timer** — currently a coroutine `Job + delay()` in `AutoDisableWorker.kt`; documented at top of file. Upgrade when androidx.work joins the classpath
|
||||
- **WorkManager upgrade for timed screen-access expiry notification** — authority already fails closed from persisted absolute expiry after restart; the prompt notification is currently a coroutine `Job + delay()` coordinated by `BridgeSafetyManager` / `AutoDisableWorker`. Upgrade only if background notification timing becomes important after androidx.work joins the classpath.
|
||||
- **Wave 3 voice-bridge multi-turn confirmation** — currently a 5s TTS countdown with cancel; conversational confirmation is the follow-up
|
||||
- **LLM client wiring for `android_navigate`** — `_default_vision_model` is stubbed; production swap to a real Anthropic/OpenAI vision client
|
||||
- **Real screenshots of each flavor's a11y permission dialog** — for `user-docs/guide/release-tracks.md`
|
||||
|
||||
+31
-2
@@ -1,5 +1,8 @@
|
||||
import java.util.Properties
|
||||
|
||||
fun String.asBuildConfigString(): String =
|
||||
"\"" + replace("\\", "\\\\").replace("\"", "\\\"") + "\""
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -9,6 +12,10 @@ plugins {
|
||||
|
||||
val supportedHermesDevAbis = setOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
|
||||
val hermesDevAbi = providers.gradleProperty("hermes.devAbi").orNull
|
||||
val candidateKind = providers.gradleProperty("candidate.kind").orElse("review").get()
|
||||
val candidateLabel = providers.gradleProperty("candidate.label").orElse("Local review").get()
|
||||
val candidateSourceRef = providers.gradleProperty("candidate.sourceRef").orElse("local").get()
|
||||
val candidateSourceSha = providers.gradleProperty("candidate.sourceSha").orElse("unknown").get()
|
||||
hermesDevAbi?.let { requestedAbi ->
|
||||
require(requestedAbi in supportedHermesDevAbis) {
|
||||
"Unsupported hermes.devAbi '$requestedAbi'. Expected one of: " +
|
||||
@@ -65,6 +72,11 @@ android {
|
||||
|
||||
// Feature flags — DEV_MODE enables all experimental features in debug builds
|
||||
buildConfigField("boolean", "DEV_MODE", "false")
|
||||
buildConfigField("boolean", "CANDIDATE_BUILD", "false")
|
||||
buildConfigField("String", "CANDIDATE_KIND", "".asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_LABEL", "".asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_SOURCE_REF", "".asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_SOURCE_SHA", "".asBuildConfigString())
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -161,6 +173,18 @@ android {
|
||||
signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
create("candidate") {
|
||||
initWith(getByName("release"))
|
||||
applicationIdSuffix = ".candidate"
|
||||
versionNameSuffix = "-candidate"
|
||||
isDebuggable = false
|
||||
matchingFallbacks += listOf("release")
|
||||
buildConfigField("boolean", "CANDIDATE_BUILD", "true")
|
||||
buildConfigField("String", "CANDIDATE_KIND", candidateKind.asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_LABEL", candidateLabel.asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_SOURCE_REF", candidateSourceRef.asBuildConfigString())
|
||||
buildConfigField("String", "CANDIDATE_SOURCE_SHA", candidateSourceSha.asBuildConfigString())
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -319,11 +343,13 @@ dependencies {
|
||||
|
||||
// Coil 3 — async image loading for generated images in chat
|
||||
implementation(libs.coil.compose)
|
||||
implementation(libs.coil.gif)
|
||||
implementation(libs.coil.network.okhttp)
|
||||
implementation(libs.exifinterface)
|
||||
|
||||
// QR Code scanning (ML Kit + CameraX)
|
||||
implementation(libs.mlkit.barcode)
|
||||
implementation(libs.zxing.core)
|
||||
implementation(libs.camera.core)
|
||||
implementation(libs.camera.camera2)
|
||||
implementation(libs.camera.lifecycle)
|
||||
@@ -364,14 +390,17 @@ dependencies {
|
||||
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
|
||||
testImplementation(libs.konsist)
|
||||
androidTestImplementation(libs.compose.ui.test.junit4)
|
||||
// On-device vanilla-Gateway contract tests exercise the production
|
||||
// Dashboard ticket + WebSocket stack over real loopback sockets.
|
||||
androidTestImplementation(libs.okhttp.mockwebserver)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
debugImplementation(libs.compose.ui.test.manifest)
|
||||
|
||||
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
|
||||
// Renders real composables on the JVM at an exact canvas — no device, no
|
||||
// status bar, no clipping. See StoreScreenshotTest.
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.71.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.71.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.72.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.72.0")
|
||||
testImplementation(libs.compose.ui.test.junit4)
|
||||
testImplementation(libs.compose.ui.test.manifest)
|
||||
testImplementation("androidx.test.ext:junit:1.3.0")
|
||||
|
||||
-2
@@ -6,8 +6,6 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertDoesNotExist
|
||||
import androidx.compose.ui.test.assertExists
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Opt-in physical-device/emulator adapter for the shared Python fixture.
|
||||
*
|
||||
* Pass `-e gatewayFixtureBaseUrl http://127.0.0.1:8765` after exposing the
|
||||
* host fixture with `adb reverse`. With no argument this test alone is skipped;
|
||||
* the embedded regression remains fully standalone.
|
||||
*/
|
||||
class GatewayExternalFixtureInstrumentedTest {
|
||||
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
|
||||
private var gatewayScope: CoroutineScope? = null
|
||||
private var gatewayClient: GatewayChatClient? = null
|
||||
private var viewModel: ChatViewModel? = null
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
viewModel?.updateGatewayClient(null)
|
||||
gatewayClient?.shutdown()
|
||||
gatewayScope?.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActivate_externalFixtureRecoversFromAuthoritativeHttpHistory() {
|
||||
val fixtureBaseUrl = InstrumentationRegistry.getArguments()
|
||||
.getString(ARG_FIXTURE_BASE_URL)
|
||||
?.trim()
|
||||
?.trimEnd('/')
|
||||
assumeTrue(
|
||||
"Pass -e $ARG_FIXTURE_BASE_URL <url> to run the external fixture lane",
|
||||
!fixtureBaseUrl.isNullOrBlank(),
|
||||
)
|
||||
requireNotNull(fixtureBaseUrl)
|
||||
|
||||
val okHttp = OkHttpClient.Builder()
|
||||
.callTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
val initialState = readFixtureJson(okHttp, "$fixtureBaseUrl/__fixture__/state")
|
||||
assertEquals("terminal_gap_activate", initialState["scenario"]?.jsonString())
|
||||
assertEquals("1", initialState["remaining_turns"].toString())
|
||||
val dashboard = DashboardApiClient(fixtureBaseUrl, okHttp)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard,
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = scope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val vm = ChatViewModel().also {
|
||||
// Deliberately omit HermesApiClient: this lane has no API-server
|
||||
// fallback surface, so a passing turn proves Gateway ownership.
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
|
||||
dashboard.getSessionMessages(sessionId, profile, mode)
|
||||
}
|
||||
it.updateGatewayClient(gateway)
|
||||
it.setChatVisible(true)
|
||||
}.also { viewModel = it }
|
||||
|
||||
compose.setContent {
|
||||
val messages by vm.messages.collectAsStateWithLifecycle()
|
||||
val streaming by vm.isStreaming.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("external-contract-transcript")) {
|
||||
Text(
|
||||
text = if (streaming) "STREAMING" else "IDLE",
|
||||
modifier = Modifier.testTag("external-stream-state"),
|
||||
)
|
||||
messages.forEach { message ->
|
||||
Text(
|
||||
text = "${message.role.name}:${message.content}",
|
||||
modifier = Modifier.testTag("external-message-${message.id}"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
vm.sendMessage("Exercise terminal gap.")
|
||||
|
||||
compose.waitUntil(10_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gateway.hasActiveTurn() &&
|
||||
handler.messages.value.any {
|
||||
it.role == MessageRole.ASSISTANT && it.content == AUTHORITATIVE_ANSWER
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithTag("external-contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("external-stream-state").assertTextEquals("IDLE")
|
||||
compose.onAllNodesWithText("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
.assertCountEquals(1)
|
||||
|
||||
val messages = handler.messages.value
|
||||
assertEquals(
|
||||
1,
|
||||
messages.count {
|
||||
it.role == MessageRole.ASSISTANT && it.content == AUTHORITATIVE_ANSWER
|
||||
},
|
||||
)
|
||||
assertEquals(1, messages.count { it.role == MessageRole.USER })
|
||||
assertFalse(messages.any { it.isStreaming || it.isThinkingStreaming })
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
|
||||
val evidence = readFixtureJson(okHttp, "$fixtureBaseUrl/__fixture__/evidence")
|
||||
assertEquals("terminal_gap_activate", evidence["scenario"]?.jsonString())
|
||||
val entries = evidence["entries"] as? JsonArray ?: JsonArray(emptyList())
|
||||
assertEquals(1, entries.rpcCount("prompt.submit"))
|
||||
assertEquals(1, entries.rpcCount("session.activate"))
|
||||
|
||||
val state = readFixtureJson(okHttp, "$fixtureBaseUrl/__fixture__/state")
|
||||
assertEquals("terminal_gap_activate", state["scenario"]?.jsonString())
|
||||
assertEquals("2", state["history_rows"].toString())
|
||||
}
|
||||
|
||||
private fun readFixtureJson(client: OkHttpClient, url: String): JsonObject {
|
||||
val request = Request.Builder().url(url).get().build()
|
||||
return client.newCall(request).execute().use { response ->
|
||||
check(response.isSuccessful) { "fixture HTTP ${response.code}" }
|
||||
Json.parseToJsonElement(response.body.string()).jsonObject
|
||||
}
|
||||
}
|
||||
|
||||
private fun JsonArray.rpcCount(method: String): Int = count { element ->
|
||||
val entry = element as? JsonObject ?: return@count false
|
||||
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
||||
}
|
||||
|
||||
private fun kotlinx.serialization.json.JsonElement.jsonString(): String? =
|
||||
(this as? JsonPrimitive)?.contentOrNull
|
||||
|
||||
private companion object {
|
||||
const val ARG_FIXTURE_BASE_URL = "gatewayFixtureBaseUrl"
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val AUTHORITATIVE_ANSWER = "Persisted after the socket gap."
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
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.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okhttp3.mockwebserver.Dispatcher
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okhttp3.mockwebserver.RecordedRequest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* On-device contract coverage for issue #365.
|
||||
*
|
||||
* This deliberately uses the production [GatewayChatClient], [ChatViewModel],
|
||||
* and [ChatHandler]. [DeviceGatewayFixture] supplies only the upstream HTTP/WSS
|
||||
* boundary, so Android main-looper dispatch and Compose collection are real.
|
||||
*/
|
||||
class GatewayForegroundRecoveryInstrumentedTest {
|
||||
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
|
||||
private lateinit var fixture: AndroidGatewayContractFixture
|
||||
private lateinit var gatewayScope: CoroutineScope
|
||||
private lateinit var gatewayClient: GatewayChatClient
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var serverSocket: WebSocket
|
||||
|
||||
@Volatile
|
||||
private var persistedHistory: List<MessageItem> = emptyList()
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = okHttp,
|
||||
),
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
viewModel = ChatViewModel().also {
|
||||
it.initialize(
|
||||
HermesApiClient(fixture.server.url("/").toString(), "fixture-key"),
|
||||
handler,
|
||||
)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoader { Result.success(persistedHistory) }
|
||||
it.updateGatewayClient(gatewayClient)
|
||||
it.setChatVisible(true)
|
||||
}
|
||||
|
||||
compose.setContent {
|
||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("contract-transcript")) {
|
||||
Text(
|
||||
text = if (streaming) "STREAMING" else "IDLE",
|
||||
modifier = Modifier.testTag("stream-state"),
|
||||
)
|
||||
messages.forEach { message ->
|
||||
Text(
|
||||
text = "${message.role.name}:${message.content}",
|
||||
modifier = Modifier.testTag("message-${message.id}"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(runBlocking { gatewayClient.prewarmAwait(STORED_SESSION_ID) })
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
fixture.awaitRpc("session.resume")
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActivate_recoversForegroundTurnWithoutNavigationOrCrossSessionLeak() {
|
||||
viewModel.sendMessage("Run a long foreground task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
|
||||
// A multiplexed Gateway shares one socket. Foreign-session events must
|
||||
// neither render nor settle the visible turn.
|
||||
serverSocket.send(fixture.event("message.start", null, FOREIGN_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", FOREIGN_ANSWER) },
|
||||
FOREIGN_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", FOREIGN_ANSWER) },
|
||||
FOREIGN_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"tool.start",
|
||||
buildJsonObject {
|
||||
put("tool_id", "tool-foreground")
|
||||
put("name", "terminal")
|
||||
},
|
||||
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")
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
assertFalse(handler.messages.value.any { it.content.contains(FOREIGN_ANSWER) })
|
||||
|
||||
// Exercise the real Activity collection boundary while the turn is
|
||||
// still live. STARTED models a covered/backgrounded activity without
|
||||
// destroying the test host; returning to RESUMED must preserve the
|
||||
// same turn and transcript without navigation.
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
// The server finishes while this socket is detached. The replacement
|
||||
// socket cannot replay message.complete; exact-session activation
|
||||
// reports running=false and history is now authoritative.
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.recoveryRunning = false
|
||||
serverSocket.close(1011, "fixture foreground gap")
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
fixture.awaitRpc("session.activate")
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
|
||||
val visible = handler.messages.value
|
||||
assertEquals(1, visible.size)
|
||||
assertEquals(AUTHORITATIVE_ANSWER, visible.single().content)
|
||||
assertFalse(visible.single().isStreaming)
|
||||
assertFalse(visible.any { it.content.contains(PARTIAL_ANSWER) })
|
||||
assertFalse(visible.any { it.content.contains(FOREIGN_ANSWER) })
|
||||
assertEquals(
|
||||
"history catch-up must not duplicate the authoritative assistant row",
|
||||
1,
|
||||
compose.onAllNodesWithTag("message-$PERSISTED_ANSWER_ID").fetchSemanticsNodes().size,
|
||||
)
|
||||
assertEquals(
|
||||
"the prompt must never be resubmitted during recovery",
|
||||
1,
|
||||
fixture.rpcCount("prompt.submit"),
|
||||
)
|
||||
assertEquals(
|
||||
"the exact live session should be activated once",
|
||||
1,
|
||||
fixture.rpcCount("session.activate"),
|
||||
)
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
const val FOREIGN_SESSION_ID = "live-foreign"
|
||||
const val PERSISTED_ANSWER_ID = "persisted-foreground-answer"
|
||||
const val PARTIAL_ANSWER = "Partial foreground answer"
|
||||
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
|
||||
const val FOREIGN_ANSWER = "Wrong session content"
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimal real-socket implementation of the vanilla Gateway contract used above. */
|
||||
internal class AndroidGatewayContractFixture {
|
||||
val server = MockWebServer()
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val sockets = LinkedBlockingQueue<WebSocket>()
|
||||
private val allSockets = ConcurrentLinkedQueue<WebSocket>()
|
||||
private val rpcLog = ConcurrentLinkedQueue<Pair<String, JsonObject>>()
|
||||
private val requestPaths = ConcurrentLinkedQueue<String>()
|
||||
private val ticketCount = AtomicInteger(0)
|
||||
|
||||
@Volatile
|
||||
var recoveryRunning = false
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
allSockets.add(webSocket)
|
||||
webSocket.send(event("gateway.ready", null, null))
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
val frame = json.parseToJsonElement(text) as? JsonObject ?: return
|
||||
val method = (frame["method"] as? JsonPrimitive)?.contentOrNull ?: return
|
||||
val id = (frame["id"] as? JsonPrimitive)?.contentOrNull?.toLongOrNull() ?: return
|
||||
val params = frame["params"] as? JsonObject ?: JsonObject(emptyMap())
|
||||
rpcLog.add(method to params)
|
||||
|
||||
val result = when (method) {
|
||||
"session.resume" -> sessionSnapshot("fixture-live-1")
|
||||
"session.activate" -> sessionSnapshot(
|
||||
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "fixture-live-1",
|
||||
)
|
||||
"prompt.submit", "session.interrupt" -> buildJsonObject { put("ok", true) }
|
||||
else -> JsonObject(emptyMap())
|
||||
}
|
||||
webSocket.send(
|
||||
buildJsonObject {
|
||||
put("jsonrpc", "2.0")
|
||||
put("id", id)
|
||||
put("result", result)
|
||||
}.toString(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
server.dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse {
|
||||
val path = request.path.orEmpty()
|
||||
requestPaths.add(path)
|
||||
return when {
|
||||
path.startsWith("/api/auth/ws-ticket") -> MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
|
||||
)
|
||||
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
}
|
||||
server.start()
|
||||
}
|
||||
|
||||
private fun sessionSnapshot(sessionId: String): JsonObject = buildJsonObject {
|
||||
put("session_id", sessionId)
|
||||
put("running", recoveryRunning)
|
||||
put("status", if (recoveryRunning) "streaming" else "idle")
|
||||
put("info", buildJsonObject { put("profile_name", "default") })
|
||||
}
|
||||
|
||||
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
|
||||
buildJsonObject {
|
||||
put("jsonrpc", "2.0")
|
||||
put("method", "event")
|
||||
put("params", buildJsonObject {
|
||||
put("type", type)
|
||||
payload?.let { put("payload", it) }
|
||||
sessionId?.let { put("session_id", it) }
|
||||
})
|
||||
}.toString()
|
||||
|
||||
fun awaitServerSocket(): WebSocket =
|
||||
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
|
||||
|
||||
fun awaitRpc(method: String): JsonObject {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
|
||||
Thread.sleep(20)
|
||||
}
|
||||
error("Gateway RPC $method not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
|
||||
fun shutdown() {
|
||||
allSockets.forEach { socket -> runCatching { socket.close(1001, "teardown") } }
|
||||
runCatching { server.shutdown() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher_candidate"
|
||||
android:label="Hermes Candidate"
|
||||
android:roundIcon="@mipmap/ic_launcher_candidate_round"
|
||||
tools:replace="android:icon,android:label" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/candidate_icon_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/candidate_icon_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="candidate_icon_background">#FFB300</color>
|
||||
</resources>
|
||||
@@ -1 +1 @@
|
||||
Long sessions now retain complete history beyond Hermes' latest-500 default, keeping edit, retry, sharing, and recovery anchors stable. Gateway submit rejections preserve the server's message without unintended SSE fallback, while event envelopes and edit-and-regenerate requests follow current upstream contracts.
|
||||
Create and save custom themes with full palette and shape controls. Shapes now apply consistently throughout the app. All Profiles sessions switch to their owning agent and survive language changes with the correct header, icon, and transcript. Gateway chats recover when a terminal frame is missed, persistent connection notifications relocalize without reconnecting, and Relay URLs normalize correctly from base, /ws, or /health forms.
|
||||
|
||||
@@ -1 +1 @@
|
||||
新增可在界面中漫游的 Petdex 浮动宠物、由已安装 Hermes 插件提供的安全原生页面,以及支持本地“Hey Hermes”的可选 Android 数字助理。本次更新还新增俄语,并改进语音恢复、路线切换、实时聊天稳定性和宠物移动。
|
||||
创建并保存带完整配色和形状控制的自定义主题。形状现在会一致应用到整个应用。通过“所有配置文件”选择会话时会切换到其所属智能体,并在更改语言后保留正确的标题、图标和对话内容。Gateway 漏掉终止帧时可恢复聊天,持久连接通知会随语言更新而无需重连,Relay 基础、/ws 与 /health 地址也会正确规范化。
|
||||
|
||||
@@ -1,5 +1,145 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.12.0",
|
||||
"title": "Themes and identity that stay put",
|
||||
"date": "2026-08-21",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Make the app yours",
|
||||
"bullets": [
|
||||
"Create and save custom themes with editable palette roles, Light or Dark ownership, shape, and a live chat preview.",
|
||||
"Apply Soft, Balanced, or Sharp styling consistently across chat, settings, sheets, dialogs, terminal, voice, and Bridge."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Keep the right agent active",
|
||||
"bullets": [
|
||||
"Selecting a session from All Profiles activates its owning agent with the correct header, avatar, transcript, draft, and routing.",
|
||||
"Language changes preserve the exact active profile and session while relocalizing the persistent connection notification without reconnecting."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Recover cleanly",
|
||||
"bullets": [
|
||||
"Settle and reconcile Gateway turns when a terminal completion frame is missed without resubmitting through fallback transport.",
|
||||
"Normalize Relay base, /ws, and /health endpoint forms without producing duplicate route segments."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.11.0",
|
||||
"title": "Access with clear boundaries",
|
||||
"date": "2026-08-20",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Choose what Bridge can do",
|
||||
"bullets": [
|
||||
"Use read-only, read-and-confirm, or custom capability presets for the active connection in sideload builds.",
|
||||
"Allow screen inspection and control for a bounded period or explicitly keep access unlimited."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Recover without losing context",
|
||||
"bullets": [
|
||||
"Keep stored-session failures visible with route-aware details and clear retry or dismiss actions.",
|
||||
"Insert newlines across more software keyboards and retain Stopped status when answer recovery is cancelled."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Use less power while idle",
|
||||
"bullets": [
|
||||
"Pause invisible Sphere, waveform, and drawer animation loops when no motion is needed.",
|
||||
"Attach capture surfaces only for requested frames and release audio or wake-lock resources at their lifecycle boundaries."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.10.0",
|
||||
"title": "Chat that stays put",
|
||||
"date": "2026-08-18",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Watch replies take shape",
|
||||
"bullets": [
|
||||
"Render paragraphs, lists, links, fenced code, and tables incrementally without replacing the message at completion.",
|
||||
"Keep bottom-follow smooth while intentional scrollback remains exactly where you left it."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Pick up where you left off",
|
||||
"bullets": [
|
||||
"Resume the visible Hermes session automatically after returning from another app.",
|
||||
"Restore composer text, quote or edit context, and pending attachments in the correct conversation after an app restart."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Review before sending",
|
||||
"bullets": [
|
||||
"Turn large pastes into compact text attachments while preserving compatible fallback delivery.",
|
||||
"Use Return on the software keyboard while the dedicated composer button remains the Send action."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.9.1",
|
||||
"title": "Profile identity that sticks",
|
||||
"date": "2026-08-16",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Identity follows the right scope",
|
||||
"bullets": [
|
||||
"Change shared avatars from Android with automatic orientation, resizing, and safe conversion to the Hermes profile-asset contract.",
|
||||
"Select upstream animated pets that follow the Hermes profile while phone-only animated icons, local avatar overrides, and Sphere skins stay local."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Profile setup stays explicit",
|
||||
"bullets": [
|
||||
"Create profiles with clear shared, copied, or isolated authentication choices and see partial setup outcomes.",
|
||||
"Named-profile sessions and profile drafts fail closed when Hermes cannot confirm their owner."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Safer Gateway operations",
|
||||
"bullets": [
|
||||
"Attachments, rewinds, recovery, model-consent changes, and hosted sign-in now follow stricter upstream contracts.",
|
||||
"Finite schedules, bounded reset evidence, and host resource warnings make consequential actions easier to review."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.9.0",
|
||||
"title": "Better sessions, reactions, and voice",
|
||||
"date": "2026-08-14",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Sessions keep their identity",
|
||||
"bullets": [
|
||||
"Browse one profile or all profiles, customize sorting and filters, and optionally group sessions by project, recency, status, or profile.",
|
||||
"Cross-profile sessions hydrate, resume, and send with their owning agent without changing the global profile selection; New Chat in All Profiles uses the default profile."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Conversation controls stay attached",
|
||||
"bullets": [
|
||||
"Reactions pin to durable rows on both user and assistant messages.",
|
||||
"Vanilla Hermes voice stays on the authenticated Gateway instead of requiring the optional API fallback."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Context without clutter",
|
||||
"bullets": [
|
||||
"Session rows show profile, project, branch, and pull-request context when Hermes supplies it, while the default view remains ungrouped.",
|
||||
"The session drawer restores secondary actions in All Profiles and closes when you tap outside it."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.8.1",
|
||||
"title": "Complete, reliable transcripts",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
v1.8.1 - Complete, reliable transcripts
|
||||
v1.12.0 - Themes and identity that stay put
|
||||
|
||||
* Keep complete history in long sessions beyond Hermes' latest-500 default.
|
||||
* Preserve stable edit, retry, sharing, and recovery anchors while paging history.
|
||||
* Show authoritative Gateway rejection messages without an unintended fallback.
|
||||
* Reconcile Gateway events and edit-and-regenerate requests with current upstream contracts.
|
||||
* Create and save custom themes with full palette and shape controls.
|
||||
* Apply Soft, Balanced, or Sharp styling consistently throughout the app.
|
||||
* Switch All Profiles sessions with the correct owning agent, icon, and transcript.
|
||||
* Preserve the active profile and session through app-language changes.
|
||||
* Recover Gateway chats when a terminal completion frame is missed.
|
||||
* Accept Relay base, /ws, and /health endpoint forms without invalid routes.
|
||||
|
||||
@@ -7,6 +7,8 @@ import android.os.Build
|
||||
import coil3.ImageLoader
|
||||
import coil3.PlatformContext
|
||||
import coil3.SingletonImageLoader
|
||||
import coil3.gif.AnimatedImageDecoder
|
||||
import coil3.gif.GifDecoder
|
||||
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||
import coil3.request.crossfade
|
||||
import com.hermesandroid.relay.bridge.UnattendedAccessManager
|
||||
@@ -38,7 +40,14 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
*/
|
||||
override fun newImageLoader(context: PlatformContext): ImageLoader =
|
||||
ImageLoader.Builder(context)
|
||||
.components { add(OkHttpNetworkFetcherFactory()) }
|
||||
.components {
|
||||
add(OkHttpNetworkFetcherFactory())
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
add(AnimatedImageDecoder.Factory())
|
||||
} else {
|
||||
add(GifDecoder.Factory())
|
||||
}
|
||||
}
|
||||
.crossfade(true)
|
||||
.build()
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
/**
|
||||
@@ -226,6 +228,7 @@ class BridgeStatusReporter(
|
||||
val destructiveVerbsCount = safetySnapshot?.destructiveVerbs?.size ?: 0
|
||||
val autoDisableMinutes = safetySnapshot?.autoDisableMinutes ?: 0
|
||||
val autoDisableAtMs = safetyManager?.autoDisableAtMs?.value
|
||||
val capabilityPolicy = safetyManager?.activeCapabilityPolicy?.value
|
||||
|
||||
val deviceName = Build.MODEL ?: "unknown"
|
||||
|
||||
@@ -281,6 +284,33 @@ class BridgeStatusReporter(
|
||||
put("auto_disable_at_ms", autoDisableAtMs)
|
||||
}
|
||||
})
|
||||
put("capabilities", buildJsonObject {
|
||||
put("schema_version", capabilityPolicy?.schemaVersion ?: 1)
|
||||
put("permanent", buildJsonArray {
|
||||
capabilityPolicy?.permanentGrants
|
||||
?.sortedBy { it.wireId }
|
||||
?.forEach { add(it.wireId) }
|
||||
})
|
||||
put("timed", buildJsonObject {
|
||||
capabilityPolicy?.timedExpiriesMs
|
||||
?.filterValues {
|
||||
it != com.hermesandroid.relay.bridge.BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
|
||||
}
|
||||
?.toSortedMap(compareBy { it.wireId })
|
||||
?.forEach { (capability, expiry) ->
|
||||
put(capability.wireId, expiry)
|
||||
}
|
||||
})
|
||||
put("unlimited", buildJsonArray {
|
||||
capabilityPolicy?.timedExpiriesMs
|
||||
?.filterValues {
|
||||
it == com.hermesandroid.relay.bridge.BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
|
||||
}
|
||||
?.keys
|
||||
?.sortedBy { it.wireId }
|
||||
?.forEach { add(it.wireId) }
|
||||
})
|
||||
})
|
||||
|
||||
// v0.4.1: unattended-access state so the agent can decide
|
||||
// upfront whether commands will reach apps with the screen
|
||||
|
||||
+5
-2
@@ -41,7 +41,7 @@ import kotlinx.coroutines.launch
|
||||
*
|
||||
* The Android system toggle in `Settings → Accessibility → Hermes-Relay` is
|
||||
* the hard switch — if it's off we never receive events. On top of that the
|
||||
* user can flip a soft master in Settings (`bridge_master_enabled`); when
|
||||
* user can flip a soft master in Settings (`bridge_master_enabled_v2`); when
|
||||
* that's false we still run (Android requires it to stay connected) but we
|
||||
* refuse to execute commands. [isMasterEnabled] is a StateFlow the UI
|
||||
* observes and the command handler checks before dispatching actions.
|
||||
@@ -61,7 +61,9 @@ class HermesAccessibilityService : AccessibilityService() {
|
||||
private const val TAG = "HermesA11yService"
|
||||
|
||||
/** Master-enable DataStore key — read + toggled from Settings UI. */
|
||||
val KEY_BRIDGE_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
|
||||
val KEY_BRIDGE_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled_v2")
|
||||
private val KEY_LEGACY_BRIDGE_MASTER_ENABLED =
|
||||
booleanPreferencesKey("bridge_master_enabled")
|
||||
|
||||
/**
|
||||
* Static reference to the live service instance, or null if the
|
||||
@@ -92,6 +94,7 @@ class HermesAccessibilityService : AccessibilityService() {
|
||||
suspend fun setMasterEnabled(context: Context, enabled: Boolean) {
|
||||
context.applicationContext.relayDataStore.edit { prefs ->
|
||||
prefs[KEY_BRIDGE_MASTER_ENABLED] = enabled
|
||||
prefs[KEY_LEGACY_BRIDGE_MASTER_ENABLED] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import android.os.HandlerThread
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
import android.view.WindowManager
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
@@ -152,12 +153,14 @@ class ScreenCapture(
|
||||
// 13 and below but breaks the second /screenshot request on 14+.
|
||||
//
|
||||
// Fix: keep the VirtualDisplay + ImageReader + HandlerThread alive
|
||||
// across captures, keyed by the MediaProjection instance. Rebuild only
|
||||
// when the projection reference changes (fresh consent grant) or the
|
||||
// dimensions change (orientation flip). The ImageReader's
|
||||
// setOnImageAvailableListener drains the buffer continuously; each
|
||||
// captureAndUpload() installs a one-shot [pendingCapture] callback
|
||||
// that fires on the next frame.
|
||||
// across captures, keyed by the MediaProjection instance. The reader
|
||||
// surface is attached only while a request is waiting, then detached so
|
||||
// SurfaceFlinger is not continuously mirroring into a drain-and-drop loop.
|
||||
// Rebuild only when the projection reference changes (fresh consent
|
||||
// grant). Orientation/size changes resize the existing VirtualDisplay and
|
||||
// replace its detached ImageReader, preserving Android 14's single-create
|
||||
// contract. Each captureAndUpload() installs a one-shot [pendingCapture]
|
||||
// callback that fires on the next attached frame.
|
||||
//
|
||||
// Thread model:
|
||||
// - `captureMutex` serializes concurrent captureAndUpload() calls
|
||||
@@ -273,6 +276,7 @@ class ScreenCapture(
|
||||
*/
|
||||
fun releaseCache() {
|
||||
synchronized(cacheLock) {
|
||||
runCatching { cachedDisplay?.setSurface(null) }
|
||||
runCatching { cachedDisplay?.release() }
|
||||
runCatching { cachedReader?.close() }
|
||||
runCatching { cachedThread?.quitSafely() }
|
||||
@@ -326,6 +330,7 @@ class ScreenCapture(
|
||||
}
|
||||
|
||||
return try {
|
||||
attachCaptureSurface()
|
||||
val timeoutMs = captureTimeoutMs()
|
||||
kotlinx.coroutines.withTimeout(timeoutMs) { deferred.await() }
|
||||
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
|
||||
@@ -336,6 +341,24 @@ class ScreenCapture(
|
||||
} catch (t: Throwable) {
|
||||
pendingCaptureRef.compareAndSet(deferred, null)
|
||||
throw t
|
||||
} finally {
|
||||
detachCaptureSurface()
|
||||
}
|
||||
}
|
||||
|
||||
private fun attachCaptureSurface() {
|
||||
synchronized(cacheLock) {
|
||||
val display = cachedDisplay ?: throw IOException("capture display unavailable")
|
||||
val surface = cachedReader?.surface ?: throw IOException("capture surface unavailable")
|
||||
display.setSurface(surface)
|
||||
Log.d(TAG, "screen capture surface attached for pending frame")
|
||||
}
|
||||
}
|
||||
|
||||
private fun detachCaptureSurface() {
|
||||
synchronized(cacheLock) {
|
||||
runCatching { cachedDisplay?.setSurface(null) }
|
||||
.onFailure { Log.v(TAG, "screen capture surface detach failed: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,11 +373,12 @@ class ScreenCapture(
|
||||
|
||||
/**
|
||||
* Build (or reuse) the cached VirtualDisplay + ImageReader + HandlerThread
|
||||
* for this projection. Rebuilds when:
|
||||
* for this projection. Rebuilds the display when:
|
||||
*
|
||||
* - The projection reference has changed (new consent grant landed)
|
||||
* - The captured dimensions don't match the current display (orientation
|
||||
* flipped, foldable opened/closed, display switched)
|
||||
*
|
||||
* Geometry changes resize that existing display and replace its detached
|
||||
* consumer surface, as required for Android 14's one-display-per-token rule.
|
||||
*
|
||||
* Must be called while [captureMutex] is held so the cached fields
|
||||
* aren't racing another capture.
|
||||
@@ -368,52 +392,41 @@ class ScreenCapture(
|
||||
synchronized(cacheLock) {
|
||||
val projectionChanged = cachedProjection !== projection
|
||||
val dimensionsChanged = width != cachedWidth || height != cachedHeight
|
||||
if (!projectionChanged && !dimensionsChanged && cachedDisplay != null && cachedReader != null) {
|
||||
val densityChanged = densityDpi != cachedDensity
|
||||
if (!projectionChanged && !dimensionsChanged && !densityChanged &&
|
||||
cachedDisplay != null && cachedReader != null
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Android 14 permits only one createVirtualDisplay() call per
|
||||
// MediaProjection. Resize the existing display and replace only
|
||||
// its detached consumer surface when the device geometry changes.
|
||||
if (!projectionChanged && cachedDisplay != null && cachedThread != null) {
|
||||
val display = cachedDisplay ?: return
|
||||
val thread = cachedThread ?: return
|
||||
val handler = cachedHandler ?: Handler(thread.looper)
|
||||
display.setSurface(null)
|
||||
runCatching { cachedReader?.close() }
|
||||
display.resize(width, height, densityDpi)
|
||||
cachedReader = createImageReader(width, height, handler)
|
||||
cachedHandler = handler
|
||||
cachedWidth = width
|
||||
cachedHeight = height
|
||||
cachedDensity = densityDpi
|
||||
Log.i(TAG, "screen capture pipeline resized ${width}x$height dpi=$densityDpi")
|
||||
return
|
||||
}
|
||||
|
||||
// Tear down any stale cache before building fresh.
|
||||
runCatching { cachedDisplay?.setSurface(null) }
|
||||
runCatching { cachedDisplay?.release() }
|
||||
runCatching { cachedReader?.close() }
|
||||
runCatching { cachedThread?.quitSafely() }
|
||||
|
||||
val thread = HandlerThread("HermesScreenCapture").apply { start() }
|
||||
val handler = Handler(thread.looper)
|
||||
val reader = ImageReader.newInstance(
|
||||
width, height, PixelFormat.RGBA_8888, MAX_IMAGES
|
||||
)
|
||||
|
||||
// Persistent listener — fires on every frame the VirtualDisplay
|
||||
// produces. If there's a pending capture request, we encode
|
||||
// the frame and complete it; otherwise we just drain the image
|
||||
// so the ImageReader buffer stays clear.
|
||||
reader.setOnImageAvailableListener({ r ->
|
||||
val waiter = pendingCaptureRef.get()
|
||||
if (waiter == null || !waiter.isActive) {
|
||||
// Drain-and-drop — nobody's asking for a screenshot
|
||||
// right now but frames are still arriving.
|
||||
runCatching { r.acquireLatestImage() }.getOrNull()?.close()
|
||||
return@setOnImageAvailableListener
|
||||
}
|
||||
var image: Image? = null
|
||||
try {
|
||||
image = r.acquireLatestImage()
|
||||
?: return@setOnImageAvailableListener
|
||||
val png = imageToPngBytes(image, width, height)
|
||||
// Only complete the EXACT deferred we latched onto,
|
||||
// so a stale listener firing after supersession doesn't
|
||||
// resolve a new request.
|
||||
if (pendingCaptureRef.compareAndSet(waiter, null)) {
|
||||
waiter.complete(png)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
if (pendingCaptureRef.compareAndSet(waiter, null)) {
|
||||
waiter.completeExceptionally(t)
|
||||
}
|
||||
} finally {
|
||||
runCatching { image?.close() }
|
||||
}
|
||||
}, handler)
|
||||
val reader = createImageReader(width, height, handler)
|
||||
|
||||
val display = try {
|
||||
projection.createVirtualDisplay(
|
||||
@@ -422,7 +435,7 @@ class ScreenCapture(
|
||||
height,
|
||||
densityDpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
reader.surface,
|
||||
null,
|
||||
null,
|
||||
handler,
|
||||
)
|
||||
@@ -461,6 +474,38 @@ class ScreenCapture(
|
||||
}
|
||||
}
|
||||
|
||||
private fun createImageReader(width: Int, height: Int, handler: Handler): ImageReader {
|
||||
val reader = ImageReader.newInstance(
|
||||
width, height, PixelFormat.RGBA_8888, MAX_IMAGES,
|
||||
)
|
||||
// The listener receives frames only while captureFrame() has attached
|
||||
// this reader's surface. The empty-waiter branch drains a frame already
|
||||
// queued at the detach boundary.
|
||||
reader.setOnImageAvailableListener({ source ->
|
||||
val waiter = pendingCaptureRef.get()
|
||||
if (waiter == null || !waiter.isActive) {
|
||||
runCatching { source.acquireLatestImage() }.getOrNull()?.close()
|
||||
return@setOnImageAvailableListener
|
||||
}
|
||||
var image: Image? = null
|
||||
try {
|
||||
image = source.acquireLatestImage()
|
||||
?: return@setOnImageAvailableListener
|
||||
val png = imageToPngBytes(image, width, height)
|
||||
if (pendingCaptureRef.compareAndSet(waiter, null)) {
|
||||
waiter.complete(png)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
if (pendingCaptureRef.compareAndSet(waiter, null)) {
|
||||
waiter.completeExceptionally(t)
|
||||
}
|
||||
} finally {
|
||||
runCatching { image?.close() }
|
||||
}
|
||||
}, handler)
|
||||
return reader
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an [Image] from `ImageReader` into a PNG byte array. The
|
||||
* plane's `rowStride` may be wider than `width * 4` — we must crop
|
||||
@@ -511,10 +556,8 @@ class ScreenCapture(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = RelayEndpointContract.parseOrNull(relayUrl)?.httpBaseUrl
|
||||
?: return Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = "$httpBase/media/upload"
|
||||
val body = MultipartBody.Builder()
|
||||
|
||||
+2
-2
@@ -70,7 +70,7 @@ import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.ui.theme.PersistedHermesRelayTheme
|
||||
import java.util.UUID
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
@@ -131,7 +131,7 @@ private class HermesVoiceInteractionSession(
|
||||
setViewTreeViewModelStoreOwner(viewOwner)
|
||||
setViewTreeSavedStateRegistryOwner(viewOwner)
|
||||
setContent {
|
||||
HermesRelayTheme {
|
||||
PersistedHermesRelayTheme {
|
||||
AssistantSessionSurface(
|
||||
expanded = surfaceExpanded,
|
||||
onExpandedChange = { surfaceExpanded = it },
|
||||
|
||||
@@ -52,18 +52,12 @@ import kotlin.math.max
|
||||
*
|
||||
* We configure [AudioRecord] with [MediaRecorder.AudioSource.VOICE_COMMUNICATION]
|
||||
* so the platform's voice-call AEC pipeline is in play, and additionally try
|
||||
* to attach [AcousticEchoCanceler] + [NoiseSuppressor] keyed to the ExoPlayer
|
||||
* audio session id so TTS audio is cancelled from the mic stream specifically.
|
||||
* to attach [AcousticEchoCanceler] + [NoiseSuppressor] to the capture
|
||||
* [AudioRecord] session. Android audio preprocessors belong to the capture
|
||||
* path; a playback session is not a valid attachment target for AEC/NS.
|
||||
* Without AEC, the device's own speaker output would trip the VAD the moment
|
||||
* TTS started and we'd interrupt ourselves.
|
||||
*
|
||||
* The ExoPlayer audio session id is not stable at the moment we want to start
|
||||
* listening — Media3 allocates the underlying AudioTrack lazily on first
|
||||
* playback, and callers may hit [start] before that's happened (e.g. the very
|
||||
* first sentence of a turn). We poll [audioSessionIdProvider] for up to 1 s
|
||||
* before giving up on AEC and proceeding with the mic-hardware AEC alone.
|
||||
* See the `AEC_SESSION_POLL_*` constants below.
|
||||
*
|
||||
* ### Graceful degradation
|
||||
*
|
||||
* - `AudioRecord.getState() != STATE_INITIALIZED` → log WARN, emit nothing,
|
||||
@@ -93,8 +87,8 @@ import kotlin.math.max
|
||||
class BargeInListener internal constructor(
|
||||
private val audioSource: AudioFrameSource,
|
||||
private val vadEngine: VadEngine,
|
||||
private val audioSessionIdProvider: () -> Int,
|
||||
private val readerDispatcher: CoroutineDispatcher = Dispatchers.IO,
|
||||
private val nowMsProvider: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@@ -108,12 +102,6 @@ class BargeInListener internal constructor(
|
||||
* brief delay (GC pause, dispatcher contention). */
|
||||
private const val AUDIO_BUFFER_FRAMES = 4
|
||||
|
||||
/** ExoPlayer may return `0` for its audio session id until its
|
||||
* AudioTrack is first allocated (on playback start). Poll the
|
||||
* provider briefly before giving up on AEC and proceeding without. */
|
||||
private const val AEC_SESSION_POLL_INTERVAL_MS = 50L
|
||||
private const val AEC_SESSION_POLL_TIMEOUT_MS = 1_000L
|
||||
|
||||
/**
|
||||
* Factory for the production path. Builds an [AudioRecordSource] from
|
||||
* a `Context` and wires it to the listener. The returned listener has
|
||||
@@ -122,11 +110,9 @@ class BargeInListener internal constructor(
|
||||
fun create(
|
||||
context: Context,
|
||||
vadEngine: VadEngine,
|
||||
audioSessionIdProvider: () -> Int,
|
||||
): BargeInListener = BargeInListener(
|
||||
audioSource = AudioRecordSource(context.applicationContext),
|
||||
vadEngine = vadEngine,
|
||||
audioSessionIdProvider = audioSessionIdProvider,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -239,9 +225,8 @@ class BargeInListener internal constructor(
|
||||
return@launch
|
||||
}
|
||||
Log.i(TAG, "Barge-in AudioRecord reader started")
|
||||
// Do not block generation-phase listening while waiting for an
|
||||
// AudioTrack session that does not exist until playback. The
|
||||
// effects attach races harmlessly beside the reader.
|
||||
// Effects attach beside the reader so capture can begin even
|
||||
// on devices that reject or omit the optional preprocessors.
|
||||
effectsJob = launch { maybeAttachEffects() }
|
||||
|
||||
while (isActive) {
|
||||
@@ -282,7 +267,7 @@ class BargeInListener internal constructor(
|
||||
val gated = rmsGate.observe(
|
||||
frame = frameBuffer,
|
||||
rawSpeech = result.probability > 0f,
|
||||
nowMs = System.currentTimeMillis(),
|
||||
nowMs = nowMsProvider(),
|
||||
playbackGraceMs = playbackGraceMs,
|
||||
confirmedSpeech = result.isSpeech,
|
||||
playbackActiveOverride = playbackActiveProvider?.invoke(),
|
||||
@@ -368,14 +353,12 @@ class BargeInListener internal constructor(
|
||||
}
|
||||
|
||||
private suspend fun maybeAttachEffects() {
|
||||
val sessionId = awaitNonZeroSessionId()
|
||||
val sessionId = audioSource.audioSessionId
|
||||
if (sessionId == 0) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"AEC not attached — ExoPlayer audio session id was still 0 " +
|
||||
"after ${AEC_SESSION_POLL_TIMEOUT_MS}ms poll; continuing " +
|
||||
"without effects (mic-hardware AEC from VOICE_COMMUNICATION " +
|
||||
"still in play)",
|
||||
"AEC not attached — AudioRecord capture session id is 0; " +
|
||||
"continuing without optional effects",
|
||||
)
|
||||
return
|
||||
}
|
||||
@@ -411,20 +394,6 @@ class BargeInListener internal constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun awaitNonZeroSessionId(): Int {
|
||||
val immediate = audioSessionIdProvider()
|
||||
if (immediate != 0) return immediate
|
||||
|
||||
var waited = 0L
|
||||
while (waited < AEC_SESSION_POLL_TIMEOUT_MS) {
|
||||
delay(AEC_SESSION_POLL_INTERVAL_MS)
|
||||
waited += AEC_SESSION_POLL_INTERVAL_MS
|
||||
val id = audioSessionIdProvider()
|
||||
if (id != 0) return id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
private fun releaseEffects() {
|
||||
aec?.let {
|
||||
runCatching { it.enabled = false }
|
||||
@@ -445,6 +414,9 @@ class BargeInListener internal constructor(
|
||||
* reader coroutine.
|
||||
*/
|
||||
internal interface AudioFrameSource {
|
||||
/** Capture-session id used by Android audio preprocessors. */
|
||||
val audioSessionId: Int
|
||||
|
||||
/**
|
||||
* Allocate underlying native resources. Returns true on success.
|
||||
* Returning false from here short-circuits the listener without any
|
||||
@@ -481,6 +453,9 @@ class BargeInListener internal constructor(
|
||||
private class AudioRecordSource(context: Context) : AudioFrameSource {
|
||||
private var record: AudioRecord? = null
|
||||
|
||||
override val audioSessionId: Int
|
||||
get() = record?.audioSessionId ?: 0
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun initialize(): Boolean {
|
||||
val sampleRate = 16_000
|
||||
|
||||
@@ -5,16 +5,24 @@ import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.BrokerEndpoint
|
||||
import com.hermesandroid.relay.data.hasHermesReach
|
||||
import com.hermesandroid.relay.data.replaceHermesReachCredential
|
||||
import com.hermesandroid.relay.data.sameBrokerAuthority
|
||||
import com.hermesandroid.relay.data.PairingPreferences
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.isSafeProfileUiMeta
|
||||
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import com.hermesandroid.relay.network.shared.InvalidCredentialException
|
||||
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
@@ -211,21 +219,47 @@ class AuthManager(
|
||||
tokenStoreKey: String,
|
||||
secrets: ConnectionAuthSecrets,
|
||||
) {
|
||||
val normalized = normalizeStoredSecrets(secrets)
|
||||
withContext(Dispatchers.IO) {
|
||||
val store = tokenStoreForBackup(context, tokenStoreKey)
|
||||
writeOrRemove(store, KEY_SESSION_TOKEN, secrets.sessionToken)
|
||||
writeOrRemove(store, KEY_REFRESH_TOKEN, secrets.refreshToken)
|
||||
writeOrRemove(store, KEY_DEVICE_ID, secrets.deviceId)
|
||||
writeOrRemove(store, KEY_API_KEY, secrets.apiKey)
|
||||
writeOrRemove(store, KEY_SESSION_TOKEN, normalized.sessionToken)
|
||||
writeOrRemove(store, KEY_REFRESH_TOKEN, normalized.refreshToken)
|
||||
writeOrRemove(store, KEY_DEVICE_ID, normalized.deviceId)
|
||||
writeOrRemove(store, KEY_API_KEY, normalized.apiKey)
|
||||
writeOrRemove(
|
||||
store,
|
||||
KEY_PROFILE_API_KEYS,
|
||||
secrets.profileApiKeys.takeIf { it.isNotEmpty() }?.let(::encodeProfileApiKeys),
|
||||
normalized.profileApiKeys
|
||||
.takeIf { it.isNotEmpty() }
|
||||
?.let(::encodeProfileApiKeys),
|
||||
)
|
||||
writeOrRemove(store, KEY_PAIRED_META, secrets.pairedSessionMetaJson)
|
||||
writeOrRemove(store, KEY_PAIRED_META, normalized.pairedSessionMetaJson)
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate a backup fully before any existing encrypted state is replaced. */
|
||||
fun validateStoredSecrets(secrets: ConnectionAuthSecrets) {
|
||||
normalizeStoredSecrets(secrets)
|
||||
}
|
||||
|
||||
private fun normalizeStoredSecrets(secrets: ConnectionAuthSecrets): ConnectionAuthSecrets =
|
||||
secrets.copy(
|
||||
sessionToken = secrets.sessionToken?.let {
|
||||
normalizeCredentialForHeader(it, "Relay session credential")
|
||||
}?.takeIf { it.isNotEmpty() },
|
||||
refreshToken = secrets.refreshToken?.let {
|
||||
normalizeCredentialForHeader(it, "Relay refresh credential")
|
||||
}?.takeIf { it.isNotEmpty() },
|
||||
apiKey = secrets.apiKey?.let {
|
||||
normalizeCredentialForHeader(it, "API credential")
|
||||
}?.takeIf { it.isNotEmpty() },
|
||||
profileApiKeys = secrets.profileApiKeys
|
||||
.mapValues { (_, value) ->
|
||||
normalizeCredentialForHeader(value, "Profile API credential")
|
||||
}
|
||||
.filterValues { it.isNotEmpty() },
|
||||
)
|
||||
|
||||
private fun tokenStoreForBackup(
|
||||
context: Context,
|
||||
tokenStoreKey: String,
|
||||
@@ -281,6 +315,7 @@ class AuthManager(
|
||||
?: return@mapNotNull null
|
||||
val model = obj["model"]?.jsonPrimitive?.contentOrNull
|
||||
?: "unknown"
|
||||
val provider = obj["provider"]?.jsonPrimitive?.contentOrNull.orEmpty()
|
||||
val description = obj["description"]?.jsonPrimitive?.contentOrNull
|
||||
?: ""
|
||||
val systemMessage = obj["system_message"]?.jsonPrimitive?.contentOrNull
|
||||
@@ -300,9 +335,15 @@ class AuthManager(
|
||||
?.jsonPrimitive?.intOrNull
|
||||
val apiServerKeyPresent = obj["api_server_key_present"]
|
||||
?.jsonPrimitive?.booleanOrNull ?: false
|
||||
val isDefault = obj["is_default"]?.jsonPrimitive?.booleanOrNull ?: false
|
||||
val hasAvatar = obj["has_avatar"]?.jsonPrimitive?.booleanOrNull ?: false
|
||||
val uiMeta = (obj["ui_meta"] as? JsonObject)
|
||||
?.takeIf(::isSafeProfileUiMeta)
|
||||
?: JsonObject(emptyMap())
|
||||
Profile(
|
||||
name = name,
|
||||
model = model,
|
||||
provider = provider,
|
||||
description = description,
|
||||
systemMessage = systemMessage,
|
||||
gatewayRunning = gatewayRunning,
|
||||
@@ -313,6 +354,9 @@ class AuthManager(
|
||||
apiServerHost = apiServerHost,
|
||||
apiServerPort = apiServerPort,
|
||||
apiServerKeyPresent = apiServerKeyPresent,
|
||||
isDefault = isDefault,
|
||||
hasAvatar = hasAvatar,
|
||||
uiMeta = uiMeta,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -558,6 +602,12 @@ class AuthManager(
|
||||
* Either way, we leave the previously-persisted list untouched.
|
||||
*/
|
||||
private var pendingEndpoints: List<EndpointCandidate>? = null
|
||||
private var activeEndpointProvider: () -> EndpointCandidate? = { null }
|
||||
|
||||
/** Bind auth.ok route credentials to the transport that actually carried them. */
|
||||
fun setActiveEndpointProvider(provider: () -> EndpointCandidate?) {
|
||||
activeEndpointProvider = provider
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-advertised agent profiles from the `auth.ok` payload's
|
||||
@@ -585,6 +635,8 @@ class AuthManager(
|
||||
*/
|
||||
private val _apiKeyPresent = MutableStateFlow(false)
|
||||
val apiKeyPresent: StateFlow<Boolean> = _apiKeyPresent.asStateFlow()
|
||||
private val _apiKeyError = MutableStateFlow<String?>(null)
|
||||
val apiKeyError: StateFlow<String?> = _apiKeyError.asStateFlow()
|
||||
|
||||
init {
|
||||
// Register as system channel handler for auth messages
|
||||
@@ -604,19 +656,40 @@ class AuthManager(
|
||||
val s = store()
|
||||
val existingToken = s.getString(KEY_SESSION_TOKEN)
|
||||
if (existingToken != null) {
|
||||
_authState.value = AuthState.Paired(existingToken)
|
||||
_currentPairedSession.value = loadStoredMetadata(existingToken)
|
||||
Log.i(
|
||||
TAG,
|
||||
"init: hydrated existing session_token=${existingToken.take(8)}… " +
|
||||
"→ authState=Paired (stale-at-startup unless this is a real continuous session)"
|
||||
)
|
||||
runCatching {
|
||||
normalizeCredentialForHeader(existingToken, "Relay session credential")
|
||||
.also { require(it.isNotEmpty()) }
|
||||
}.onSuccess { normalized ->
|
||||
if (normalized != existingToken) s.putString(KEY_SESSION_TOKEN, normalized)
|
||||
_authState.value = AuthState.Paired(normalized)
|
||||
_currentPairedSession.value = loadStoredMetadata(normalized)
|
||||
Log.i(TAG, "init: hydrated existing session credential")
|
||||
}.onFailure {
|
||||
_authState.value = AuthState.Failed(
|
||||
"Saved Relay credential is malformed. Re-pair this connection.",
|
||||
)
|
||||
Log.w(TAG, "init: rejected malformed saved Relay credential")
|
||||
}
|
||||
} else {
|
||||
Log.i(TAG, "init: no stored session_token → authState stays Unpaired")
|
||||
}
|
||||
// Converge the plain api-key-present hint with the decrypted
|
||||
// truth (also repairs a hint that predates legacy migration).
|
||||
recordApiKeyHint(!s.getString(KEY_API_KEY).isNullOrBlank())
|
||||
val storedApiKey = s.getString(KEY_API_KEY)
|
||||
if (storedApiKey != null) {
|
||||
runCatching {
|
||||
normalizeCredentialForHeader(storedApiKey, "API credential")
|
||||
.also { require(it.isNotEmpty()) }
|
||||
}.onSuccess { normalized ->
|
||||
if (normalized != storedApiKey) s.putString(KEY_API_KEY, normalized)
|
||||
_apiKeyError.value = null
|
||||
}.onFailure {
|
||||
_apiKeyError.value =
|
||||
"Saved API credential is malformed. Replace or clear it."
|
||||
Log.w(TAG, "init: rejected malformed saved API credential")
|
||||
}
|
||||
}
|
||||
recordApiKeyHint(!storedApiKey.isNullOrBlank())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -793,10 +866,20 @@ class AuthManager(
|
||||
val deviceId = getDeviceId()
|
||||
val payload = when (currentState) {
|
||||
is AuthState.Paired -> {
|
||||
val refreshToken = store().getString(KEY_REFRESH_TOKEN)
|
||||
val refreshToken = store().getString(KEY_REFRESH_TOKEN)?.let { raw ->
|
||||
runCatching {
|
||||
normalizeCredentialForHeader(raw, "Relay refresh credential")
|
||||
}.getOrElse {
|
||||
_authState.value = AuthState.Failed(
|
||||
"Saved Relay credential is malformed. Re-pair this connection.",
|
||||
)
|
||||
Log.w(TAG, "authenticate: rejected malformed refresh credential")
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
Log.i(
|
||||
TAG,
|
||||
"authenticate: sending session_token (state=Paired, token=${currentState.token.take(8)}…, " +
|
||||
"authenticate: sending saved session credential (state=Paired, " +
|
||||
"refresh=${!refreshToken.isNullOrBlank()})"
|
||||
)
|
||||
buildJsonObject {
|
||||
@@ -984,10 +1067,26 @@ class AuthManager(
|
||||
|
||||
// --- API Key storage (for direct Hermes API Server auth) ---
|
||||
|
||||
suspend fun getApiKey(): String? = store().getString(KEY_API_KEY)
|
||||
suspend fun getApiKey(): String? {
|
||||
val raw = store().getString(KEY_API_KEY) ?: return null
|
||||
return runCatching {
|
||||
normalizeCredentialForHeader(raw, "API credential")
|
||||
.takeIf { it.isNotEmpty() }
|
||||
}.onSuccess {
|
||||
_apiKeyError.value = null
|
||||
}.onFailure {
|
||||
_apiKeyError.value = "Saved API credential is malformed. Replace or clear it."
|
||||
Log.w(TAG, "getApiKey: rejected malformed saved API credential")
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
suspend fun setApiKey(key: String) {
|
||||
val trimmed = key.trim()
|
||||
val trimmed = runCatching {
|
||||
normalizeCredentialForHeader(key, "API credential")
|
||||
}.getOrElse {
|
||||
_apiKeyError.value = "API credentials must be a single line."
|
||||
throw it
|
||||
}
|
||||
val s = store()
|
||||
if (trimmed.isBlank()) {
|
||||
s.remove(KEY_API_KEY)
|
||||
@@ -996,11 +1095,13 @@ class AuthManager(
|
||||
s.putString(KEY_API_KEY, trimmed)
|
||||
recordApiKeyHint(true)
|
||||
}
|
||||
_apiKeyError.value = null
|
||||
}
|
||||
|
||||
suspend fun clearApiKey() {
|
||||
store().remove(KEY_API_KEY)
|
||||
recordApiKeyHint(false)
|
||||
_apiKeyError.value = null
|
||||
}
|
||||
|
||||
suspend fun getProfileApiKey(profileName: String): String? =
|
||||
@@ -1012,7 +1113,7 @@ class AuthManager(
|
||||
profileApiKeysMutex.withLock {
|
||||
val tokenStore = store()
|
||||
val keys = decodeProfileApiKeys(tokenStore.getString(KEY_PROFILE_API_KEYS)).toMutableMap()
|
||||
val normalizedKey = key.trim()
|
||||
val normalizedKey = normalizeCredentialForHeader(key, "Profile API credential")
|
||||
if (normalizedKey.isBlank()) keys.remove(normalizedProfile)
|
||||
else keys[normalizedProfile] = normalizedKey
|
||||
if (keys.isEmpty()) tokenStore.remove(KEY_PROFILE_API_KEYS)
|
||||
@@ -1031,7 +1132,10 @@ class AuthManager(
|
||||
scope.launch {
|
||||
try {
|
||||
val payload = envelope.payload
|
||||
val token = payload["session_token"]?.jsonPrimitive?.contentOrNull
|
||||
val token = payload["session_token"]?.jsonPrimitive?.contentOrNull?.let { raw ->
|
||||
normalizeCredentialForHeader(raw, "Relay session credential")
|
||||
.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
if (token == null) {
|
||||
Log.w(
|
||||
@@ -1042,18 +1146,20 @@ class AuthManager(
|
||||
}
|
||||
|
||||
if (token != null) {
|
||||
applyBrokerRouteCredential(payload)
|
||||
val s = store()
|
||||
s.putString(KEY_SESSION_TOKEN, token)
|
||||
val refreshToken = payload["refresh_token"]
|
||||
?.jsonPrimitive
|
||||
?.contentOrNull
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { normalizeCredentialForHeader(it, "Relay refresh credential") }
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
if (refreshToken != null) {
|
||||
s.putString(KEY_REFRESH_TOKEN, refreshToken)
|
||||
Log.i(TAG, "handleAuthOk: stored rotated refresh token")
|
||||
}
|
||||
_authState.value = AuthState.Paired(token)
|
||||
Log.i(TAG, "handleAuthOk: Paired(token=${token.take(8)}…)")
|
||||
Log.i(TAG, "handleAuthOk: paired with server-issued session credential")
|
||||
// Per-connection signal for socket-scoped consumers (e.g.
|
||||
// re-sending proactive.subscribe). Fires on every auth.ok.
|
||||
_authOkEvents.tryEmit(Unit)
|
||||
@@ -1146,10 +1252,56 @@ class AuthManager(
|
||||
// handler is exactly why the broken `_sessionLabels` parser
|
||||
// (stringifying object entries) sat undetected for so long.
|
||||
Log.w(TAG, "auth.ok parse failed: ${e.message}", e)
|
||||
if (e is InvalidCredentialException) {
|
||||
_authState.value = AuthState.Failed(
|
||||
"Relay returned a malformed credential. Re-pair this connection.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyBrokerRouteCredential(payload: JsonObject) {
|
||||
val active = activeEndpointProvider()?.takeIf { it.hasHermesReach() } ?: return
|
||||
val current = active.broker ?: return
|
||||
// Fresh pairing is scoped by pendingEndpoints; reconnect rotation is
|
||||
// accepted only by this connection-scoped AuthManager's live session.
|
||||
if (pendingEndpoints == null && _authState.value !is AuthState.Paired) return
|
||||
val credential = payload["route_credential"] as? JsonObject ?: return
|
||||
if (credential["kind"]?.jsonPrimitive?.contentOrNull != "broker_route") return
|
||||
val brokerUrl = credential["broker_url"]?.jsonPrimitive?.contentOrNull ?: return
|
||||
val hostId = credential["host_id"]?.jsonPrimitive?.contentOrNull ?: return
|
||||
if (!sameBrokerAuthority(brokerUrl, current.url) || hostId != current.hostId) {
|
||||
Log.w(TAG, "Ignoring broker route credential that does not match the active paired route")
|
||||
return
|
||||
}
|
||||
val replacement = BrokerEndpoint(
|
||||
url = current.url,
|
||||
protocolVersion = current.protocolVersion,
|
||||
hostId = current.hostId,
|
||||
credentialKind = "route",
|
||||
token = credential["token"]?.jsonPrimitive?.contentOrNull?.let {
|
||||
runCatching {
|
||||
normalizeCredentialForHeader(it, "Hermes Reach credential")
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "Ignoring malformed Hermes Reach route credential")
|
||||
return
|
||||
}
|
||||
} ?: return,
|
||||
expiresAt = credential["expires_at"]?.jsonPrimitive?.longOrNull,
|
||||
)
|
||||
val validated = active.copy(broker = replacement).takeIf { it.hasHermesReach() } ?: return
|
||||
val deviceId = getDeviceId()
|
||||
val source = pendingEndpoints
|
||||
?: PairingPreferences.getDeviceEndpoints(context, deviceId).first()
|
||||
val updated = replaceHermesReachCredential(source, current, validated)
|
||||
if (updated == source) return
|
||||
if (pendingEndpoints != null) pendingEndpoints = updated
|
||||
else PairingPreferences.setDeviceEndpoints(context, deviceId, updated)
|
||||
Log.i(TAG, "Accepted a durable Hermes Reach route credential for the active paired route")
|
||||
}
|
||||
|
||||
|
||||
private fun handleAuthFail(envelope: Envelope) {
|
||||
try {
|
||||
val rawReason = envelope.payload["reason"]?.jsonPrimitive?.contentOrNull
|
||||
|
||||
@@ -90,12 +90,28 @@ class CertPinStore(private val context: Context) {
|
||||
if (pins.isEmpty()) return CertificatePinner.DEFAULT
|
||||
val builder = CertificatePinner.Builder()
|
||||
for ((hostPort, pin) in pins) {
|
||||
val host = hostPort.substringBefore(':')
|
||||
val host = hostPort.substringBeforeLast(':')
|
||||
builder.add(host, pin)
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a pinner for one exact URL authority. CertificatePinner keys by
|
||||
* hostname only, so adding every stored host:port entry to one client
|
||||
* accidentally lets a pin learned on one port govern another port.
|
||||
*/
|
||||
fun buildPinnerSnapshotFor(url: String): CertificatePinner {
|
||||
val hostPort = hostPortFromUrl(url) ?: return CertificatePinner.DEFAULT
|
||||
val pin = getPinsBlocking()[hostPort] ?: return CertificatePinner.DEFAULT
|
||||
val host = runCatching { URI(url.trim()).host }.getOrNull()
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: return CertificatePinner.DEFAULT
|
||||
return CertificatePinner.Builder()
|
||||
.add(host, pin)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a pin for a host. Called from the WebSocket listener's `onOpen`
|
||||
* when we have a successful connection and can read the peer certs from
|
||||
|
||||
@@ -15,25 +15,22 @@ import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.hermesandroid.relay.MainActivity
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.accessibility.HermesAccessibilityService
|
||||
|
||||
/**
|
||||
* Phase 3 — safety-rails `bridge-safety-rails`
|
||||
*
|
||||
* Canonical "turn the bridge off after idle" unit of work. Not a real
|
||||
* Canonical timed-screen-expiry notification unit. Not a real
|
||||
* `androidx.work.CoroutineWorker` — the project intentionally does not
|
||||
* depend on androidx.work — but its shape mirrors one exactly: a single
|
||||
* suspend [run] method that performs the work and returns.
|
||||
*
|
||||
* Why this pattern instead of dropping a WorkManager dep:
|
||||
* - Auto-disable is a pure in-memory decision: the toggle lives in our
|
||||
* own DataStore, no inter-process scheduling is required.
|
||||
* - Capability expiry is persisted as absolute wall-clock timestamps;
|
||||
* the in-process job exists only to prune promptly and notify.
|
||||
* - Android's AlarmManager / WorkManager are needed when the work must
|
||||
* survive process death. For bridge, process death already implies
|
||||
* the service is disconnected and the master toggle re-evaluates
|
||||
* fresh on the next launch. So a coroutine-owned `delay` does it.
|
||||
* - Every command reschedules the timer, so the idle window is always
|
||||
* reset against wall clock. No drift concerns.
|
||||
* survive process death. Authorization itself does survive because the
|
||||
* command boundary compares persisted expiry with the current clock.
|
||||
* - Only timed screen inspection/control commands reset the timer.
|
||||
*
|
||||
* When WorkManager is added later (say, if notif-listener needs background-posted
|
||||
* notifications on a schedule), this file is a natural upgrade point:
|
||||
@@ -51,17 +48,10 @@ class AutoDisableWorker(private val context: Context) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the auto-disable: flip the master toggle off and post a
|
||||
* one-shot "bridge paused" notification. Idempotent — safe to call
|
||||
* twice (the second call just re-writes the same DataStore value
|
||||
* and overrides the existing notification).
|
||||
* Post a one-shot notification after timed screen authority is revoked.
|
||||
* Idempotent — a repeated call replaces the existing notification.
|
||||
*/
|
||||
suspend fun run() {
|
||||
try {
|
||||
HermesAccessibilityService.setMasterEnabled(context, false)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "run: failed to flip master toggle", t)
|
||||
}
|
||||
postNotification()
|
||||
}
|
||||
|
||||
@@ -92,8 +82,7 @@ class AutoDisableWorker(private val context: Context) {
|
||||
.setContentTitle(context.getString(R.string.bridge_notification_auto_disabled_title))
|
||||
.setContentText(context.getString(R.string.bridge_notification_auto_disabled_body))
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(
|
||||
"Hermes bridge was idle for too long, so device control has been turned off " +
|
||||
"automatically. Open the Bridge tab to turn it back on if you still need it."
|
||||
context.getString(R.string.bridge_notification_auto_disabled_body)
|
||||
))
|
||||
.setContentIntent(tapPending)
|
||||
.setAutoCancel(true)
|
||||
@@ -115,7 +104,7 @@ class AutoDisableWorker(private val context: Context) {
|
||||
CHANNEL_NAME,
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "Fires once when the bridge auto-disables after being idle."
|
||||
description = "Fires once when timed Bridge screen access expires after idle."
|
||||
setShowBadge(false)
|
||||
}
|
||||
nm.createNotificationChannel(channel)
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.hermesandroid.relay.bridge
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** Stable, auditable authority groups for every phone-side Bridge command. */
|
||||
@Serializable
|
||||
enum class BridgeCapability(val wireId: String, val timed: Boolean) {
|
||||
DEVICE_INFO("device_info", false),
|
||||
CONTACTS_READ("contacts_read", false),
|
||||
LOCATION_READ("location_read", false),
|
||||
CLIPBOARD_READ("clipboard_read", false),
|
||||
CLIPBOARD_WRITE("clipboard_write", false),
|
||||
MEDIA_CONTROL("media_control", false),
|
||||
COMMUNICATIONS("communications", false),
|
||||
OUTBOUND_SHARING("outbound_sharing", false),
|
||||
SCREEN_INSPECTION("screen_inspection", true),
|
||||
SCREEN_CONTROL("screen_control", true),
|
||||
}
|
||||
|
||||
enum class BridgeCapabilityGrant { EXEMPT, PERMANENT, TIMED }
|
||||
|
||||
data class BridgeCommandAuthority(
|
||||
val capability: BridgeCapability? = null,
|
||||
val grant: BridgeCapabilityGrant,
|
||||
)
|
||||
|
||||
/**
|
||||
* Closed command registry. Authorization is resolved from both path and HTTP
|
||||
* method so method-split commands such as clipboard read/write cannot share a
|
||||
* grant accidentally. Unknown paths and method combinations return null and
|
||||
* must be denied by the command boundary.
|
||||
*
|
||||
* Composite Python tools (android_navigate/android_macro) do not get a broad
|
||||
* grant: every primitive route they dispatch is checked here independently.
|
||||
*/
|
||||
object BridgeCommandRegistry {
|
||||
private data class Key(val method: String, val path: String)
|
||||
|
||||
private fun permanent(capability: BridgeCapability) =
|
||||
BridgeCommandAuthority(capability, BridgeCapabilityGrant.PERMANENT)
|
||||
|
||||
private fun timed(capability: BridgeCapability) =
|
||||
BridgeCommandAuthority(capability, BridgeCapabilityGrant.TIMED)
|
||||
|
||||
private val exempt = BridgeCommandAuthority(grant = BridgeCapabilityGrant.EXEMPT)
|
||||
|
||||
private val routes: Map<Key, BridgeCommandAuthority> = buildMap {
|
||||
fun route(method: String, path: String, authority: BridgeCommandAuthority) {
|
||||
put(Key(method, path), authority)
|
||||
}
|
||||
|
||||
route("GET", "/ping", exempt)
|
||||
route("POST", "/setup", exempt)
|
||||
route("POST", "/wait", exempt)
|
||||
|
||||
route("GET", "/current_app", permanent(BridgeCapability.DEVICE_INFO))
|
||||
route("GET", "/get_apps", permanent(BridgeCapability.DEVICE_INFO))
|
||||
route("GET", "/apps", permanent(BridgeCapability.DEVICE_INFO))
|
||||
route("POST", "/search_contacts", permanent(BridgeCapability.CONTACTS_READ))
|
||||
route("GET", "/location", permanent(BridgeCapability.LOCATION_READ))
|
||||
route("GET", "/clipboard", permanent(BridgeCapability.CLIPBOARD_READ))
|
||||
route("POST", "/clipboard", permanent(BridgeCapability.CLIPBOARD_WRITE))
|
||||
route("POST", "/media", permanent(BridgeCapability.MEDIA_CONTROL))
|
||||
route("POST", "/call", permanent(BridgeCapability.COMMUNICATIONS))
|
||||
route("POST", "/send_sms", permanent(BridgeCapability.COMMUNICATIONS))
|
||||
route("POST", "/share_media", permanent(BridgeCapability.OUTBOUND_SHARING))
|
||||
route("POST", "/send_mms", permanent(BridgeCapability.OUTBOUND_SHARING))
|
||||
|
||||
listOf("/screen", "/screenshot", "/screen_hash", "/events").forEach {
|
||||
route("GET", it, timed(BridgeCapability.SCREEN_INSPECTION))
|
||||
}
|
||||
listOf("/find_nodes", "/describe_node", "/diff_screen", "/events/stream").forEach {
|
||||
route("POST", it, timed(BridgeCapability.SCREEN_INSPECTION))
|
||||
}
|
||||
|
||||
listOf(
|
||||
"/tap", "/tap_text", "/long_press", "/type", "/swipe", "/drag",
|
||||
"/scroll", "/press_key", "/open_app", "/return_to_hermes",
|
||||
"/send_intent", "/broadcast",
|
||||
).forEach { route("POST", it, timed(BridgeCapability.SCREEN_CONTROL)) }
|
||||
}
|
||||
|
||||
fun resolve(path: String, method: String): BridgeCommandAuthority? =
|
||||
routes[Key(method.trim().uppercase(), path.trim())]
|
||||
|
||||
fun registeredRoutes(): Set<Pair<String, String>> =
|
||||
routes.keys.mapTo(linkedSetOf()) { it.method to it.path }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class BridgeCapabilityPolicy(
|
||||
val schemaVersion: Int = CURRENT_SCHEMA_VERSION,
|
||||
val permanentGrants: Set<BridgeCapability> = emptySet(),
|
||||
val timedExpiriesMs: Map<BridgeCapability, Long> = emptyMap(),
|
||||
) {
|
||||
companion object {
|
||||
const val CURRENT_SCHEMA_VERSION = 1
|
||||
/** Explicit sentinel for a user-selected "Until turned off" lease. */
|
||||
const val NEVER_EXPIRES_AT_MS: Long = Long.MAX_VALUE
|
||||
}
|
||||
|
||||
fun allows(capability: BridgeCapability, nowMs: Long): Boolean =
|
||||
if (capability.timed) {
|
||||
(timedExpiriesMs[capability] ?: 0L) > nowMs
|
||||
} else {
|
||||
capability in permanentGrants
|
||||
}
|
||||
|
||||
fun expiryFor(capability: BridgeCapability): Long? = timedExpiriesMs[capability]
|
||||
|
||||
fun isUnlimited(capability: BridgeCapability): Boolean =
|
||||
timedExpiriesMs[capability] == NEVER_EXPIRES_AT_MS
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
|
||||
import com.hermesandroid.relay.data.BridgeSafetySettings
|
||||
import com.hermesandroid.relay.data.BridgeCapabilityPolicyRepository
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -14,6 +15,8 @@ import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.plus
|
||||
@@ -25,8 +28,8 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
/**
|
||||
* Phase 3 — safety-rails `bridge-safety-rails`
|
||||
*
|
||||
* Central enforcement point for Tier 5 safety: per-app blocklist, destructive
|
||||
* verb confirmation, and idle-based auto-disable. Owned as a singleton-per-
|
||||
* Central enforcement point for Tier 5 safety: connection-scoped capabilities,
|
||||
* per-app blocklist, destructive confirmation, and timed screen access. Owned as a singleton-per-
|
||||
* process by [ConnectionViewModel] and injected into [BridgeCommandHandler].
|
||||
*
|
||||
* # Integration surface
|
||||
@@ -47,9 +50,9 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
* reacts, which is exactly the UX we want (the server sees a slow
|
||||
* response, not a denial race).
|
||||
*
|
||||
* - [rescheduleAutoDisable] — every accepted command bumps the idle timer
|
||||
* forward; after [BridgeSafetySettings.autoDisableMinutes] of silence
|
||||
* the master toggle flips off and a one-shot notification fires.
|
||||
* - [rescheduleAutoDisable] — accepted timed screen commands bump the idle
|
||||
* expiry forward; after [BridgeSafetySettings.autoDisableMinutes] of
|
||||
* silence only timed screen authority is revoked and a notification fires.
|
||||
* [cancelAutoDisable] cancels the pending timer (called when the master
|
||||
* toggle flips off manually, so we don't race the timer against the
|
||||
* user).
|
||||
@@ -71,15 +74,14 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
* The Android app does not depend on androidx.work. [AutoDisableWorker]
|
||||
* documents the canonical pattern, but the live path is a coroutine
|
||||
* `Job` owned by this manager, delayed by the configured minutes. This is
|
||||
* acceptable because we are the in-memory owner of the master-toggle flow
|
||||
* — no inter-process or cross-restart scheduling is needed. On process
|
||||
* death the master toggle is simply evaluated fresh from DataStore, and
|
||||
* any command not explicitly sent within the idle window never actually
|
||||
* happens because the app isn't running.
|
||||
* acceptable because authorization stores an absolute expiry in DataStore.
|
||||
* After process death or reconnect, the command boundary compares that expiry
|
||||
* to wall clock and denies stale authority even if the notification job did not run.
|
||||
*/
|
||||
class BridgeSafetyManager(
|
||||
context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
private val activeConnectionId: StateFlow<String?>,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "BridgeSafetyMgr"
|
||||
@@ -94,10 +96,14 @@ class BridgeSafetyManager(
|
||||
*/
|
||||
fun peek(): BridgeSafetyManager? = INSTANCE
|
||||
|
||||
fun install(context: Context, scope: CoroutineScope): BridgeSafetyManager {
|
||||
fun install(
|
||||
context: Context,
|
||||
scope: CoroutineScope,
|
||||
activeConnectionId: StateFlow<String?>,
|
||||
): BridgeSafetyManager {
|
||||
val existing = INSTANCE
|
||||
if (existing != null) return existing
|
||||
val created = BridgeSafetyManager(context.applicationContext, scope)
|
||||
val created = BridgeSafetyManager(context.applicationContext, scope, activeConnectionId)
|
||||
INSTANCE = created
|
||||
return created
|
||||
}
|
||||
@@ -105,6 +111,10 @@ class BridgeSafetyManager(
|
||||
|
||||
private val appContext: Context = context.applicationContext
|
||||
private val prefsRepo = BridgeSafetyPreferencesRepository(appContext)
|
||||
private val capabilityRepo = BridgeCapabilityPolicyRepository(appContext)
|
||||
private val _activeCapabilityPolicy = MutableStateFlow(BridgeCapabilityPolicy())
|
||||
val activeCapabilityPolicy: StateFlow<BridgeCapabilityPolicy> =
|
||||
_activeCapabilityPolicy.asStateFlow()
|
||||
|
||||
/** Latest settings snapshot — UI + checks read this via [settings]. */
|
||||
private val _settings = MutableStateFlow(BridgeSafetySettings())
|
||||
@@ -140,12 +150,12 @@ class BridgeSafetyManager(
|
||||
private val pendingConfirmations = ConcurrentHashMap<Long, PendingConfirmation>()
|
||||
private val nextRequestId = AtomicLong(0L)
|
||||
|
||||
/** Coroutine job that fires auto-disable after idle. */
|
||||
/** Coroutine job that prunes timed screen authority after idle. */
|
||||
@Volatile
|
||||
private var autoDisableJob: Job? = null
|
||||
|
||||
/**
|
||||
* Remaining time (epoch millis) for the current auto-disable job, or
|
||||
* Remaining time (epoch millis) for current timed screen authority, or
|
||||
* null when idle. BridgeSafetySummaryCard reads this as a countdown.
|
||||
*/
|
||||
private val _autoDisableAtMs = MutableStateFlow<Long?>(null)
|
||||
@@ -167,6 +177,100 @@ class BridgeSafetyManager(
|
||||
trustedHydrated = true
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
activeConnectionId.collectLatest { connectionId ->
|
||||
schedulePersistedExpiry(connectionId)
|
||||
capabilityRepo.policy(connectionId).collect { policy ->
|
||||
_activeCapabilityPolicy.value = policy
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class CapabilityAuthorization(
|
||||
val allowed: Boolean,
|
||||
val authority: BridgeCommandAuthority? = null,
|
||||
val errorCode: String? = null,
|
||||
)
|
||||
|
||||
fun capabilityPolicy(connectionId: String?): Flow<BridgeCapabilityPolicy> =
|
||||
capabilityRepo.policy(connectionId)
|
||||
|
||||
suspend fun authorizeCapability(
|
||||
path: String,
|
||||
method: String,
|
||||
nowMs: Long = System.currentTimeMillis(),
|
||||
): CapabilityAuthorization {
|
||||
val authority = BridgeCommandRegistry.resolve(path, method)
|
||||
?: return CapabilityAuthorization(false, errorCode = "unknown_bridge_command")
|
||||
if (authority.grant == BridgeCapabilityGrant.EXEMPT) {
|
||||
return CapabilityAuthorization(true, authority)
|
||||
}
|
||||
val connectionId = activeConnectionId.value
|
||||
?: return CapabilityAuthorization(false, authority, "bridge_policy_unbound")
|
||||
val capability = authority.capability
|
||||
?: return CapabilityAuthorization(false, authority, "bridge_policy_invalid")
|
||||
val policy = capabilityRepo.snapshot(connectionId)
|
||||
return if (policy.allows(capability, nowMs)) {
|
||||
CapabilityAuthorization(true, authority)
|
||||
} else {
|
||||
CapabilityAuthorization(
|
||||
false,
|
||||
authority,
|
||||
if (capability.timed) "bridge_capability_expired" else "bridge_capability_denied",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setPermanentCapability(
|
||||
connectionId: String?,
|
||||
capability: BridgeCapability,
|
||||
allowed: Boolean,
|
||||
) {
|
||||
capabilityRepo.setPermanent(connectionId, capability, allowed)
|
||||
}
|
||||
|
||||
suspend fun replacePermanentCapabilities(
|
||||
connectionId: String?,
|
||||
capabilities: Set<BridgeCapability>,
|
||||
) {
|
||||
capabilityRepo.replacePermanent(connectionId, capabilities)
|
||||
}
|
||||
|
||||
suspend fun setTimedCapability(
|
||||
connectionId: String?,
|
||||
capability: BridgeCapability,
|
||||
allowed: Boolean,
|
||||
) {
|
||||
if (!allowed) {
|
||||
capabilityRepo.revoke(connectionId, capability)
|
||||
if (capability == BridgeCapability.SCREEN_CONTROL) {
|
||||
prefsRepo.setUnattendedAccessEnabled(false)
|
||||
}
|
||||
schedulePersistedExpiry(connectionId)
|
||||
return
|
||||
}
|
||||
val fireAt = System.currentTimeMillis() + currentSettings().autoDisableMinutes * 60_000L
|
||||
capabilityRepo.grantTimed(connectionId, capability, fireAt)
|
||||
schedulePersistedExpiry(connectionId)
|
||||
}
|
||||
|
||||
suspend fun replaceTimedCapabilities(
|
||||
connectionId: String?,
|
||||
capabilities: Set<BridgeCapability>,
|
||||
durationMinutes: Int,
|
||||
unlimited: Boolean = false,
|
||||
) {
|
||||
val fireAt = if (unlimited) {
|
||||
BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS
|
||||
} else {
|
||||
System.currentTimeMillis() + durationMinutes * 60_000L
|
||||
}
|
||||
capabilityRepo.replaceTimed(connectionId, capabilities, fireAt)
|
||||
if (BridgeCapability.SCREEN_CONTROL !in capabilities) {
|
||||
prefsRepo.setUnattendedAccessEnabled(false)
|
||||
}
|
||||
schedulePersistedExpiry(connectionId)
|
||||
}
|
||||
|
||||
// ── Blocklist ────────────────────────────────────────────────────────
|
||||
@@ -307,26 +411,35 @@ class BridgeSafetyManager(
|
||||
pending.deferred.complete(allowed)
|
||||
}
|
||||
|
||||
// ── Auto-disable timer ───────────────────────────────────────────────
|
||||
// ── Timed screen-access expiry ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Cancel any pending timer and arm a fresh one. Called on every accepted
|
||||
* bridge command — an actively-used bridge never auto-disables.
|
||||
* Refresh active timed grants and arm their shared idle expiry. Permanent
|
||||
* capability activity never calls this method.
|
||||
*/
|
||||
fun rescheduleAutoDisable() {
|
||||
val connectionId = activeConnectionId.value ?: return
|
||||
val minutes = _settings.value.autoDisableMinutes
|
||||
val delayMs = minutes * 60_000L
|
||||
val fireAt = System.currentTimeMillis() + delayMs
|
||||
val fireAt = System.currentTimeMillis() + minutes * 60_000L
|
||||
autoDisableJob?.cancel()
|
||||
_autoDisableAtMs.value = fireAt
|
||||
|
||||
autoDisableJob = (scope + SupervisorJob()).launch {
|
||||
try {
|
||||
val snapshot = capabilityRepo.snapshot(connectionId)
|
||||
val nowMs = System.currentTimeMillis()
|
||||
val finite = snapshot.timedExpiriesMs.filterValues {
|
||||
it != BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS && it > nowMs
|
||||
}
|
||||
if (finite.isEmpty()) {
|
||||
_autoDisableAtMs.value = null
|
||||
return@launch
|
||||
}
|
||||
capabilityRepo.refreshActiveTimed(connectionId, fireAt)
|
||||
_autoDisableAtMs.value = fireAt
|
||||
val delayMs = (fireAt - System.currentTimeMillis()).coerceAtLeast(0L)
|
||||
delay(delayMs)
|
||||
Log.i(TAG, "Auto-disable fired after $minutes min of idle")
|
||||
// Hand off to the canonical worker so both code paths look
|
||||
// identical from a behavioral standpoint (notification +
|
||||
// master-toggle flip).
|
||||
Log.i(TAG, "Timed Bridge capabilities expired after $minutes min of idle")
|
||||
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
|
||||
clearUnattendedIfControlEnded(connectionId)
|
||||
AutoDisableWorker(appContext).run()
|
||||
} catch (_: Throwable) {
|
||||
// Cancellation is expected on reschedule — swallow quietly.
|
||||
@@ -342,6 +455,48 @@ class BridgeSafetyManager(
|
||||
_autoDisableAtMs.value = null
|
||||
}
|
||||
|
||||
fun revokeTimedCapabilities() {
|
||||
val connectionId = activeConnectionId.value ?: return
|
||||
cancelAutoDisable()
|
||||
scope.launch {
|
||||
capabilityRepo.revokeTimed(connectionId)
|
||||
prefsRepo.setUnattendedAccessEnabled(false)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun schedulePersistedExpiry(connectionId: String?) {
|
||||
autoDisableJob?.cancel()
|
||||
val policy = capabilityRepo.snapshot(connectionId)
|
||||
val nextExpiry = policy.timedExpiriesMs.values
|
||||
.filter { it != BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS }
|
||||
.maxOrNull()
|
||||
if (nextExpiry == null) {
|
||||
_autoDisableAtMs.value = null
|
||||
return
|
||||
}
|
||||
if (nextExpiry <= System.currentTimeMillis()) {
|
||||
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
|
||||
clearUnattendedIfControlEnded(connectionId)
|
||||
_autoDisableAtMs.value = null
|
||||
return
|
||||
}
|
||||
_autoDisableAtMs.value = nextExpiry
|
||||
autoDisableJob = (scope + SupervisorJob()).launch {
|
||||
delay((nextExpiry - System.currentTimeMillis()).coerceAtLeast(0L))
|
||||
capabilityRepo.pruneExpired(connectionId, System.currentTimeMillis())
|
||||
clearUnattendedIfControlEnded(connectionId)
|
||||
AutoDisableWorker(appContext).run()
|
||||
if (activeConnectionId.value == connectionId) _autoDisableAtMs.value = null
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun clearUnattendedIfControlEnded(connectionId: String?) {
|
||||
val policy = capabilityRepo.snapshot(connectionId)
|
||||
if (!policy.allows(BridgeCapability.SCREEN_CONTROL, System.currentTimeMillis())) {
|
||||
prefsRepo.setUnattendedAccessEnabled(false)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internals ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -242,11 +242,9 @@ object UnattendedAccessManager {
|
||||
* returns [WakeOutcome.Success] / [SuccessNoKeyguardChange] /
|
||||
* [KeyguardBlocked] depending on the dismiss attempt outcome.
|
||||
*
|
||||
* The wake lock auto-releases via the platform's 30s timeout — we
|
||||
* don't release explicitly per call because the bridge command may
|
||||
* take several gestures to complete and we want one continuous
|
||||
* wake-up, not a stutter. [release] is provided for the master
|
||||
* toggle off path.
|
||||
* The caller must pair each successful acquire with [releaseAfterAction].
|
||||
* The platform's 30s timeout remains a crash/stall backstop, not the normal
|
||||
* lifetime. Nested or concurrent commands share the ref-counted lock.
|
||||
*
|
||||
* # Compatibility shim
|
||||
*
|
||||
@@ -300,6 +298,22 @@ object UnattendedAccessManager {
|
||||
return requestDismiss()
|
||||
}
|
||||
|
||||
/** Release one command's ownership without disturbing concurrent actions. */
|
||||
fun releaseAfterAction() {
|
||||
synchronized(countLock) {
|
||||
if (lockCount <= 0) return
|
||||
lockCount -= 1
|
||||
if (lockCount == 0) {
|
||||
val lock = wakeLock ?: return
|
||||
try {
|
||||
if (lock.isHeld) lock.release()
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "wakeLock.release threw: ${t.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous keyguard dismiss attempt. Returns:
|
||||
* - [WakeOutcome.SuccessNoKeyguardChange] when there's no keyguard
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.ui.theme.AppFont
|
||||
import com.hermesandroid.relay.ui.theme.AppThemes
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceShape
|
||||
import com.hermesandroid.relay.ui.theme.normalizeAccentHex
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
internal data class PersistedAppearance(
|
||||
val themePreference: String = "auto",
|
||||
val appThemeId: String = AppThemes.DEFAULT_ID,
|
||||
val accentHex: String? = null,
|
||||
val shapeId: String = AppearanceShape.DEFAULT.id,
|
||||
val appFontId: String = AppFont.DEFAULT.id,
|
||||
val fontScale: Float = 1.0f,
|
||||
val customTheme: CustomThemePreset? = null,
|
||||
)
|
||||
|
||||
internal object AppearancePreferences {
|
||||
val themeKey = stringPreferencesKey("theme")
|
||||
val appThemeKey = stringPreferencesKey("app_theme")
|
||||
val accentKey = stringPreferencesKey("appearance_accent")
|
||||
val shapeKey = stringPreferencesKey("appearance_shape")
|
||||
val appFontKey = stringPreferencesKey("app_font")
|
||||
val fontScaleKey = floatPreferencesKey("font_scale")
|
||||
val customThemesKey = stringPreferencesKey("custom_theme_presets")
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val serializer = ListSerializer(CustomThemePreset.serializer())
|
||||
|
||||
fun state(context: Context): Flow<PersistedAppearance> = context.applicationContext.relayDataStore.data
|
||||
.map { preferences ->
|
||||
val customThemes = decodeCustomThemes(preferences[customThemesKey])
|
||||
val requestedThemeId = preferences[appThemeKey]
|
||||
val customTheme = CustomThemePreset.idFromAppTheme(requestedThemeId)
|
||||
?.let { id -> customThemes.firstOrNull { it.id == id } }
|
||||
PersistedAppearance(
|
||||
themePreference = preferences[themeKey]
|
||||
?.takeIf { it == "auto" || it == "light" || it == "dark" }
|
||||
?: "auto",
|
||||
appThemeId = customTheme?.appThemeId ?: AppThemes.byId(requestedThemeId).id,
|
||||
accentHex = normalizeAccentHex(preferences[accentKey]),
|
||||
shapeId = AppearanceShape.fromId(preferences[shapeKey]).id,
|
||||
appFontId = AppFont.byId(preferences[appFontKey]).id,
|
||||
fontScale = (preferences[fontScaleKey] ?: 1.0f).coerceIn(0.85f, 1.3f),
|
||||
customTheme = customTheme,
|
||||
)
|
||||
}
|
||||
|
||||
fun shape(context: Context): Flow<String> = state(context).map { it.shapeId }
|
||||
|
||||
fun customThemes(context: Context): Flow<List<CustomThemePreset>> =
|
||||
context.applicationContext.relayDataStore.data.map { decodeCustomThemes(it[customThemesKey]) }
|
||||
|
||||
fun decodeCustomThemes(raw: String?): List<CustomThemePreset> = raw
|
||||
?.let { runCatching { json.decodeFromString(serializer, it) }.getOrNull() }
|
||||
.orEmpty()
|
||||
.mapNotNull { it.normalized() }
|
||||
.distinctBy { it.id }
|
||||
.take(CustomThemePreset.MAX_PRESETS)
|
||||
|
||||
fun encodeCustomThemes(themes: List<CustomThemePreset>): String = json.encodeToString(
|
||||
serializer,
|
||||
themes.mapNotNull { it.normalized() }
|
||||
.distinctBy { it.id }
|
||||
.take(CustomThemePreset.MAX_PRESETS),
|
||||
)
|
||||
|
||||
fun upsertCustomTheme(
|
||||
current: List<CustomThemePreset>,
|
||||
preset: CustomThemePreset,
|
||||
): List<CustomThemePreset>? {
|
||||
val normalized = preset.normalized() ?: return null
|
||||
val safeCurrent = current.mapNotNull { it.normalized() }
|
||||
.distinctBy { it.id }
|
||||
.take(CustomThemePreset.MAX_PRESETS)
|
||||
val existingIndex = safeCurrent.indexOfFirst { it.id == normalized.id }
|
||||
if (existingIndex < 0 && safeCurrent.size >= CustomThemePreset.MAX_PRESETS) return null
|
||||
return safeCurrent.toMutableList().apply {
|
||||
if (existingIndex >= 0) set(existingIndex, normalized) else add(normalized)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.bridge.BridgeCapability
|
||||
import com.hermesandroid.relay.bridge.BridgeCapabilityPolicy
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/** Connection-scoped Bridge authority. Missing, malformed, or future schemas deny all. */
|
||||
class BridgeCapabilityPolicyRepository(private val context: Context) {
|
||||
companion object {
|
||||
private val KEY_POLICIES = stringPreferencesKey("bridge_capability_policies_v1")
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class StoredPolicies(
|
||||
val schemaVersion: Int = BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION,
|
||||
val installId: String = "",
|
||||
val byConnection: Map<String, BridgeCapabilityPolicy> = emptyMap(),
|
||||
)
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||
private val installId: String = localInstallId(context)
|
||||
|
||||
fun policy(connectionId: String?): Flow<BridgeCapabilityPolicy> =
|
||||
context.relayDataStore.data.map { prefs ->
|
||||
readPolicies(prefs[KEY_POLICIES])[connectionId.normalizedPolicyKey()]
|
||||
?.takeIf { it.schemaVersion == BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION }
|
||||
?: BridgeCapabilityPolicy()
|
||||
}
|
||||
|
||||
suspend fun snapshot(connectionId: String?): BridgeCapabilityPolicy =
|
||||
policy(connectionId).first()
|
||||
|
||||
suspend fun setPermanent(connectionId: String?, capability: BridgeCapability, allowed: Boolean) {
|
||||
require(!capability.timed) { "Timed capabilities require an expiry" }
|
||||
update(connectionId) { current ->
|
||||
current.copy(
|
||||
permanentGrants = if (allowed) {
|
||||
current.permanentGrants + capability
|
||||
} else {
|
||||
current.permanentGrants - capability
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun replacePermanent(
|
||||
connectionId: String?,
|
||||
capabilities: Set<BridgeCapability>,
|
||||
) {
|
||||
require(capabilities.none { it.timed }) { "Timed capabilities require an expiry" }
|
||||
update(connectionId) { current -> current.copy(permanentGrants = capabilities) }
|
||||
}
|
||||
|
||||
suspend fun grantTimed(
|
||||
connectionId: String?,
|
||||
capability: BridgeCapability,
|
||||
expiresAtMs: Long,
|
||||
nowMs: Long = System.currentTimeMillis(),
|
||||
) {
|
||||
require(capability.timed) { "Permanent capabilities do not accept an expiry" }
|
||||
update(connectionId) { current ->
|
||||
current.copy(
|
||||
timedExpiriesMs = (
|
||||
current.timedExpiriesMs.filterValues { it > nowMs }.keys + capability
|
||||
)
|
||||
.associateWith { expiresAtMs },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun revoke(connectionId: String?, capability: BridgeCapability) {
|
||||
update(connectionId) { current ->
|
||||
current.copy(
|
||||
permanentGrants = current.permanentGrants - capability,
|
||||
timedExpiriesMs = current.timedExpiriesMs - capability,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun revokeTimed(connectionId: String?) {
|
||||
update(connectionId) { it.copy(timedExpiriesMs = emptyMap()) }
|
||||
}
|
||||
|
||||
suspend fun replaceTimed(
|
||||
connectionId: String?,
|
||||
capabilities: Set<BridgeCapability>,
|
||||
expiresAtMs: Long,
|
||||
) {
|
||||
require(capabilities.all { it.timed }) { "Permanent capabilities cannot be timed" }
|
||||
update(connectionId) { current ->
|
||||
current.copy(timedExpiriesMs = capabilities.associateWith { expiresAtMs })
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun refreshActiveTimed(connectionId: String?, expiresAtMs: Long) {
|
||||
update(connectionId) { current ->
|
||||
current.copy(
|
||||
timedExpiriesMs = current.timedExpiriesMs.mapNotNull { (capability, currentExpiry) ->
|
||||
when {
|
||||
currentExpiry == BridgeCapabilityPolicy.NEVER_EXPIRES_AT_MS ->
|
||||
capability to currentExpiry
|
||||
currentExpiry > System.currentTimeMillis() -> capability to expiresAtMs
|
||||
else -> null
|
||||
}
|
||||
}.toMap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun pruneExpired(connectionId: String?, nowMs: Long) {
|
||||
update(connectionId) { current ->
|
||||
current.copy(timedExpiriesMs = current.timedExpiriesMs.filterValues { it > nowMs })
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clearConnection(connectionId: String) {
|
||||
val key = connectionId.normalizedPolicyKey()
|
||||
context.relayDataStore.edit { prefs ->
|
||||
val current = readPolicies(prefs[KEY_POLICIES]).toMutableMap()
|
||||
current.remove(key)
|
||||
prefs[KEY_POLICIES] = json.encodeToString(
|
||||
StoredPolicies(installId = installId, byConnection = current),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun update(
|
||||
connectionId: String?,
|
||||
transform: (BridgeCapabilityPolicy) -> BridgeCapabilityPolicy,
|
||||
) {
|
||||
val key = connectionId.normalizedPolicyKey()
|
||||
context.relayDataStore.edit { prefs ->
|
||||
val current = readPolicies(prefs[KEY_POLICIES]).toMutableMap()
|
||||
current[key] = transform(current[key] ?: BridgeCapabilityPolicy())
|
||||
prefs[KEY_POLICIES] = json.encodeToString(
|
||||
StoredPolicies(installId = installId, byConnection = current),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun readPolicies(raw: String?): Map<String, BridgeCapabilityPolicy> {
|
||||
if (raw.isNullOrBlank()) return emptyMap()
|
||||
val stored = runCatching { json.decodeFromString<StoredPolicies>(raw) }.getOrNull()
|
||||
?: return emptyMap()
|
||||
if (stored.schemaVersion != BridgeCapabilityPolicy.CURRENT_SCHEMA_VERSION ||
|
||||
stored.installId != installId
|
||||
) return emptyMap()
|
||||
return stored.byConnection
|
||||
}
|
||||
|
||||
private fun String?.normalizedPolicyKey(): String =
|
||||
this?.trim()?.takeIf { it.isNotEmpty() } ?: "__unbound__"
|
||||
|
||||
private fun localInstallId(context: Context): String {
|
||||
val file = File(context.noBackupFilesDir, "bridge-policy-install-id")
|
||||
return runCatching {
|
||||
if (file.isFile) {
|
||||
file.readText().trim().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
} ?: UUID.randomUUID().toString().also { id ->
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(id)
|
||||
}
|
||||
}.getOrElse {
|
||||
// An unavailable no-backup fence must never make restored grants
|
||||
// usable. This process-only value causes every persisted read to
|
||||
// mismatch and therefore deny.
|
||||
"unavailable-${UUID.randomUUID()}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,11 @@ data class BridgeSettings(
|
||||
class BridgePreferencesRepository(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private val KEY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
|
||||
// v2 is deliberately separate. Older APKs know only the legacy key
|
||||
// and therefore remain disabled after a downgrade instead of treating
|
||||
// the new granular grants as blanket authority.
|
||||
private val KEY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled_v2")
|
||||
private val KEY_LEGACY_MASTER_ENABLED = booleanPreferencesKey("bridge_master_enabled")
|
||||
private val KEY_ACTIVITY_LOG = stringPreferencesKey("bridge_activity_log")
|
||||
|
||||
/** Hard cap on persisted entries. See file-level KDoc for rationale. */
|
||||
@@ -99,7 +103,10 @@ class BridgePreferencesRepository(private val context: Context) {
|
||||
}
|
||||
|
||||
suspend fun setMasterEnabled(enabled: Boolean) {
|
||||
context.relayDataStore.edit { it[KEY_MASTER_ENABLED] = enabled }
|
||||
context.relayDataStore.edit {
|
||||
it[KEY_MASTER_ENABLED] = enabled
|
||||
it[KEY_LEGACY_MASTER_ENABLED] = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,10 +29,9 @@ import kotlinx.serialization.json.Json
|
||||
* appear in `/tap_text` or `/type` payloads. Seeded with a set of verbs
|
||||
* that carry irreversible or high-stakes consequences. Editable.
|
||||
*
|
||||
* - [autoDisableMinutes] — idle timeout after which the master toggle
|
||||
* auto-flips to false. Rescheduled on every command so an active agent
|
||||
* never triggers it; a runaway agent that stops sending commands for
|
||||
* this long loses bridge access automatically.
|
||||
* - [autoDisableMinutes] — idle timeout for timed screen inspection and
|
||||
* control grants. Only accepted timed commands refresh it; permanent
|
||||
* read/action grants neither expire nor keep screen authority alive.
|
||||
*
|
||||
* - [statusOverlayEnabled] — opt-in floating-dot indicator (like the
|
||||
* screen-recording red dot) that's visible while bridge is active.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.BuildConfig
|
||||
|
||||
/** Immutable provenance embedded into side-by-side review and RC builds. */
|
||||
object CandidateBuild {
|
||||
val isCandidate: Boolean get() = BuildConfig.CANDIDATE_BUILD
|
||||
val kind: String get() = BuildConfig.CANDIDATE_KIND.ifBlank { "review" }
|
||||
val label: String get() = BuildConfig.CANDIDATE_LABEL.ifBlank { "Local review" }
|
||||
val sourceRef: String get() = BuildConfig.CANDIDATE_SOURCE_REF.ifBlank { "local" }
|
||||
val sourceSha: String get() = BuildConfig.CANDIDATE_SOURCE_SHA.ifBlank { "unknown" }
|
||||
val shortSha: String get() = sourceSha.take(12)
|
||||
|
||||
val heading: String
|
||||
get() = when (kind.lowercase()) {
|
||||
"rc", "release-candidate" -> "RELEASE CANDIDATE"
|
||||
else -> "REVIEW CANDIDATE"
|
||||
}
|
||||
|
||||
val provenance: String
|
||||
get() = listOf(label, shortSha)
|
||||
.filter { it.isNotBlank() && it != "unknown" }
|
||||
.joinToString(" · ")
|
||||
}
|
||||
@@ -1,9 +1,27 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
import java.util.WeakHashMap
|
||||
import java.nio.file.AtomicMoveNotSupportedException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/**
|
||||
* Immutable owner of one composer draft.
|
||||
@@ -86,15 +104,15 @@ data class ChatComposerDraft(
|
||||
*/
|
||||
interface ChatComposerDraftStore {
|
||||
fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft>
|
||||
fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
|
||||
fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
|
||||
fun update(
|
||||
suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
|
||||
suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
|
||||
suspend fun update(
|
||||
key: ChatComposerDraftKey,
|
||||
transform: (ChatComposerDraft) -> ChatComposerDraft,
|
||||
)
|
||||
fun remove(key: ChatComposerDraftKey)
|
||||
fun removeSession(connectionId: String, profileId: String, sessionId: String)
|
||||
fun clear()
|
||||
suspend fun remove(key: ChatComposerDraftKey)
|
||||
suspend fun removeSession(connectionId: String, profileId: String, sessionId: String)
|
||||
suspend fun clear()
|
||||
}
|
||||
|
||||
class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
|
||||
@@ -105,43 +123,370 @@ class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
|
||||
.map { it[key] ?: ChatComposerDraft() }
|
||||
.distinctUntilChanged()
|
||||
|
||||
override fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
|
||||
override suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
|
||||
drafts.value[key] ?: ChatComposerDraft()
|
||||
|
||||
@Synchronized
|
||||
override fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
|
||||
val normalized = draft.normalized()
|
||||
drafts.value = if (normalized.isEmpty) {
|
||||
drafts.value - key
|
||||
} else {
|
||||
drafts.value + (key to normalized)
|
||||
override suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
|
||||
synchronized(drafts) {
|
||||
val normalized = draft.normalized()
|
||||
drafts.value = if (normalized.isEmpty) {
|
||||
drafts.value - key
|
||||
} else {
|
||||
drafts.value + (key to normalized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun update(
|
||||
override suspend fun update(
|
||||
key: ChatComposerDraftKey,
|
||||
transform: (ChatComposerDraft) -> ChatComposerDraft,
|
||||
) {
|
||||
save(key, transform(snapshot(key)))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun remove(key: ChatComposerDraftKey) {
|
||||
drafts.value = drafts.value - key
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun removeSession(connectionId: String, profileId: String, sessionId: String) {
|
||||
drafts.value = drafts.value.filterKeys { key ->
|
||||
key.connectionId != connectionId ||
|
||||
key.profileId != profileId ||
|
||||
key.sessionId != sessionId
|
||||
override suspend fun remove(key: ChatComposerDraftKey) {
|
||||
synchronized(drafts) {
|
||||
drafts.value = drafts.value - key
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun clear() {
|
||||
drafts.value = emptyMap()
|
||||
override suspend fun removeSession(connectionId: String, profileId: String, sessionId: String) {
|
||||
synchronized(drafts) {
|
||||
drafts.value = drafts.value.filterKeys { key ->
|
||||
key.connectionId != connectionId ||
|
||||
key.profileId != profileId ||
|
||||
key.sessionId != sessionId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clear() {
|
||||
synchronized(drafts) {
|
||||
drafts.value = emptyMap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* App-private durable composer storage.
|
||||
*
|
||||
* The caller supplies a directory under `noBackupFilesDir`: drafts survive
|
||||
* process death and ordinary app exits but never enter Android cloud backup.
|
||||
* Metadata stays small JSON while attachment bytes are content-addressed blobs,
|
||||
* so typing does not repeatedly rewrite Base64 payloads.
|
||||
*/
|
||||
class PersistentChatComposerDraftStore(
|
||||
private val root: File,
|
||||
) : ChatComposerDraftStore {
|
||||
private val mutex = Mutex()
|
||||
private val updates = MutableSharedFlow<ChatComposerDraftKey>(extraBufferCapacity = 64)
|
||||
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||
private val draftsDir = File(root, "drafts")
|
||||
private val blobsDir = File(root, "blobs")
|
||||
private val contentBlobIds = WeakHashMap<String, String>()
|
||||
|
||||
override fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft> = flow {
|
||||
emit(snapshot(key))
|
||||
emitAll(
|
||||
updates
|
||||
.filter { it == key }
|
||||
.map { snapshot(key) }
|
||||
.distinctUntilChanged(),
|
||||
)
|
||||
}.distinctUntilChanged()
|
||||
|
||||
override suspend fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft = withContext(Dispatchers.IO) {
|
||||
mutex.withLock { readDraft(key) }
|
||||
}
|
||||
|
||||
override suspend fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
|
||||
withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val normalized = draft.normalized()
|
||||
if (normalized.isEmpty) {
|
||||
draftFile(key).delete()
|
||||
} else {
|
||||
ensureDirectories()
|
||||
val persisted = normalized.toPersisted(key)
|
||||
atomicWrite(
|
||||
draftFile(key),
|
||||
json.encodeToString(PersistedDraft.serializer(), persisted)
|
||||
.toByteArray(Charsets.UTF_8),
|
||||
)
|
||||
}
|
||||
pruneAndCollect(except = key)
|
||||
}
|
||||
}
|
||||
updates.tryEmit(key)
|
||||
}
|
||||
|
||||
override suspend fun update(
|
||||
key: ChatComposerDraftKey,
|
||||
transform: (ChatComposerDraft) -> ChatComposerDraft,
|
||||
) {
|
||||
withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val normalized = transform(readDraft(key)).normalized()
|
||||
if (normalized.isEmpty) {
|
||||
draftFile(key).delete()
|
||||
} else {
|
||||
ensureDirectories()
|
||||
atomicWrite(
|
||||
draftFile(key),
|
||||
json.encodeToString(
|
||||
PersistedDraft.serializer(),
|
||||
normalized.toPersisted(key),
|
||||
).toByteArray(Charsets.UTF_8),
|
||||
)
|
||||
}
|
||||
pruneAndCollect(except = key)
|
||||
}
|
||||
}
|
||||
updates.tryEmit(key)
|
||||
}
|
||||
|
||||
override suspend fun remove(key: ChatComposerDraftKey) {
|
||||
withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
draftFile(key).delete()
|
||||
collectOrphanBlobs()
|
||||
}
|
||||
}
|
||||
updates.tryEmit(key)
|
||||
}
|
||||
|
||||
override suspend fun removeSession(connectionId: String, profileId: String, sessionId: String) {
|
||||
val removed = mutableListOf<ChatComposerDraftKey>()
|
||||
withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
draftFiles().forEach { file ->
|
||||
val persisted = readPersisted(file) ?: return@forEach
|
||||
val key = persisted.key.toDomain()
|
||||
if (
|
||||
key.connectionId == connectionId &&
|
||||
key.profileId == profileId &&
|
||||
key.sessionId == sessionId
|
||||
) {
|
||||
file.delete()
|
||||
removed += key
|
||||
}
|
||||
}
|
||||
collectOrphanBlobs()
|
||||
}
|
||||
}
|
||||
removed.forEach(updates::tryEmit)
|
||||
}
|
||||
|
||||
override suspend fun clear() {
|
||||
withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
root.listFiles().orEmpty().forEach(File::deleteRecursively)
|
||||
contentBlobIds.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ChatComposerDraft.toPersisted(key: ChatComposerDraftKey): PersistedDraft =
|
||||
PersistedDraft(
|
||||
key = PersistedKey.from(key),
|
||||
text = text,
|
||||
selectionStart = selectionStart,
|
||||
selectionEnd = selectionEnd,
|
||||
quotedMessageId = context.quotedMessageId,
|
||||
editingMessageId = context.editingMessageId,
|
||||
attachments = attachments.mapNotNull(::persistAttachment),
|
||||
savedAtEpochMs = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
private fun persistAttachment(attachment: Attachment): PersistedAttachment? {
|
||||
val rawBytes = attachment.composerRawText
|
||||
?.takeIf { attachment.isLargePaste }
|
||||
?.toByteArray(Charsets.UTF_8)
|
||||
val cachedBlobId = if (rawBytes == null) contentBlobIds[attachment.content] else null
|
||||
val cachedBlob = cachedBlobId?.let { File(blobsDir, "$it.blob") }
|
||||
if (cachedBlobId != null && cachedBlob?.exists() == true) {
|
||||
return attachment.toPersistedAttachment(cachedBlobId)
|
||||
}
|
||||
val bytes = rawBytes
|
||||
?: runCatching { Base64.getDecoder().decode(attachment.content) }.getOrNull()
|
||||
?: return null
|
||||
if (bytes.isEmpty()) return null
|
||||
val blobId = sha256(bytes)
|
||||
val blob = File(blobsDir, "$blobId.blob")
|
||||
if (!blob.exists()) atomicWrite(blob, bytes)
|
||||
if (rawBytes == null) contentBlobIds[attachment.content] = blobId
|
||||
return attachment.toPersistedAttachment(blobId)
|
||||
}
|
||||
|
||||
private fun Attachment.toPersistedAttachment(blobId: String): PersistedAttachment =
|
||||
PersistedAttachment(
|
||||
contentType = contentType,
|
||||
blobId = blobId,
|
||||
fileName = fileName,
|
||||
fileSize = fileSize,
|
||||
sensitive = sensitive,
|
||||
isLargePaste = isLargePaste,
|
||||
composerId = composerId,
|
||||
)
|
||||
|
||||
private fun readDraft(key: ChatComposerDraftKey): ChatComposerDraft {
|
||||
val persisted = readPersisted(draftFile(key)) ?: return ChatComposerDraft()
|
||||
if (persisted.key.toDomain() != key) return ChatComposerDraft()
|
||||
return ChatComposerDraft(
|
||||
text = persisted.text,
|
||||
selectionStart = persisted.selectionStart,
|
||||
selectionEnd = persisted.selectionEnd,
|
||||
context = ChatComposerDraftContext(
|
||||
quotedMessageId = persisted.quotedMessageId,
|
||||
editingMessageId = persisted.editingMessageId,
|
||||
),
|
||||
attachments = persisted.attachments.mapNotNull { attachment ->
|
||||
val blob = File(blobsDir, "${attachment.blobId}.blob")
|
||||
val bytes = runCatching { blob.readBytes() }.getOrNull()
|
||||
?.takeIf(ByteArray::isNotEmpty) ?: return@mapNotNull null
|
||||
val content = Base64.getEncoder().encodeToString(bytes)
|
||||
contentBlobIds[content] = attachment.blobId
|
||||
Attachment(
|
||||
contentType = attachment.contentType,
|
||||
content = content,
|
||||
fileName = attachment.fileName,
|
||||
fileSize = attachment.fileSize ?: bytes.size.toLong(),
|
||||
sensitive = attachment.sensitive,
|
||||
isLargePaste = attachment.isLargePaste,
|
||||
composerId = attachment.composerId,
|
||||
)
|
||||
},
|
||||
).normalized()
|
||||
}
|
||||
|
||||
private fun readPersisted(file: File): PersistedDraft? = runCatching {
|
||||
json.decodeFromString(PersistedDraft.serializer(), file.readText(Charsets.UTF_8))
|
||||
}.getOrNull()
|
||||
|
||||
private fun pruneAndCollect(except: ChatComposerDraftKey) {
|
||||
val exceptFile = draftFile(except)
|
||||
val candidates = draftFiles()
|
||||
.filterNot { it == exceptFile }
|
||||
.sortedBy(File::lastModified)
|
||||
candidates
|
||||
.take((draftFiles().size - MAX_DRAFTS).coerceAtLeast(0))
|
||||
.forEach { it.delete() }
|
||||
collectOrphanBlobs()
|
||||
for (oldest in candidates) {
|
||||
if (blobsDir.listFiles().orEmpty().sumOf(File::length) <= MAX_BLOB_BYTES) break
|
||||
if (oldest.exists()) {
|
||||
oldest.delete()
|
||||
collectOrphanBlobs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun collectOrphanBlobs() {
|
||||
val referenced = draftFiles()
|
||||
.mapNotNull(::readPersisted)
|
||||
.flatMap { draft -> draft.attachments.map(PersistedAttachment::blobId) }
|
||||
.toSet()
|
||||
blobsDir.listFiles().orEmpty()
|
||||
.filter { it.isFile && it.extension == "blob" && it.nameWithoutExtension !in referenced }
|
||||
.forEach(File::delete)
|
||||
}
|
||||
|
||||
private fun ensureDirectories() {
|
||||
check(draftsDir.exists() || draftsDir.mkdirs()) { "Could not create composer draft directory" }
|
||||
check(blobsDir.exists() || blobsDir.mkdirs()) { "Could not create composer blob directory" }
|
||||
}
|
||||
|
||||
private fun draftFiles(): List<File> = draftsDir.listFiles().orEmpty()
|
||||
.filter { it.isFile && it.extension == "json" }
|
||||
|
||||
private fun draftFile(key: ChatComposerDraftKey): File =
|
||||
File(draftsDir, "${sha256(key.storageIdentity().toByteArray(Charsets.UTF_8))}.json")
|
||||
|
||||
private fun atomicWrite(target: File, bytes: ByteArray) {
|
||||
target.parentFile?.let { parent ->
|
||||
check(parent.exists() || parent.mkdirs()) { "Could not create composer storage directory" }
|
||||
}
|
||||
val temporary = File(target.parentFile, ".${target.name}.${System.nanoTime()}.tmp")
|
||||
try {
|
||||
FileOutputStream(temporary).use { output ->
|
||||
output.write(bytes)
|
||||
output.fd.sync()
|
||||
}
|
||||
try {
|
||||
Files.move(
|
||||
temporary.toPath(),
|
||||
target.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
} catch (_: AtomicMoveNotSupportedException) {
|
||||
Files.move(
|
||||
temporary.toPath(),
|
||||
target.toPath(),
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
temporary.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun ChatComposerDraftKey.storageIdentity(): String =
|
||||
listOf(connectionId, profileId, sessionId, draftId).joinToString("\u0000")
|
||||
|
||||
private fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256")
|
||||
.digest(bytes)
|
||||
.joinToString("") { byte -> "%02x".format(byte) }
|
||||
|
||||
companion object {
|
||||
private const val MAX_DRAFTS = 64
|
||||
private const val MAX_BLOB_BYTES = 128L * 1024L * 1024L
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedDraft(
|
||||
val key: PersistedKey,
|
||||
val text: String,
|
||||
val selectionStart: Int,
|
||||
val selectionEnd: Int,
|
||||
val quotedMessageId: String? = null,
|
||||
val editingMessageId: String? = null,
|
||||
val attachments: List<PersistedAttachment> = emptyList(),
|
||||
val savedAtEpochMs: Long,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class PersistedKey(
|
||||
val connectionId: String,
|
||||
val profileId: String,
|
||||
val sessionId: String,
|
||||
val draftId: String,
|
||||
) {
|
||||
fun toDomain(): ChatComposerDraftKey = ChatComposerDraftKey(
|
||||
connectionId = connectionId,
|
||||
profileId = profileId,
|
||||
sessionId = sessionId,
|
||||
draftId = draftId,
|
||||
)
|
||||
|
||||
companion object {
|
||||
fun from(key: ChatComposerDraftKey): PersistedKey = PersistedKey(
|
||||
connectionId = key.connectionId,
|
||||
profileId = key.profileId,
|
||||
sessionId = key.sessionId,
|
||||
draftId = key.draftId,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedAttachment(
|
||||
val contentType: String,
|
||||
val blobId: String,
|
||||
val fileName: String? = null,
|
||||
val fileSize: Long? = null,
|
||||
val sensitive: Boolean = false,
|
||||
val isLargePaste: Boolean = false,
|
||||
val composerId: String? = null,
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.hermesandroid.relay.data
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -30,6 +31,8 @@ class ChatInputPreferencesRepository(
|
||||
companion object {
|
||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
internal val KEY_CONVERT_LARGE_PASTES =
|
||||
booleanPreferencesKey("convert_large_pastes_to_attachments")
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: Flow<PhysicalKeyboardEnterBehavior> = dataStore.data
|
||||
@@ -40,9 +43,19 @@ class ChatInputPreferencesRepository(
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_PHYSICAL_KEYBOARD_ENTER] = behavior.storedValue
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setConvertLargePastesToAttachments(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_CONVERT_LARGE_PASTES] = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import java.util.Base64
|
||||
|
||||
const val LARGE_PASTE_THRESHOLD_CHARS = 5_000
|
||||
|
||||
data class TextTransportAttachments(
|
||||
val message: String,
|
||||
val attachments: List<Attachment>,
|
||||
)
|
||||
|
||||
fun largePasteAttachment(text: String, composerId: String? = null): Attachment {
|
||||
val bytes = text.toByteArray(Charsets.UTF_8)
|
||||
return Attachment(
|
||||
contentType = "text/plain; charset=utf-8",
|
||||
content = Base64.getEncoder().encodeToString(bytes),
|
||||
fileName = "pasted-text.txt",
|
||||
fileSize = bytes.size.toLong(),
|
||||
isLargePaste = true,
|
||||
composerId = composerId,
|
||||
)
|
||||
}
|
||||
|
||||
fun prepareTextTransportAttachments(
|
||||
message: String,
|
||||
attachments: List<Attachment>,
|
||||
): TextTransportAttachments {
|
||||
val largePastes = attachments.filter(Attachment::isLargePaste)
|
||||
if (largePastes.isEmpty()) return TextTransportAttachments(message, attachments)
|
||||
|
||||
val materialized = largePastes.mapNotNull { attachment ->
|
||||
runCatching {
|
||||
val text = String(Base64.getDecoder().decode(attachment.content), Charsets.UTF_8)
|
||||
val name = attachment.fileName?.takeIf(String::isNotBlank) ?: "pasted text"
|
||||
"--- $name ---\n$text"
|
||||
}.getOrNull()
|
||||
}
|
||||
return TextTransportAttachments(
|
||||
message = (listOf(message) + materialized)
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("\n\n"),
|
||||
attachments = attachments.filterNot(Attachment::isLargePaste),
|
||||
)
|
||||
}
|
||||
@@ -141,6 +141,18 @@ data class ChatMessage(
|
||||
* through `copy`, while [id] remains the authoritative lookup/wire id.
|
||||
*/
|
||||
val uiKey: String = id,
|
||||
/**
|
||||
* Durable Gateway transcript row identity for rewind/edit-regenerate.
|
||||
* This is server-owned and can change after a truncating rewrite; it is
|
||||
* never used as a Compose key or synthesized client-side.
|
||||
*/
|
||||
val rowId: Long? = null,
|
||||
/**
|
||||
* Durable iOS-style tapbacks attached to this server message. Hermes keeps
|
||||
* one reaction per author in the message's display metadata; the UI also
|
||||
* updates this list optimistically while a reaction write is in flight.
|
||||
*/
|
||||
val reactions: List<MessageReaction> = emptyList(),
|
||||
/**
|
||||
* Mixture-of-Agents advisor responses surfaced during the live turn.
|
||||
* Unavailable advisors retain only neutral state, never their raw failure
|
||||
@@ -150,6 +162,29 @@ data class ChatMessage(
|
||||
val moaReferences: List<MoaReference> = emptyList(),
|
||||
)
|
||||
|
||||
data class MessageReaction(
|
||||
val emoji: String,
|
||||
val author: String,
|
||||
/** Epoch seconds, matching the Gateway/Desktop contract. */
|
||||
val at: Double,
|
||||
)
|
||||
|
||||
/** Apply Hermes' one-reaction-per-author, re-tap-to-retract semantics. */
|
||||
internal fun applyMessageReaction(
|
||||
reactions: List<MessageReaction>,
|
||||
emoji: String?,
|
||||
author: String = "user",
|
||||
at: Double = System.currentTimeMillis() / 1000.0,
|
||||
): List<MessageReaction> {
|
||||
val previous = reactions.firstOrNull { it.author == author }
|
||||
val withoutAuthor = reactions.filterNot { it.author == author }
|
||||
return if (emoji.isNullOrBlank() || previous?.emoji == emoji) {
|
||||
withoutAuthor
|
||||
} else {
|
||||
withoutAuthor + MessageReaction(emoji = emoji, author = author, at = at)
|
||||
}
|
||||
}
|
||||
|
||||
data class MoaReference(
|
||||
val index: Int,
|
||||
val count: Int?,
|
||||
@@ -293,7 +328,13 @@ data class Attachment(
|
||||
* existing outbound/inbound call site stays valid and unflagged media
|
||||
* renders exactly as before.
|
||||
*/
|
||||
val sensitive: Boolean = false
|
||||
val sensitive: Boolean = false,
|
||||
/** Local composer metadata; never serialized onto the Hermes wire. */
|
||||
val isLargePaste: Boolean = false,
|
||||
/** Stable id for an asynchronous composer preparation; never sent to Hermes. */
|
||||
val composerId: String? = null,
|
||||
/** Raw UTF-8 text retained only while a large-paste attachment is preparing. */
|
||||
val composerRawText: String? = null,
|
||||
) {
|
||||
val isImage: Boolean get() = contentType.startsWith("image/")
|
||||
|
||||
@@ -366,6 +407,8 @@ data class ToolCall(
|
||||
* header can render without a separate lane registry.
|
||||
*/
|
||||
val taskLabel: String? = null,
|
||||
/** Live upstream child id used by subagent.steer while this lane runs. */
|
||||
val subagentId: String? = null,
|
||||
/** Deterministic non-low output risk reported by upstream for this call. */
|
||||
val outputRisk: String? = null,
|
||||
/** Human-readable deterministic findings; rendered as untrusted metadata. */
|
||||
@@ -404,6 +447,11 @@ data class ChatSession(
|
||||
val title: String?,
|
||||
val model: String?,
|
||||
val messageCount: Int = 0,
|
||||
val inputTokens: Int = 0,
|
||||
val outputTokens: Int = 0,
|
||||
val actualCostUsd: Double? = null,
|
||||
val estimatedCostUsd: Double? = null,
|
||||
val isActive: Boolean = false,
|
||||
val updatedAt: Long = 0L,
|
||||
val startedAt: Long = 0L,
|
||||
val lastActivityAt: Long = 0L,
|
||||
@@ -419,7 +467,21 @@ data class ChatSession(
|
||||
/** Durable upstream session metadata, scoped by the owning connection/profile DB. */
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
/** Optional newer-upstream workspace context; absent on legacy/API-only hosts. */
|
||||
val workingDirectory: String? = null,
|
||||
val gitBranch: String? = null,
|
||||
val gitRepoRoot: String? = null,
|
||||
val pullRequestNumber: Int? = null,
|
||||
val pullRequestUrl: String? = null,
|
||||
val pullRequestState: String? = null,
|
||||
val pullRequestDraft: Boolean = false,
|
||||
) {
|
||||
val totalTokens: Int
|
||||
get() = inputTokens + outputTokens
|
||||
|
||||
val costUsd: Double
|
||||
get() = actualCostUsd ?: estimatedCostUsd ?: 0.0
|
||||
|
||||
val activityTimestamp: Long
|
||||
get() = firstPositive(lastActivityAt, updatedAt, startedAt)
|
||||
|
||||
|
||||
@@ -129,6 +129,7 @@ data class ChatTurnAskCheckpoint(
|
||||
val requestId: String? = null,
|
||||
val text: String,
|
||||
val choices: List<String>? = null,
|
||||
val multiSelect: Boolean = false,
|
||||
val smartDenied: Boolean = false,
|
||||
val envVar: String? = null,
|
||||
val timeoutSeconds: Int,
|
||||
|
||||
@@ -14,6 +14,9 @@ data class DashboardConnectionStatus(
|
||||
val gatewayTicketAvailable: Boolean? = null,
|
||||
val message: String? = null,
|
||||
val gatewayMode: String? = null,
|
||||
/** Profiles positively advertised by the live multiplex gateway. */
|
||||
val servedProfiles: List<String> = emptyList(),
|
||||
/** Installed profiles reported by the dashboard; never routing authority. */
|
||||
val profiles: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
|
||||
@@ -63,12 +63,8 @@ fun EndpointCandidate?.isEncryptedOverlayRoute(isTailscaleDetected: Boolean): Bo
|
||||
val hint = security.orEmpty().lowercase()
|
||||
return r == "tailscale" ||
|
||||
(isTailscaleDetected && hint.contains("tailscale")) ||
|
||||
r == "plugin_proxy" ||
|
||||
r == "plugin-proxy" ||
|
||||
hasSecureProxy() ||
|
||||
hint.contains("wireguard") ||
|
||||
hint.contains("https") ||
|
||||
hint.contains("tls")
|
||||
(!hasSecureProxy() && (hint.contains("https") || hint.contains("tls")))
|
||||
}
|
||||
|
||||
/** Human label for the overlay mechanism encrypting a route. */
|
||||
@@ -78,7 +74,6 @@ fun EndpointCandidate?.overlayMechanism(isTailscaleDetected: Boolean): String {
|
||||
val hint = security.orEmpty().lowercase()
|
||||
return when {
|
||||
r == "tailscale" || (isTailscaleDetected && hint.contains("tailscale")) -> "Tailscale"
|
||||
r == "plugin_proxy" || r == "plugin-proxy" || hasSecureProxy() -> "Proxy"
|
||||
hint.contains("wireguard") -> "WireGuard"
|
||||
hint.contains("https") || hint.contains("tls") -> "TLS"
|
||||
else -> "Encrypted"
|
||||
@@ -92,7 +87,10 @@ fun classifySurfaceSecurity(
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
): SurfaceSecurity {
|
||||
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
|
||||
val (kind, mechanism) = when {
|
||||
secureLinkProtected -> SurfaceSecurityKind.Tls to
|
||||
if (activeEndpoint?.hasHermesReach() == true) "Hermes Reach" else "Hermes Secure Link"
|
||||
isTlsUrl(url) -> SurfaceSecurityKind.Tls to "TLS"
|
||||
activeEndpoint.isEncryptedOverlayRoute(isTailscaleDetected) ->
|
||||
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
|
||||
@@ -101,6 +99,33 @@ fun classifySurfaceSecurity(
|
||||
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
|
||||
}
|
||||
|
||||
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
|
||||
val candidate = this ?: return false
|
||||
val routes = candidate.proxy?.takeIf { candidate.hasSecureProxy() }
|
||||
?.let { proxy ->
|
||||
val base = proxy.url.trim().trimEnd('/')
|
||||
Triple(
|
||||
"$base/dashboard",
|
||||
"$base/api",
|
||||
"wss://${base.substringAfter("://")}/relay/ws",
|
||||
)
|
||||
} ?: return false
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage" -> "dashboard"
|
||||
"API / sessions" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
if (service !in candidate.secureLinkServices()) return false
|
||||
val expected = when (service) {
|
||||
"dashboard" -> routes.first
|
||||
"api" -> routes.second
|
||||
else -> routes.third
|
||||
}
|
||||
return normalized.equals(expected, ignoreCase = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Roll up the per-surface verdicts into one connection-level [ConnectionSecurity].
|
||||
* Pure + side-effect free so it is unit-testable without Android.
|
||||
|
||||
@@ -45,12 +45,13 @@ object ConnectionValidation {
|
||||
kind = "API server URL",
|
||||
)
|
||||
|
||||
/** Relay URL must be ws:// or wss:// with a host. */
|
||||
fun validateRelayUrl(raw: String): String? = validateUrl(
|
||||
raw = raw,
|
||||
allowedSchemes = setOf("ws", "wss"),
|
||||
kind = "relay URL",
|
||||
)
|
||||
/** Relay URL may identify its base, WebSocket route, or health route. */
|
||||
fun validateRelayUrl(raw: String): String? {
|
||||
if (raw.isBlank()) return "relay URL can't be blank"
|
||||
return runCatching { RelayEndpointContract.parse(raw) }
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
}
|
||||
|
||||
/** Dashboard/Gateway URL must be HTTP(S) when configured. */
|
||||
fun validateDashboardUrl(raw: String): String? = validateOptionalUrl(
|
||||
@@ -67,11 +68,8 @@ object ConnectionValidation {
|
||||
)
|
||||
|
||||
/** A blank Relay URL means Relay-only power features are not configured. */
|
||||
fun validateOptionalRelayUrl(raw: String): String? = validateOptionalUrl(
|
||||
raw = raw,
|
||||
allowedSchemes = setOf("ws", "wss"),
|
||||
kind = "relay URL",
|
||||
)
|
||||
fun validateOptionalRelayUrl(raw: String): String? =
|
||||
if (raw.isBlank()) null else validateRelayUrl(raw)
|
||||
|
||||
/**
|
||||
* Validate the independently optional connection surfaces. A connection
|
||||
@@ -114,7 +112,7 @@ object ConnectionValidation {
|
||||
val legacyExactMatch =
|
||||
(apiServerUrl.isNotBlank() || relayUrl.isNotBlank()) &&
|
||||
urlsEqual(c.apiServerUrl, apiServerUrl) &&
|
||||
urlsEqual(c.relayUrl, relayUrl)
|
||||
relayUrlsEqual(c.relayUrl, relayUrl)
|
||||
val candidateDashboard = dashboardUrl
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: Connection.deriveDefaultDashboardUrl(apiServerUrl)
|
||||
@@ -133,6 +131,12 @@ object ConnectionValidation {
|
||||
private fun urlsEqual(first: String, second: String): Boolean =
|
||||
first.trim().trimEnd('/').equals(second.trim().trimEnd('/'), ignoreCase = true)
|
||||
|
||||
private fun relayUrlsEqual(first: String, second: String): Boolean {
|
||||
val left = RelayEndpointContract.parseOrNull(first)?.webSocketUrl ?: return urlsEqual(first, second)
|
||||
val right = RelayEndpointContract.parseOrNull(second)?.webSocketUrl ?: return urlsEqual(first, second)
|
||||
return left.equals(right, ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun validateUrl(raw: String, allowedSchemes: Set<String>, kind: String): String? {
|
||||
val trimmed = raw.trim()
|
||||
if (trimmed.isEmpty()) return "$kind can't be blank"
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceShape
|
||||
import com.hermesandroid.relay.ui.theme.normalizeAccentHex
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CustomThemePreset(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val mode: String,
|
||||
val backgroundHex: String,
|
||||
val surfaceHex: String,
|
||||
val accentHex: String,
|
||||
val textHex: String,
|
||||
val shapeId: String = AppearanceShape.DEFAULT.id,
|
||||
) {
|
||||
val appThemeId: String get() = "$APP_THEME_PREFIX$id"
|
||||
val isDark: Boolean get() = mode != MODE_LIGHT
|
||||
|
||||
fun normalized(): CustomThemePreset? {
|
||||
val normalizedId = id.trim().take(64).takeIf { it.matches(ID_PATTERN) } ?: return null
|
||||
val normalizedName = name.trim().replace(WHITESPACE, " ").take(MAX_NAME_LENGTH)
|
||||
.takeIf(String::isNotBlank) ?: return null
|
||||
return copy(
|
||||
id = normalizedId,
|
||||
name = normalizedName,
|
||||
mode = if (mode == MODE_LIGHT) MODE_LIGHT else MODE_DARK,
|
||||
backgroundHex = normalizeAccentHex(backgroundHex) ?: return null,
|
||||
surfaceHex = normalizeAccentHex(surfaceHex) ?: return null,
|
||||
accentHex = normalizeAccentHex(accentHex) ?: return null,
|
||||
textHex = normalizeAccentHex(textHex) ?: return null,
|
||||
shapeId = AppearanceShape.fromId(shapeId).id,
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val APP_THEME_PREFIX = "custom:"
|
||||
const val MODE_LIGHT = "light"
|
||||
const val MODE_DARK = "dark"
|
||||
const val MAX_PRESETS = 20
|
||||
const val MAX_NAME_LENGTH = 24
|
||||
|
||||
private val ID_PATTERN = Regex("[A-Za-z0-9_-]+")
|
||||
private val WHITESPACE = Regex("\\s+")
|
||||
|
||||
fun idFromAppTheme(appThemeId: String?): String? = appThemeId
|
||||
?.takeIf { it.startsWith(APP_THEME_PREFIX) }
|
||||
?.removePrefix(APP_THEME_PREFIX)
|
||||
?.takeIf(String::isNotBlank)
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,11 @@ class DataManager(
|
||||
|
||||
suspend fun restoreConnectionBackup(backup: AppBackup) {
|
||||
val store = connectionStore ?: return
|
||||
// Validate every credential before deleting or replacing any current
|
||||
// encrypted state. A malformed/hostile backup fails atomically.
|
||||
backup.connectionSecrets.forEach { secret ->
|
||||
AuthManager.validateStoredSecrets(secret.auth)
|
||||
}
|
||||
deleteSensitivePreferenceFiles()
|
||||
store.replaceConnections(
|
||||
connections = backup.connections,
|
||||
|
||||
@@ -45,8 +45,13 @@ data class EndpointCandidate(
|
||||
val relay: RelayEndpoint? = null,
|
||||
val dashboard: DashboardEndpoint? = null,
|
||||
val proxy: ProxyEndpoint? = null,
|
||||
/** Optional outbound rendezvous carrying the pinned [proxy] byte stream. */
|
||||
val broker: BrokerEndpoint? = null,
|
||||
val security: String? = null,
|
||||
val recommended: Boolean = false,
|
||||
val experimental: Boolean = false,
|
||||
@SerialName("display_name")
|
||||
val displayName: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -110,6 +115,27 @@ data class ProxyEndpoint(
|
||||
val transportHint: String? = null,
|
||||
@SerialName("pin_sha256")
|
||||
val pinSha256: String? = null,
|
||||
/** Independently authenticated services carried by this pinned origin. */
|
||||
val surfaces: List<String> = listOf("relay"),
|
||||
)
|
||||
|
||||
/**
|
||||
* Hermes Reach rendezvous metadata from an operator-reviewed pairing payload.
|
||||
* The token authenticates only this broker route; Hermes service credentials
|
||||
* remain inside the QR-pinned Secure Link TLS connection.
|
||||
*/
|
||||
@Serializable
|
||||
data class BrokerEndpoint(
|
||||
val url: String,
|
||||
@SerialName("protocol_version")
|
||||
val protocolVersion: Int = 1,
|
||||
@SerialName("host_id")
|
||||
val hostId: String,
|
||||
@SerialName("credential_kind")
|
||||
val credentialKind: String,
|
||||
val token: String,
|
||||
@SerialName("expires_at")
|
||||
val expiresAt: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -123,7 +149,7 @@ data class ProxyEndpoint(
|
||||
*/
|
||||
fun EndpointCandidate.isKnownRole(): Boolean {
|
||||
return when (role.lowercase()) {
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "https" -> true
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
@@ -146,7 +172,8 @@ fun EndpointCandidate.displayLabel(): String {
|
||||
"Public"
|
||||
}
|
||||
"https" -> "HTTPS"
|
||||
"plugin_proxy", "plugin-proxy" -> "Plugin proxy"
|
||||
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
|
||||
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
|
||||
else -> "Custom VPN ($role)"
|
||||
}
|
||||
}
|
||||
@@ -177,7 +204,69 @@ fun EndpointCandidate.routeAuthority(): String? {
|
||||
}
|
||||
|
||||
fun EndpointCandidate.hasSecureProxy(): Boolean =
|
||||
proxy?.url?.startsWith("https://", ignoreCase = true) == true ||
|
||||
proxy?.url?.startsWith("wss://", ignoreCase = true) == true ||
|
||||
role.equals("plugin_proxy", ignoreCase = true) ||
|
||||
role.equals("plugin-proxy", ignoreCase = true)
|
||||
proxy?.isValidPinnedProxy() == true
|
||||
|
||||
/** Product-facing service inventory; wire identifiers remain unchanged. */
|
||||
fun EndpointCandidate.secureLinkServices(): List<String> =
|
||||
if (!hasSecureProxy()) emptyList() else proxy.orEmptySurfaces()
|
||||
|
||||
fun EndpointCandidate.secureLinkCoversAllServices(): Boolean =
|
||||
secureLinkServices().containsAll(listOf("relay", "api", "dashboard"))
|
||||
|
||||
fun EndpointCandidate.presentationRouteUrl(): String? =
|
||||
broker?.url?.takeIf { hasHermesReach() } ?: proxy?.url?.takeIf { hasSecureProxy() } ?: primaryRouteUrl()
|
||||
|
||||
fun EndpointCandidate.hasHermesReach(): Boolean =
|
||||
role.lowercase() in setOf("outbound_broker", "broker", "relay_broker") &&
|
||||
broker?.isValidHermesReach() == true && hasSecureProxy()
|
||||
|
||||
fun BrokerEndpoint.isValidHermesReach(): Boolean {
|
||||
if (protocolVersion != 1 || !hostId.isCanonicalBase64Url(16) || !token.isCanonicalBase64Url(32)) return false
|
||||
if (credentialKind !in setOf("bootstrap", "route")) return false
|
||||
if (credentialKind == "bootstrap" && expiresAt?.let { it <= System.currentTimeMillis() / 1000L } == true) return false
|
||||
val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false
|
||||
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return false
|
||||
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
|
||||
return uri.rawPath.orEmpty().let { it.isEmpty() || it == "/" || it == "/v1/connect" }
|
||||
}
|
||||
|
||||
private fun String.isCanonicalBase64Url(byteCount: Int): Boolean {
|
||||
if (isBlank() || '=' in this) return false
|
||||
val decoded = runCatching { java.util.Base64.getUrlDecoder().decode(this) }.getOrNull() ?: return false
|
||||
return decoded.size == byteCount &&
|
||||
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == this
|
||||
}
|
||||
|
||||
/** Exact host locator + broker authority replacement; never crosses devices. */
|
||||
internal fun replaceHermesReachCredential(
|
||||
source: List<EndpointCandidate>,
|
||||
expected: BrokerEndpoint,
|
||||
replacement: EndpointCandidate,
|
||||
): List<EndpointCandidate> = source.map { candidate ->
|
||||
if (candidate.broker?.hostId == expected.hostId &&
|
||||
sameBrokerAuthority(candidate.broker.url, expected.url)
|
||||
) replacement else candidate
|
||||
}
|
||||
|
||||
internal fun sameBrokerAuthority(left: String, right: String): Boolean = runCatching {
|
||||
val a = URI(left.trim())
|
||||
val b = URI(right.trim())
|
||||
fun port(uri: URI) = if (uri.port > 0) uri.port else 443
|
||||
a.scheme.equals("wss", true) && b.scheme.equals("wss", true) &&
|
||||
a.host.equals(b.host, true) && port(a) == port(b) &&
|
||||
a.rawPath.orEmpty().trimEnd('/') == b.rawPath.orEmpty().trimEnd('/')
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun ProxyEndpoint?.orEmptySurfaces(): List<String> = this?.surfaces.orEmpty()
|
||||
.map { it.trim().lowercase() }
|
||||
.filter { it in setOf("relay", "api", "dashboard") }
|
||||
.distinct()
|
||||
|
||||
fun ProxyEndpoint.isValidPinnedProxy(): Boolean {
|
||||
val uri = runCatching { URI(url.trim().trimEnd('/')) }.getOrNull() ?: return false
|
||||
if (!uri.scheme.equals("https", ignoreCase = true) || uri.host.isNullOrBlank()) return false
|
||||
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
|
||||
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" }) return false
|
||||
val pin = pinSha256?.trim()?.removePrefix("sha256/") ?: return false
|
||||
return runCatching { java.util.Base64.getDecoder().decode(pin).size == 32 }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -139,5 +139,5 @@ object BuildFlavor {
|
||||
GOOGLE_PLAY -> "Google Play"
|
||||
SIDELOAD -> "Sideload"
|
||||
else -> current.ifBlank { "Unknown" }
|
||||
}
|
||||
} + if (CandidateBuild.isCandidate) " Candidate" else ""
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/**
|
||||
* A rich content card emitted inline in an assistant message via the
|
||||
@@ -117,6 +119,8 @@ data class HermesCardInput(
|
||||
val kind: String,
|
||||
/** Quick-answer chips (clarify). Empty = no chip row. */
|
||||
val choices: List<String> = emptyList(),
|
||||
/** Choices toggle independently and require an explicit submit. */
|
||||
val multiSelect: Boolean = false,
|
||||
/** Render the inline free-text mini field under the chips. */
|
||||
val allowFreeText: Boolean = false,
|
||||
/** Password-style field: masked glyphs + reveal toggle (secret/sudo). */
|
||||
@@ -124,7 +128,7 @@ data class HermesCardInput(
|
||||
/** Submit is a 650ms hold-to-confirm press-fill instead of a tap (sudo). */
|
||||
val holdToConfirm: Boolean = false,
|
||||
/**
|
||||
* Wall-clock expiry for timed asks (sudo 120s, clarify/secret 300s).
|
||||
* Wall-clock expiry for asks with an advertised deadline.
|
||||
* The renderer shows a countdown footer (Amber under 30s) and
|
||||
* self-collapses to "Expired — not granted" past it. Null = no timeout
|
||||
* (approval is session-scoped).
|
||||
@@ -155,6 +159,10 @@ data class HermesCardInput(
|
||||
}
|
||||
}
|
||||
|
||||
/** Exact JSON-array wire value expected by upstream multi-select clarify. */
|
||||
internal fun encodeClarifyMultiSelectAnswer(values: List<String>): String =
|
||||
Json.encodeToString(values.map(String::trim).filter(String::isNotEmpty).distinct())
|
||||
|
||||
/**
|
||||
* A label/value row inside a card. [value] is rendered as markdown so the
|
||||
* agent can embed emphasis, inline code, or links.
|
||||
|
||||
@@ -34,6 +34,10 @@ data class ProactiveInboxEntry(
|
||||
* field).
|
||||
*/
|
||||
val chatId: String? = null,
|
||||
/** Owning saved connection. Null only for entries written by older builds. */
|
||||
val connectionId: String? = null,
|
||||
/** Relay proved this row came from its bounded offline queue. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
)
|
||||
|
||||
private val Context.proactiveInboxStore: DataStore<Preferences> by
|
||||
@@ -49,10 +53,10 @@ private const val MAX_ENTRIES = 100
|
||||
* newest-first, deduped by id (so a re-delivered message doesn't double up), and
|
||||
* capped at [MAX_ENTRIES]. Survives app restart.
|
||||
*
|
||||
* Demoted (2026-06-29): the agent conversation now lives as a Thread in Chat (the
|
||||
* gateway session is the durable history), so the in-app inbox view is retired.
|
||||
* This store is only fed for messages NOT shown in an open Thread; it currently
|
||||
* has no viewer and is fully retireable — see TODO.
|
||||
* Demoted (2026-06-29): once a phone gateway session exists, it is the durable
|
||||
* history. Outbound agent messages arrive before that session exists, so this
|
||||
* bounded store also backs the provisional Thread until the user's first reply
|
||||
* promotes it to a real `source=phone` session.
|
||||
*/
|
||||
class ProactiveInboxRepository(private val context: Context) {
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ImageDecoder
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import java.io.ByteArrayOutputStream
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal fun profileAvatarMime(bytes: ByteArray): String? = when {
|
||||
bytes.size >= 8 && bytes.copyOfRange(0, 8).contentEquals(
|
||||
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a),
|
||||
) -> "image/png"
|
||||
bytes.size >= 3 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte() &&
|
||||
bytes[2] == 0xff.toByte() -> "image/jpeg"
|
||||
bytes.size >= 12 && bytes.copyOfRange(0, 4).contentEquals("RIFF".toByteArray()) &&
|
||||
bytes.copyOfRange(8, 12).contentEquals("WEBP".toByteArray()) -> "image/webp"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert any image Android can decode into the small static format accepted by
|
||||
* upstream `profiles.set_asset`. ImageDecoder applies camera EXIF orientation
|
||||
* and downsamples before allocating the bitmap on current Android releases.
|
||||
*/
|
||||
internal fun prepareProfileAvatar(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
maxBytes: Int,
|
||||
): ByteArray? {
|
||||
val original = runCatching {
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
val output = ByteArrayOutputStream(minOf(maxBytes + 1, 64 * 1024))
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (output.size() <= maxBytes) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
output.toByteArray()
|
||||
}
|
||||
}.getOrNull()
|
||||
if (original != null && original.size <= maxBytes && profileAvatarMime(original) != null) {
|
||||
return original
|
||||
}
|
||||
|
||||
val bitmap = decodeProfileAvatar(context, uri) ?: return null
|
||||
return try {
|
||||
encodeProfileAvatar(bitmap, maxBytes)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeProfileAvatar(context: Context, uri: Uri): Bitmap? = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
ImageDecoder.decodeBitmap(ImageDecoder.createSource(context.contentResolver, uri)) { decoder, info, _ ->
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
val width = info.size.width
|
||||
val height = info.size.height
|
||||
val longest = maxOf(width, height)
|
||||
if (longest > PROFILE_AVATAR_MAX_DIMENSION) {
|
||||
val scale = PROFILE_AVATAR_MAX_DIMENSION.toFloat() / longest
|
||||
decoder.setTargetSize(
|
||||
(width * scale).roundToInt().coerceAtLeast(1),
|
||||
(height * scale).roundToInt().coerceAtLeast(1),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / sample > PROFILE_AVATAR_MAX_DIMENSION) sample *= 2
|
||||
context.contentResolver.openInputStream(uri)?.use {
|
||||
BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
}
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
internal fun encodeProfileAvatar(bitmap: Bitmap, maxBytes: Int): ByteArray? {
|
||||
var working = bitmap.scaledToFit(PROFILE_AVATAR_MAX_DIMENSION)
|
||||
var ownsWorking = working !== bitmap
|
||||
try {
|
||||
while (true) {
|
||||
val format = if (working.hasAlpha()) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG
|
||||
val qualities = if (format == Bitmap.CompressFormat.PNG) intArrayOf(100) else intArrayOf(92, 82, 72, 62)
|
||||
for (quality in qualities) {
|
||||
val encoded = ByteArrayOutputStream().use { output ->
|
||||
if (!working.compress(format, quality, output)) null else output.toByteArray()
|
||||
}
|
||||
if (encoded != null && encoded.size <= maxBytes) return encoded
|
||||
}
|
||||
if (maxOf(working.width, working.height) <= PROFILE_AVATAR_MIN_DIMENSION) return null
|
||||
val next = Bitmap.createScaledBitmap(
|
||||
working,
|
||||
(working.width * 0.75f).roundToInt().coerceAtLeast(1),
|
||||
(working.height * 0.75f).roundToInt().coerceAtLeast(1),
|
||||
true,
|
||||
)
|
||||
if (ownsWorking) working.recycle()
|
||||
working = next
|
||||
ownsWorking = true
|
||||
}
|
||||
} finally {
|
||||
if (ownsWorking) working.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun Bitmap.scaledToFit(maxDimension: Int): Bitmap {
|
||||
val longest = maxOf(width, height)
|
||||
if (longest <= maxDimension) return this
|
||||
val scale = maxDimension.toFloat() / longest
|
||||
return Bitmap.createScaledBitmap(
|
||||
this,
|
||||
(width * scale).roundToInt().coerceAtLeast(1),
|
||||
(height * scale).roundToInt().coerceAtLeast(1),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
private const val PROFILE_AVATAR_MAX_DIMENSION = 1024
|
||||
private const val PROFILE_AVATAR_MIN_DIMENSION = 128
|
||||
@@ -2,6 +2,35 @@ package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
|
||||
internal fun isSafeProfileUiMeta(meta: JsonObject): Boolean {
|
||||
if (meta.toString().toByteArray(Charsets.UTF_8).size > 65_536) return false
|
||||
fun containsEmbeddedAsset(value: String): Boolean {
|
||||
val compact = value.trim()
|
||||
return compact.startsWith("data:image/", ignoreCase = true) ||
|
||||
compact.startsWith("iVBORw0KGgo") || // PNG
|
||||
compact.startsWith("/9j/") || // JPEG
|
||||
compact.startsWith("UklGR") || // RIFF/WebP
|
||||
compact.startsWith("R0lGOD") || // GIF
|
||||
compact.startsWith("UEsDB") // ZIP/pet archive
|
||||
}
|
||||
fun safe(element: JsonElement): Boolean = when (element) {
|
||||
is JsonObject -> element.size <= 128 && element.all { (key, value) ->
|
||||
key.length <= 128 && safe(value)
|
||||
}
|
||||
is JsonArray -> element.size <= 128 && element.all(::safe)
|
||||
is JsonPrimitive -> {
|
||||
val value = element.contentOrNull
|
||||
value == null || (value.length <= 4_096 && !containsEmbeddedAsset(value))
|
||||
}
|
||||
}
|
||||
return safe(meta)
|
||||
}
|
||||
|
||||
/**
|
||||
* An agent profile advertised by a Hermes server in its `auth.ok` payload.
|
||||
@@ -56,6 +85,7 @@ import kotlinx.serialization.Serializable
|
||||
data class Profile(
|
||||
val name: String,
|
||||
val model: String,
|
||||
val provider: String = "",
|
||||
val description: String = "",
|
||||
@SerialName("system_message")
|
||||
val systemMessage: String? = null,
|
||||
@@ -75,6 +105,12 @@ data class Profile(
|
||||
val apiServerPort: Int? = null,
|
||||
@SerialName("api_server_key_present")
|
||||
val apiServerKeyPresent: Boolean = false,
|
||||
@SerialName("is_default")
|
||||
val isDefault: Boolean = false,
|
||||
@SerialName("has_avatar")
|
||||
val hasAvatar: Boolean = false,
|
||||
@SerialName("ui_meta")
|
||||
val uiMeta: JsonObject = JsonObject(emptyMap()),
|
||||
) {
|
||||
val hasIsolatedApi: Boolean
|
||||
get() = !apiServerUrl.isNullOrBlank()
|
||||
|
||||
@@ -4,13 +4,15 @@ import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/**
|
||||
* Local-only per-profile agent icons — the visual twin of [ProfileDisplayAliasStore].
|
||||
* Per-profile icon cache. Local fallback paths and Hermes-owned avatar cache
|
||||
* paths use separate keys so syncing either side never silently overwrites the other.
|
||||
*
|
||||
* Stores a **file path** to an image that was copied into app storage (not a SAF
|
||||
* content URI, so it survives without a persistable-permission grant). Like the
|
||||
@@ -25,6 +27,8 @@ class ProfileIconStore(
|
||||
|
||||
companion object {
|
||||
private const val PREFIX = "profile_icon__"
|
||||
private const val SERVER_PREFIX = "profile_avatar_server__"
|
||||
private const val LOCAL_OVERRIDE_PREFIX = "profile_icon_override__"
|
||||
|
||||
private fun keyName(connectionId: String, profileName: String?): String =
|
||||
"$PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}"
|
||||
@@ -34,6 +38,20 @@ class ProfileIconStore(
|
||||
|
||||
private fun connectionPrefix(connectionId: String): String =
|
||||
"$PREFIX${connectionId}__"
|
||||
|
||||
private fun serverKeyFor(connectionId: String, profileName: String) =
|
||||
stringPreferencesKey("$SERVER_PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}")
|
||||
|
||||
private fun serverConnectionPrefix(connectionId: String): String =
|
||||
"$SERVER_PREFIX${connectionId}__"
|
||||
|
||||
private fun localOverrideKeyFor(connectionId: String, profileName: String?) =
|
||||
booleanPreferencesKey(
|
||||
"$LOCAL_OVERRIDE_PREFIX${connectionId}__${AgentDisplay.profileSessionKey(profileName)}",
|
||||
)
|
||||
|
||||
private fun localOverrideConnectionPrefix(connectionId: String): String =
|
||||
"$LOCAL_OVERRIDE_PREFIX${connectionId}__"
|
||||
}
|
||||
|
||||
suspend fun setIcon(connectionId: String, profileName: String?, path: String?) {
|
||||
@@ -52,11 +70,39 @@ class ProfileIconStore(
|
||||
return dataStore.data.map { prefs -> prefs[key] }
|
||||
}
|
||||
|
||||
suspend fun setServerAvatar(connectionId: String, profileName: String, path: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
val key = serverKeyFor(connectionId, profileName)
|
||||
if (path.isNullOrBlank()) prefs.remove(key) else prefs[key] = path
|
||||
}
|
||||
}
|
||||
|
||||
fun serverAvatarFlow(connectionId: String, profileName: String): Flow<String?> {
|
||||
val key = serverKeyFor(connectionId, profileName)
|
||||
return dataStore.data.map { prefs -> prefs[key] }
|
||||
}
|
||||
|
||||
suspend fun setLocalOverride(connectionId: String, profileName: String?, enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
val key = localOverrideKeyFor(connectionId, profileName)
|
||||
if (enabled) prefs[key] = true else prefs.remove(key)
|
||||
}
|
||||
}
|
||||
|
||||
fun localOverrideFlow(connectionId: String, profileName: String?): Flow<Boolean> {
|
||||
val key = localOverrideKeyFor(connectionId, profileName)
|
||||
return dataStore.data.map { prefs -> prefs[key] ?: false }
|
||||
}
|
||||
|
||||
suspend fun clearConnection(connectionId: String) {
|
||||
val prefix = connectionPrefix(connectionId)
|
||||
val prefixes = listOf(
|
||||
connectionPrefix(connectionId),
|
||||
serverConnectionPrefix(connectionId),
|
||||
localOverrideConnectionPrefix(connectionId),
|
||||
)
|
||||
dataStore.edit { prefs ->
|
||||
prefs.asMap().keys
|
||||
.filter { it.name.startsWith(prefix) }
|
||||
.filter { key -> prefixes.any(key.name::startsWith) }
|
||||
.forEach { prefs.remove(it) }
|
||||
}
|
||||
}
|
||||
@@ -66,5 +112,11 @@ class ProfileIconStore(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun preferredProfileIcon(
|
||||
server: String?,
|
||||
local: String?,
|
||||
useLocalOverride: Boolean,
|
||||
): String? = if (useLocalOverride && !local.isNullOrBlank()) local else server ?: local
|
||||
|
||||
internal val Context.profileIconsDataStore: DataStore<Preferences>
|
||||
by preferencesDataStore(name = "profile_icons")
|
||||
|
||||
@@ -136,3 +136,154 @@ data class ProfileMemoryUpdateResponse(
|
||||
@SerialName("bytes_written")
|
||||
val bytesWritten: Long,
|
||||
)
|
||||
|
||||
/** Authoritative upstream `profiles.describe` snapshot. */
|
||||
data class GatewayProfileDescription(
|
||||
val name: String,
|
||||
val description: String,
|
||||
val soul: String,
|
||||
val provider: String,
|
||||
val model: String,
|
||||
val skills: List<GatewayProfileSkill>,
|
||||
val toolsets: List<GatewayProfileToolset>,
|
||||
val toolsetsPinned: Boolean,
|
||||
)
|
||||
|
||||
data class GatewayProfileSkill(val name: String, val enabled: Boolean)
|
||||
|
||||
data class GatewayProfileToolset(
|
||||
val name: String,
|
||||
val description: String,
|
||||
val toolCount: Int,
|
||||
val enabled: Boolean,
|
||||
)
|
||||
|
||||
enum class GatewayProfileSection(val wireName: String) {
|
||||
Description("description"),
|
||||
Soul("soul"),
|
||||
Model("model"),
|
||||
Skills("skills"),
|
||||
Toolsets("toolsets"),
|
||||
McpServers("mcp_servers"),
|
||||
UiMeta("ui_meta"),
|
||||
}
|
||||
|
||||
/** Null leaves a section unchanged; empty lists retain upstream replace semantics. */
|
||||
data class GatewayProfilePatch(
|
||||
val description: String? = null,
|
||||
val soul: String? = null,
|
||||
val provider: String? = null,
|
||||
val model: String? = null,
|
||||
val disabledSkills: List<String>? = null,
|
||||
val enabledToolsets: List<String>? = null,
|
||||
val enabledMcpServers: List<String>? = null,
|
||||
/** Small interoperable preferences only; binary assets belong in profiles.set_asset. */
|
||||
val uiMeta: JsonObject? = null,
|
||||
) {
|
||||
val requestedSections: Set<GatewayProfileSection>
|
||||
get() = buildSet {
|
||||
if (description != null) add(GatewayProfileSection.Description)
|
||||
if (soul != null) add(GatewayProfileSection.Soul)
|
||||
if (provider != null && model != null) add(GatewayProfileSection.Model)
|
||||
if (disabledSkills != null) add(GatewayProfileSection.Skills)
|
||||
if (enabledToolsets != null) add(GatewayProfileSection.Toolsets)
|
||||
if (enabledMcpServers != null) add(GatewayProfileSection.McpServers)
|
||||
if (uiMeta != null) add(GatewayProfileSection.UiMeta)
|
||||
}
|
||||
}
|
||||
|
||||
enum class GatewayProfileAuthChoice {
|
||||
/** Share the launch profile's refreshable OAuth/token store; copy static environment keys. */
|
||||
Shared,
|
||||
|
||||
/** Copy the current credential snapshot into a separate profile-owned store. */
|
||||
Copied,
|
||||
|
||||
/** Copy no credentials or provider defaults. */
|
||||
Isolated,
|
||||
}
|
||||
|
||||
data class GatewayProfileCreateRequest(
|
||||
val name: String,
|
||||
val description: String? = null,
|
||||
val cloneFrom: String? = null,
|
||||
val cloneAll: Boolean = false,
|
||||
val noSkills: Boolean = false,
|
||||
val soul: String? = null,
|
||||
val model: String? = null,
|
||||
val provider: String? = null,
|
||||
val authChoice: GatewayProfileAuthChoice = GatewayProfileAuthChoice.Shared,
|
||||
)
|
||||
|
||||
data class GatewayProfileCreateResult(
|
||||
val name: String,
|
||||
val soulWritten: Boolean,
|
||||
val modelSet: Boolean,
|
||||
val mirroredEnvironment: Boolean,
|
||||
val mirroredAuth: String?,
|
||||
val modelInherited: Boolean,
|
||||
val voiceMirrored: Boolean,
|
||||
) {
|
||||
fun partialMessages(request: GatewayProfileCreateRequest): List<String> = buildList {
|
||||
if (!request.soul.isNullOrBlank() && !soulWritten) add("SOUL was not saved")
|
||||
if (!request.model.isNullOrBlank() && !modelSet) add("model was not saved")
|
||||
if (request.authChoice == GatewayProfileAuthChoice.Shared && mirroredAuth != "shared") {
|
||||
add("shared sign-in was not confirmed")
|
||||
}
|
||||
if (
|
||||
request.authChoice == GatewayProfileAuthChoice.Copied &&
|
||||
!mirroredEnvironment && mirroredAuth != "true"
|
||||
) {
|
||||
add("no credential source was copied")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class GatewayProfileAsset(
|
||||
val data: ByteArray,
|
||||
val mime: String,
|
||||
)
|
||||
|
||||
class GatewayProfileManagementUnsupportedException(
|
||||
operation: String,
|
||||
) : Exception("$operation is not supported by this gateway")
|
||||
|
||||
data class GatewayProfileConfigureResult(
|
||||
val requested: Set<GatewayProfileSection>,
|
||||
val applied: Set<GatewayProfileSection>,
|
||||
) {
|
||||
val failed: Set<GatewayProfileSection> get() = requested - applied
|
||||
}
|
||||
|
||||
interface GatewayProfileEditorClient {
|
||||
suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription>
|
||||
suspend fun configureProfile(
|
||||
profileName: String,
|
||||
patch: GatewayProfilePatch,
|
||||
): Result<GatewayProfileConfigureResult>
|
||||
}
|
||||
|
||||
class GatewayProfileEditorUnsupportedException : Exception(
|
||||
"Profile editing is not supported by this gateway",
|
||||
)
|
||||
|
||||
/** Relay fallback retained for older gateways and Relay-only memory files. */
|
||||
interface LegacyProfileInspectorClient {
|
||||
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse>
|
||||
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse>
|
||||
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse>
|
||||
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse>
|
||||
suspend fun updateSoul(profileName: String, content: String): Result<ProfileSoulUpdateResponse>
|
||||
suspend fun updateMemoryEntry(
|
||||
profileName: String,
|
||||
filename: String,
|
||||
content: String,
|
||||
): Result<ProfileMemoryUpdateResponse>
|
||||
suspend fun updateSkillToggle(skillName: String, enabled: Boolean): Result<RelaySkillToggleResult>
|
||||
suspend fun probeSkillToggleSupported(): Boolean
|
||||
}
|
||||
|
||||
sealed interface RelaySkillToggleResult {
|
||||
data object Ok : RelaySkillToggleResult
|
||||
data object NotImplemented : RelaySkillToggleResult
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.builtins.MapSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
@@ -16,6 +17,8 @@ import kotlinx.serialization.json.Json
|
||||
data class ProfilePresentation(
|
||||
val order: List<String> = emptyList(),
|
||||
val hidden: Set<String> = emptySet(),
|
||||
/** Local-only named-profile accent overrides, stored as normalized RGB hex. */
|
||||
val colors: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -63,14 +66,17 @@ class ProfilePresentationStore(
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val listSerializer = ListSerializer(String.serializer())
|
||||
private val mapSerializer = MapSerializer(String.serializer(), String.serializer())
|
||||
|
||||
private fun orderKey(connectionId: String) = stringPreferencesKey("order_$connectionId")
|
||||
private fun hiddenKey(connectionId: String) = stringPreferencesKey("hidden_$connectionId")
|
||||
private fun colorsKey(connectionId: String) = stringPreferencesKey("colors_$connectionId")
|
||||
|
||||
fun presentationFlow(connectionId: String): Flow<ProfilePresentation> = dataStore.data.map { prefs ->
|
||||
ProfilePresentation(
|
||||
order = decode(prefs[orderKey(connectionId)]),
|
||||
hidden = decode(prefs[hiddenKey(connectionId)]).toSet(),
|
||||
colors = decodeMap(prefs[colorsKey(connectionId)]),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -82,10 +88,18 @@ class ProfilePresentationStore(
|
||||
dataStore.edit { it[hiddenKey(connectionId)] = json.encodeToString(listSerializer, hidden.sorted()) }
|
||||
}
|
||||
|
||||
suspend fun setColors(connectionId: String, colors: Map<String, String>) {
|
||||
dataStore.edit {
|
||||
if (colors.isEmpty()) it.remove(colorsKey(connectionId))
|
||||
else it[colorsKey(connectionId)] = json.encodeToString(mapSerializer, colors.toSortedMap())
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clear(connectionId: String) {
|
||||
dataStore.edit {
|
||||
it.remove(orderKey(connectionId))
|
||||
it.remove(hiddenKey(connectionId))
|
||||
it.remove(colorsKey(connectionId))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +112,12 @@ class ProfilePresentationStore(
|
||||
} else {
|
||||
runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
private fun decodeMap(raw: String?): Map<String, String> = if (raw == null) {
|
||||
emptyMap()
|
||||
} else {
|
||||
runCatching { json.decodeFromString(mapSerializer, raw) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
|
||||
internal val Context.profilePresentationDataStore: DataStore<Preferences>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import java.net.URI
|
||||
|
||||
/** Canonical Relay routes derived from one operator- or pairing-supplied URL. */
|
||||
data class RelayEndpoints(
|
||||
val httpBaseUrl: String,
|
||||
val webSocketBaseUrl: String,
|
||||
val webSocketUrl: String,
|
||||
val healthUrl: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Parses the accepted Relay URL forms and derives every route from one base.
|
||||
*
|
||||
* The input may identify the route base, its terminal `/ws` endpoint, or its
|
||||
* terminal `/health` endpoint, using either HTTP(S) or WS(S). The final
|
||||
* `ws`/`health` segment is removed before both canonical routes are rebuilt,
|
||||
* which makes the operation idempotent and preserves reverse-proxy prefixes.
|
||||
*/
|
||||
object RelayEndpointContract {
|
||||
private val encodedAmbiguousPathByte = Regex("%(?:2e|2f|5c)", RegexOption.IGNORE_CASE)
|
||||
|
||||
fun parseOrNull(raw: String?): RelayEndpoints? = runCatching { parse(raw) }.getOrNull()
|
||||
|
||||
fun parse(raw: String?): RelayEndpoints {
|
||||
val input = raw?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?: throw IllegalArgumentException("Relay URL is empty")
|
||||
val uri = runCatching { URI(input) }.getOrElse {
|
||||
throw IllegalArgumentException("Relay URL is malformed")
|
||||
}
|
||||
val sourceScheme = uri.scheme?.lowercase()
|
||||
val secure = when (sourceScheme) {
|
||||
"https", "wss" -> true
|
||||
"http", "ws" -> false
|
||||
else -> throw IllegalArgumentException("Relay URL must use HTTP(S) or WS(S)")
|
||||
}
|
||||
if (uri.host.isNullOrBlank() || uri.rawAuthority.isNullOrBlank() || uri.isOpaque) {
|
||||
throw IllegalArgumentException("Relay URL has no valid host")
|
||||
}
|
||||
if (uri.rawUserInfo != null) {
|
||||
throw IllegalArgumentException("Relay URL must not contain user info")
|
||||
}
|
||||
if (uri.rawQuery != null || uri.rawFragment != null) {
|
||||
throw IllegalArgumentException("Relay URL must not contain a query or fragment")
|
||||
}
|
||||
if (uri.port == 0 || uri.port > 65_535) {
|
||||
throw IllegalArgumentException("Relay URL has an invalid port")
|
||||
}
|
||||
|
||||
val rawPath = uri.rawPath.orEmpty()
|
||||
if ('\\' in rawPath || "//" in rawPath || encodedAmbiguousPathByte.containsMatchIn(rawPath)) {
|
||||
throw IllegalArgumentException("Relay URL contains an ambiguous path")
|
||||
}
|
||||
val trimmedPath = rawPath.trimEnd('/')
|
||||
val pathSegments = trimmedPath.split('/').filter { it.isNotEmpty() }
|
||||
if (pathSegments.any { it == "." || it == ".." }) {
|
||||
throw IllegalArgumentException("Relay URL contains a relative path segment")
|
||||
}
|
||||
val baseSegments = if (pathSegments.lastOrNull() in setOf("ws", "health")) {
|
||||
pathSegments.dropLast(1)
|
||||
} else {
|
||||
pathSegments
|
||||
}
|
||||
val basePath = baseSegments.joinToString(separator = "/", prefix = "/")
|
||||
.takeUnless { it == "/" }
|
||||
.orEmpty()
|
||||
val httpScheme = if (secure) "https" else "http"
|
||||
val webSocketScheme = if (secure) "wss" else "ws"
|
||||
val httpBase = "$httpScheme://${uri.rawAuthority}$basePath"
|
||||
val webSocketBase = "$webSocketScheme://${uri.rawAuthority}$basePath"
|
||||
val webSocket = "$webSocketBase/ws"
|
||||
val health = "$httpBase/health"
|
||||
|
||||
if (httpBase.toHttpUrlOrNull() == null || health.toHttpUrlOrNull() == null) {
|
||||
throw IllegalArgumentException("Relay URL is malformed")
|
||||
}
|
||||
return RelayEndpoints(
|
||||
httpBaseUrl = httpBase,
|
||||
webSocketBaseUrl = webSocketBase,
|
||||
webSocketUrl = webSocket,
|
||||
healthUrl = health,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,7 @@ class BridgeCommandHandler(
|
||||
|
||||
private val pendingActivities =
|
||||
java.util.concurrent.ConcurrentHashMap<String, PendingActivity>()
|
||||
private val unattendedWakeRequests = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
||||
// === END v0.4.1 polish ===
|
||||
|
||||
private val json = Json {
|
||||
@@ -302,6 +303,8 @@ class BridgeCommandHandler(
|
||||
put("error", t.message ?: "unknown executor error")
|
||||
}
|
||||
)
|
||||
} finally {
|
||||
releaseUnattendedWake(requestId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -396,6 +399,8 @@ class BridgeCommandHandler(
|
||||
errorCode = "dispatch_exception",
|
||||
resultJson = null,
|
||||
)
|
||||
} finally {
|
||||
releaseUnattendedWake(requestId)
|
||||
}
|
||||
|
||||
val resultJson = sink.get()
|
||||
@@ -421,6 +426,54 @@ class BridgeCommandHandler(
|
||||
method: String,
|
||||
body: JsonObject,
|
||||
) {
|
||||
// Resolve path + method through the closed capability registry before
|
||||
// any wake, confirmation, event read, executor, or run-tracker effect.
|
||||
val registeredAuthority =
|
||||
com.hermesandroid.relay.bridge.BridgeCommandRegistry.resolve(path, method)
|
||||
val capabilityAuthorization = when {
|
||||
registeredAuthority == null -> BridgeSafetyManager.CapabilityAuthorization(
|
||||
allowed = false,
|
||||
errorCode = "unknown_bridge_command",
|
||||
)
|
||||
!BuildFlavor.isSideload && registeredAuthority.grant !=
|
||||
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.EXEMPT ->
|
||||
BridgeSafetyManager.CapabilityAuthorization(
|
||||
allowed = false,
|
||||
authority = registeredAuthority,
|
||||
errorCode = "device_control_sideload_only",
|
||||
)
|
||||
registeredAuthority.grant ==
|
||||
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.EXEMPT ->
|
||||
BridgeSafetyManager.CapabilityAuthorization(true, registeredAuthority)
|
||||
else -> safetyManager?.authorizeCapability(path, method)
|
||||
?: BridgeSafetyManager.CapabilityAuthorization(
|
||||
allowed = false,
|
||||
authority = registeredAuthority,
|
||||
errorCode = "bridge_policy_unavailable",
|
||||
)
|
||||
}
|
||||
if (!capabilityAuthorization.allowed) {
|
||||
return respond(
|
||||
requestId,
|
||||
403,
|
||||
buildJsonObject {
|
||||
put(
|
||||
"error",
|
||||
if (capabilityAuthorization.errorCode == "device_control_sideload_only") {
|
||||
"Device Control is not included in the Google Play build."
|
||||
} else {
|
||||
"Bridge capability is not granted for this connection."
|
||||
},
|
||||
)
|
||||
put("error_code", capabilityAuthorization.errorCode ?: "bridge_capability_denied")
|
||||
capabilityAuthorization.authority?.capability?.let {
|
||||
put("capability", it.wireId)
|
||||
}
|
||||
put("required_action", "Review Bridge > Safety & capabilities on the phone")
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// === v0.4.1 polish: keep auto-return idle timer alive ===
|
||||
// Any non-polling bridge command during a run is evidence the
|
||||
// agent is still working — reset BridgeRunTracker's idle timer
|
||||
@@ -475,44 +528,6 @@ class BridgeCommandHandler(
|
||||
return
|
||||
}
|
||||
|
||||
// === PHASE3-event-stream: B1 android_events read-only polling ===
|
||||
// /events is a read-only peek at the EventStore ring buffer. The
|
||||
// buffer lives in our own process so there's no safety gate —
|
||||
// the agent already opted into streaming via /events/stream
|
||||
// which IS gated. This mirrors the /ping early-return path so
|
||||
// polling works even when the service is transiently unbound.
|
||||
if (path == "/events") {
|
||||
val limitRaw = body["limit"]?.jsonPrimitive?.content?.toIntOrNull() ?: 50
|
||||
val limit = limitRaw.coerceIn(1, EventStore.MAX_ENTRIES)
|
||||
val since = body["since"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
|
||||
val entries = EventStore.recent(limit = limit, since = since)
|
||||
val arr: JsonArray = buildJsonArray {
|
||||
for (e in entries) {
|
||||
add(
|
||||
buildJsonObject {
|
||||
put("timestamp", e.timestamp)
|
||||
put("event_type", e.eventType)
|
||||
e.packageName?.let { put("package_name", it) }
|
||||
e.className?.let { put("class_name", it) }
|
||||
e.text?.let { put("text", it) }
|
||||
e.contentDescription?.let { put("content_description", it) }
|
||||
put("source", e.source)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
respond(
|
||||
requestId, 200,
|
||||
buildJsonObject {
|
||||
put("entries", arr)
|
||||
put("count", entries.size)
|
||||
put("streaming", EventStore.isStreaming)
|
||||
}
|
||||
)
|
||||
return
|
||||
}
|
||||
// === END PHASE3-event-stream ===
|
||||
|
||||
// /setup exists on the relay as a legacy bridge HTTP route, but
|
||||
// android_setup() in plugin/tools/android_tool.py is host-side
|
||||
// only (it just writes ANDROID_BRIDGE_TOKEN to ~/.hermes/.env)
|
||||
@@ -576,10 +591,7 @@ class BridgeCommandHandler(
|
||||
}
|
||||
)
|
||||
|
||||
if (!service.isMasterEnabled() &&
|
||||
path != "/current_app" &&
|
||||
path != "/return_to_hermes"
|
||||
) {
|
||||
if (!service.isMasterEnabled()) {
|
||||
// Crystal-clear error text + structured error_code. Bailey hit
|
||||
// 2026-04-15: when the phone was paired + a11y granted but
|
||||
// master toggle flipped off, the agent read the shorter
|
||||
@@ -649,9 +661,13 @@ class BridgeCommandHandler(
|
||||
}
|
||||
}
|
||||
|
||||
// Reschedule the idle auto-disable timer on every accepted
|
||||
// command. Safe to call even when no timer is currently armed.
|
||||
safetyManager?.rescheduleAutoDisable()
|
||||
// Permanent capabilities never keep screen control armed. Only an
|
||||
// accepted timed inspection/control command refreshes the timer.
|
||||
if (capabilityAuthorization.authority?.grant ==
|
||||
com.hermesandroid.relay.bridge.BridgeCapabilityGrant.TIMED
|
||||
) {
|
||||
safetyManager?.rescheduleAutoDisable()
|
||||
}
|
||||
// === END PHASE3-safety-rails ===
|
||||
|
||||
// === v0.4.1 unattended-access wake + keyguard dismiss ===
|
||||
@@ -673,6 +689,9 @@ class BridgeCommandHandler(
|
||||
if (!isReadOnlyRoute) {
|
||||
val outcome = runCatching { UnattendedAccessManager.acquireForAction() }
|
||||
.getOrDefault(UnattendedAccessManager.WakeOutcome.Disabled)
|
||||
if (outcome != UnattendedAccessManager.WakeOutcome.Disabled) {
|
||||
unattendedWakeRequests += requestId
|
||||
}
|
||||
if (outcome == UnattendedAccessManager.WakeOutcome.KeyguardBlocked) {
|
||||
respond(
|
||||
requestId, 423,
|
||||
@@ -705,6 +724,30 @@ class BridgeCommandHandler(
|
||||
val executor = service.actionExecutor
|
||||
|
||||
when (path) {
|
||||
"/events" -> {
|
||||
val limitRaw = body["limit"]?.jsonPrimitive?.content?.toIntOrNull() ?: 50
|
||||
val limit = limitRaw.coerceIn(1, EventStore.MAX_ENTRIES)
|
||||
val since = body["since"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
|
||||
val entries = EventStore.recent(limit = limit, since = since)
|
||||
val arr: JsonArray = buildJsonArray {
|
||||
for (e in entries) {
|
||||
add(buildJsonObject {
|
||||
put("timestamp", e.timestamp)
|
||||
put("event_type", e.eventType)
|
||||
e.packageName?.let { put("package_name", it) }
|
||||
e.className?.let { put("class_name", it) }
|
||||
e.text?.let { put("text", it) }
|
||||
e.contentDescription?.let { put("content_description", it) }
|
||||
put("source", e.source)
|
||||
})
|
||||
}
|
||||
}
|
||||
respond(requestId, 200, buildJsonObject {
|
||||
put("entries", arr)
|
||||
put("count", entries.size)
|
||||
put("streaming", EventStore.isStreaming)
|
||||
})
|
||||
}
|
||||
"/current_app" -> respond(
|
||||
requestId, 200,
|
||||
buildJsonObject {
|
||||
@@ -2417,6 +2460,12 @@ class BridgeCommandHandler(
|
||||
}
|
||||
multiplexer.send(envelope)
|
||||
}
|
||||
|
||||
private fun releaseUnattendedWake(requestId: String) {
|
||||
if (unattendedWakeRequests.remove(requestId)) {
|
||||
UnattendedAccessManager.releaseAfterAction()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LocalDispatchResult moved to network.shared (ADR 34 fence): it is a passive
|
||||
|
||||
@@ -10,8 +10,10 @@ import android.util.Log
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.auth.CertPinStore
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.PairingPreferences
|
||||
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||
@@ -19,6 +21,7 @@ import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import com.hermesandroid.relay.network.shared.EndpointResolver
|
||||
import com.hermesandroid.relay.network.shared.EndpointSurface
|
||||
import com.hermesandroid.relay.network.shared.fullJitterDelayMs
|
||||
import com.hermesandroid.relay.network.shutdownOffMainThread
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -76,6 +79,9 @@ internal fun buildRelayRequestOrNull(url: String): Request? =
|
||||
null
|
||||
}
|
||||
|
||||
private fun EndpointCandidate.relayWebSocketUrl(): String? =
|
||||
pluginProxyRoutesOrNull()?.relayWebSocketUrl ?: relay?.url
|
||||
|
||||
class ConnectionManager(
|
||||
private val multiplexer: ChannelMultiplexer,
|
||||
/**
|
||||
@@ -139,6 +145,12 @@ class ConnectionManager(
|
||||
* non-null — the manager falls back to the single-URL path.
|
||||
*/
|
||||
private val deviceIdProvider: (suspend () -> String?)? = null,
|
||||
/** Random source for ordinary reconnect full-jitter; exact backoffs never use it. */
|
||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||
/** Exact-authority pinned client for a plugin-proxy WSS URL. */
|
||||
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Test seam for observing lifecycle teardown without opening a socket. */
|
||||
private val okHttpClientFactory: (() -> OkHttpClient)? = null,
|
||||
) {
|
||||
private val supervisorJob = SupervisorJob()
|
||||
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
|
||||
@@ -148,7 +160,8 @@ class ConnectionManager(
|
||||
encodeDefaults = true
|
||||
}
|
||||
|
||||
private fun buildClient(): OkHttpClient {
|
||||
private fun buildClient(url: String? = null): OkHttpClient {
|
||||
okHttpClientFactory?.let { return it() }
|
||||
val builder = OkHttpClient.Builder()
|
||||
// OkHttp's 10s default connectTimeout is LAN-tuned; a Tailscale
|
||||
// DERP-relayed cold-start handshake can exceed it, and a failed
|
||||
@@ -162,7 +175,9 @@ class ConnectionManager(
|
||||
// that wipes a pin would still be subject to the pre-wipe rules.
|
||||
certPinStore?.let { store ->
|
||||
try {
|
||||
builder.certificatePinner(store.buildPinnerSnapshot())
|
||||
builder.certificatePinner(
|
||||
url?.let(store::buildPinnerSnapshotFor) ?: store.buildPinnerSnapshot(),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "CertificatePinner build failed: ${e.message}")
|
||||
builder.certificatePinner(CertificatePinner.DEFAULT)
|
||||
@@ -221,10 +236,12 @@ class ConnectionManager(
|
||||
// Endpoints card in Settings.
|
||||
private val _activeEndpoint = MutableStateFlow<EndpointCandidate?>(null)
|
||||
val activeEndpoint: StateFlow<EndpointCandidate?> = _activeEndpoint.asStateFlow()
|
||||
private val _activeApiEndpoint = MutableStateFlow<EndpointCandidate?>(null)
|
||||
val activeApiEndpoint: StateFlow<EndpointCandidate?> = _activeApiEndpoint.asStateFlow()
|
||||
|
||||
/** Relay-only winner, deliberately separate from the standard route. */
|
||||
@Volatile
|
||||
private var activeRelayEndpoint: EndpointCandidate? = null
|
||||
private val _activeRelayEndpoint = MutableStateFlow<EndpointCandidate?>(null)
|
||||
val activeRelayEndpoint: StateFlow<EndpointCandidate?> = _activeRelayEndpoint.asStateFlow()
|
||||
|
||||
/**
|
||||
* Manual role override. When non-null, the resolver's output is replaced
|
||||
@@ -345,11 +362,14 @@ class ConnectionManager(
|
||||
// behavior for freshly-upgraded installs and for v1/v2 QRs where
|
||||
// the synthesized list just collapses to the same URL anyway.
|
||||
scope.launch {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val resolvedRelayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
|
||||
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
|
||||
activeRelayEndpoint = relayResolved
|
||||
_activeRelayEndpoint.value = relayResolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (resolved != null) {
|
||||
_activeEndpoint.value = resolved
|
||||
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
|
||||
@@ -376,7 +396,7 @@ class ConnectionManager(
|
||||
Log.i(
|
||||
TAG,
|
||||
"connect: relay resolver picked role=${relayRoute.role} " +
|
||||
"url=${relayRoute.relay?.url}",
|
||||
"url=${relayRoute.relayWebSocketUrl()}",
|
||||
)
|
||||
}
|
||||
if (targetUrl != null) {
|
||||
@@ -434,7 +454,22 @@ class ConnectionManager(
|
||||
replaceReason: String = "Relay socket replaced",
|
||||
preserveReconnectBackoff: Boolean = false,
|
||||
) {
|
||||
val isInsecure = url.startsWith("ws://") && !url.startsWith("wss://")
|
||||
val endpoints = RelayEndpointContract.parseOrNull(url)
|
||||
if (endpoints == null) {
|
||||
Log.e(TAG, "Invalid Relay URL")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = context?.getString(R.string.conn_diag_url_invalid) ?: "Relay socket URL invalid",
|
||||
detail = "Malformed or unsafe Relay URL",
|
||||
operation = "Open Relay WebSocket",
|
||||
configuredUrl = url,
|
||||
suggestion = "Use a Relay URL with no credentials, query, or fragment.",
|
||||
)
|
||||
return
|
||||
}
|
||||
val normalized = endpoints.webSocketUrl
|
||||
val isInsecure = normalized.startsWith("ws://", ignoreCase = true)
|
||||
if (isInsecure && !_insecureMode.value) {
|
||||
Log.e(TAG, "Blocked ws:// connection — insecure mode is disabled. Use wss:// or enable insecure mode in Settings.")
|
||||
DiagnosticsLog.record(
|
||||
@@ -448,25 +483,6 @@ class ConnectionManager(
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!url.startsWith("ws://") && !url.startsWith("wss://")) {
|
||||
Log.e(TAG, "Invalid URL scheme — must start with ws:// or wss://")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = context?.getString(R.string.conn_diag_url_invalid) ?: "Relay socket URL invalid",
|
||||
detail = "URL must start with ws:// or wss://",
|
||||
operation = "Open Relay WebSocket",
|
||||
configuredUrl = url,
|
||||
suggestion = "Edit or re-pair the Relay route with a ws:// or wss:// URL.",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Normalize: append /ws if the user gave us a bare host:port with no
|
||||
// path. The relay routes the WebSocket handler at /ws; a bare URL
|
||||
// hits the HTTP root and comes back as 404 Not Found during the
|
||||
// upgrade handshake. We still accept an explicit path if present.
|
||||
val normalized = normalizeRelayUrl(url)
|
||||
if (isRelayRateLimitBackoffActive(
|
||||
rateLimitBackoffUntilMs,
|
||||
SystemClock.elapsedRealtime(),
|
||||
@@ -531,7 +547,8 @@ class ConnectionManager(
|
||||
* for any reason we don't block the connect loop forever.
|
||||
*/
|
||||
suspend fun resolveBestEndpoint(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
|
||||
private suspend fun resolveBestEndpointSafe(
|
||||
surface: EndpointSurface,
|
||||
@@ -609,7 +626,9 @@ class ConnectionManager(
|
||||
suspend fun probeAndReconnectNow(): EndpointCandidate? {
|
||||
endpointResolver?.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
|
||||
// Transient probe miss while the relay socket is demonstrably up
|
||||
@@ -618,8 +637,9 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
if (relayResolved != null) activeRelayEndpoint = relayResolved
|
||||
val targetUrl = relayResolved?.relay?.url ?: current ?: return resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
|
||||
val normalizedTarget = normalizeRelayUrl(targetUrl)
|
||||
// Reconnect when the winner changed, and also when the socket is
|
||||
// stale/disconnected on the same winner. The latter makes the
|
||||
@@ -656,7 +676,9 @@ class ConnectionManager(
|
||||
*/
|
||||
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
|
||||
if (clearProbeCache) endpointResolver?.clearCache()
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
|
||||
// Transient probe miss while the relay socket is demonstrably up
|
||||
// (slow resume, mid-handoff blip) — keep publishing the live
|
||||
@@ -665,6 +687,7 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -681,7 +704,7 @@ class ConnectionManager(
|
||||
fun getManualRoleOverride(): String? = _manualRoleOverride.value
|
||||
|
||||
private fun markActiveRelayEndpointUnreachable(reason: String) {
|
||||
val active = activeRelayEndpoint ?: return
|
||||
val active = _activeRelayEndpoint.value ?: return
|
||||
endpointResolver?.markUnreachable(active, EndpointSurface.Relay)
|
||||
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
|
||||
}
|
||||
@@ -707,7 +730,9 @@ class ConnectionManager(
|
||||
// manages its own cache (clear + markUnreachable) and passes false.
|
||||
if (wipeCache) endpointResolver.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
if (resolved == null) {
|
||||
// Hysteresis for the AUTOMATIC (network-callback) path. A
|
||||
// transient cold-route probe miss must NOT null the published
|
||||
@@ -744,6 +769,7 @@ class ConnectionManager(
|
||||
}
|
||||
sustainedLossDeclared = false
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (current == null) return@launch
|
||||
// After an explicit disconnect() the route still publishes above
|
||||
// (HTTP surfaces keep roaming), but no socket action: without
|
||||
@@ -753,8 +779,8 @@ class ConnectionManager(
|
||||
// the swap path never re-checked it.)
|
||||
if (!shouldReconnect) return@launch
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
if (relayResolved != null) activeRelayEndpoint = relayResolved
|
||||
val relayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
?: return@launch
|
||||
if (isRelayRateLimitBackoffActive(
|
||||
rateLimitBackoffUntilMs,
|
||||
@@ -859,21 +885,8 @@ class ConnectionManager(
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeRelayUrl(url: String): String {
|
||||
// Strip scheme to reason about the path portion cheaply.
|
||||
val schemeEnd = url.indexOf("://")
|
||||
if (schemeEnd < 0) return url
|
||||
val afterScheme = url.substring(schemeEnd + 3)
|
||||
val pathStart = afterScheme.indexOf('/')
|
||||
return if (pathStart < 0) {
|
||||
// No path at all — append /ws
|
||||
"$url/ws"
|
||||
} else {
|
||||
val path = afterScheme.substring(pathStart)
|
||||
// Empty or root path — append ws
|
||||
if (path == "/" || path.isEmpty()) "${url.trimEnd('/')}/ws" else url
|
||||
}
|
||||
}
|
||||
private fun normalizeRelayUrl(url: String): String =
|
||||
RelayEndpointContract.parseOrNull(url)?.webSocketUrl ?: url
|
||||
|
||||
fun disconnect() {
|
||||
shouldReconnect = false
|
||||
@@ -899,7 +912,8 @@ class ConnectionManager(
|
||||
// the ViewModel on the next connection load.
|
||||
_manualRoleOverride.value = null
|
||||
_activeEndpoint.value = null
|
||||
activeRelayEndpoint = null
|
||||
_activeApiEndpoint.value = null
|
||||
_activeRelayEndpoint.value = null
|
||||
reconnectState.reset()
|
||||
}
|
||||
|
||||
@@ -979,7 +993,18 @@ class ConnectionManager(
|
||||
// Every new socket starts unauthenticated — the send-gate stays closed
|
||||
// (auth frame excepted) until this socket's own auth.ok arrives.
|
||||
authenticated = false
|
||||
client = buildClient()
|
||||
val isPluginProxyUrl = _activeRelayEndpoint.value?.pluginProxyRoutesOrNull()
|
||||
?.relayWebSocketUrl
|
||||
?.equals(url, ignoreCase = true) == true
|
||||
client = if (isPluginProxyUrl) {
|
||||
proxyClientProvider?.invoke(url) ?: run {
|
||||
Log.e(TAG, "Pinned plugin proxy client unavailable — refusing generic TLS fallback")
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
return
|
||||
}
|
||||
} else {
|
||||
buildClient(url)
|
||||
}
|
||||
|
||||
val request = buildRelayRequestOrNull(url)
|
||||
if (request == null) {
|
||||
@@ -1213,8 +1238,9 @@ class ConnectionManager(
|
||||
SLOW_POLL_BACKOFF_MS
|
||||
}
|
||||
else -> {
|
||||
val ms = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
|
||||
val capMs = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
|
||||
.coerceAtMost(MAX_BACKOFF_MS)
|
||||
val ms = fullJitterDelayMs(capMs, reconnectJitterUnit())
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Info,
|
||||
@@ -1236,7 +1262,7 @@ class ConnectionManager(
|
||||
// during the retry window).
|
||||
if (shouldReconnect && reconnectGate()) {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val targetUrl = resolved?.relay?.url
|
||||
val targetUrl = resolved?.relayWebSocketUrl()
|
||||
if (resolved != null) {
|
||||
// Mirror scheduleNetworkReResolve: clear the sustained-loss
|
||||
// latch on a successful resolve so a later transient miss
|
||||
@@ -1244,7 +1270,7 @@ class ConnectionManager(
|
||||
// in onLost's grace job but can be cleared on EITHER success
|
||||
// edge — network-callback or relay-timer.)
|
||||
sustainedLossDeclared = false
|
||||
activeRelayEndpoint = resolved
|
||||
_activeRelayEndpoint.value = resolved
|
||||
}
|
||||
if (targetUrl != null && normalizeRelayUrl(targetUrl) != url) {
|
||||
Log.i(TAG, "scheduleReconnect: switching $url → ${normalizeRelayUrl(targetUrl)}")
|
||||
|
||||
+31
-16
@@ -5,7 +5,9 @@ import android.util.Log
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import com.hermesandroid.relay.notifications.ProactiveMessageNotifier
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
/**
|
||||
@@ -50,7 +52,7 @@ class ProactiveMessageHandler(
|
||||
/** Sink for the dedicated Hermes inbox (Phase 2a) — the always-present log. */
|
||||
private val toInbox: ((ProactiveMessage) -> Unit)? = null,
|
||||
/** Sink for injecting into the active chat session (Phase 2b). */
|
||||
var toSession: ((ProactiveMessage) -> Unit)? = null,
|
||||
var toSession: ((ProactiveMessage) -> Boolean)? = null,
|
||||
/**
|
||||
* Sink for the relay's per-reply ack (`proactive.reply.ack`) — lets the
|
||||
* chat layer settle a Thread reply bubble from SENDING → DELIVERED. Wired
|
||||
@@ -61,11 +63,13 @@ class ProactiveMessageHandler(
|
||||
/**
|
||||
* Show an inbound message inline in the Chat **Thread** it belongs to, when
|
||||
* that Thread is currently open. Returns true if it was shown there — in
|
||||
* which case the message is NOT also notified or added to the inbox (you're
|
||||
* already looking at the conversation). The unified-Threads counterpart of
|
||||
* which case the message is persisted but not also notified (you're already
|
||||
* looking at the conversation). The unified-Threads counterpart of
|
||||
* [toSession]; wired after construction.
|
||||
*/
|
||||
var injectIntoThread: ((ProactiveMessage) -> Boolean)? = null,
|
||||
/** One callback per completed queued-message flush, never per message. */
|
||||
var onBacklogDelivered: ((Int) -> Unit)? = null,
|
||||
) {
|
||||
|
||||
fun onMessage(envelope: Envelope) {
|
||||
@@ -80,6 +84,10 @@ class ProactiveMessageHandler(
|
||||
}
|
||||
// Subscribe ack — informational; nothing to do client-side.
|
||||
"proactive.subscribed" -> Log.d(TAG, "proactive subscribe acked")
|
||||
"proactive.backlog.complete" -> {
|
||||
val count = envelope.payload["count"]?.jsonPrimitive?.intOrNull ?: 0
|
||||
if (count > 0) onBacklogDelivered?.invoke(count)
|
||||
}
|
||||
// Per-reply ack — settle the matching Thread reply bubble (the
|
||||
// `client_msg_id` is the id the app stamped on its own reply).
|
||||
"proactive.reply.ack" -> {
|
||||
@@ -94,24 +102,28 @@ class ProactiveMessageHandler(
|
||||
/** Route a parsed message: into the open Thread if it belongs there, else
|
||||
* the durable inbox log + the surface its hint selects. */
|
||||
private fun dispatch(msg: ProactiveMessage) {
|
||||
// Unified Threads: if this message belongs to the Thread currently open
|
||||
// in Chat, render it inline there and STOP — no notification, no inbox
|
||||
// entry (you're already looking at the conversation).
|
||||
if (injectIntoThread?.invoke(msg) == true) return
|
||||
// Otherwise the inbox is the durable log of agent-initiated messages and
|
||||
// the surfacing hint selects the additional surface.
|
||||
// Persist first even when the currently open Thread consumes the live
|
||||
// message. Agent-initiated outbound sends do not create a gateway
|
||||
// session until the phone replies, so this cache is the provisional
|
||||
// Thread transcript during that gap.
|
||||
toInbox?.invoke(msg)
|
||||
// The surfacing hint selects the additional surface. Thread injection
|
||||
// is best-effort presentation of the persisted row, not itself a reason
|
||||
// to suppress an explicitly requested notification.
|
||||
when (msg.surfacing?.lowercase()) {
|
||||
"inbox" -> { /* inbox only — already recorded above */ }
|
||||
"inbox" -> {
|
||||
injectIntoThread?.invoke(msg)
|
||||
}
|
||||
"session" -> {
|
||||
val sink = toSession
|
||||
// Legacy explicit "inject into active session" path; if no sink
|
||||
// (or no active chat) fall back to a notification so it isn't
|
||||
// silently missed (the inbox copy already exists either way).
|
||||
if (sink != null) sink.invoke(msg) else notify(msg)
|
||||
val delivered = injectIntoThread?.invoke(msg) == true ||
|
||||
toSession?.invoke(msg) == true
|
||||
if (!delivered) notify(msg)
|
||||
}
|
||||
// null / "default" / "notification" / anything unrecognized.
|
||||
else -> notify(msg)
|
||||
else -> {
|
||||
injectIntoThread?.invoke(msg)
|
||||
notify(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +148,7 @@ class ProactiveMessageHandler(
|
||||
surfacing = payload["surfacing"]?.jsonPrimitive?.contentOrNull,
|
||||
sentAt = payload["sent_at"]?.jsonPrimitive?.contentOrNull?.toLongOrNull(),
|
||||
replyTo = payload["reply_to"]?.jsonPrimitive?.contentOrNull,
|
||||
arrivedWhileAway = payload["queued_delivery"]?.jsonPrimitive?.booleanOrNull == true,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,4 +170,6 @@ data class ProactiveMessage(
|
||||
val sentAt: Long?,
|
||||
/** Id of the message this one answers, if any (server threading hint). */
|
||||
val replyTo: String? = null,
|
||||
/** True only when Relay explicitly marked this as a reconnect queue flush. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.auth.PairedDeviceInfo
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||
@@ -59,6 +60,9 @@ class RelayHttpClient(
|
||||
private val context: Context? = null,
|
||||
) {
|
||||
|
||||
private fun relayHttpBaseOrNull(url: String): String? =
|
||||
RelayEndpointContract.parseOrNull(url)?.httpBaseUrl
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayHttpClient"
|
||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||
@@ -180,10 +184,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
val url = try {
|
||||
"$httpBase/chat/image-activity".toHttpUrl().newBuilder()
|
||||
.addQueryParameter("profile", profile)
|
||||
@@ -247,10 +249,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = "$httpBase/media/$token".toHttpUrlOrNull()
|
||||
?: return@withContext Result.failure(
|
||||
@@ -299,10 +299,10 @@ class RelayHttpClient(
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMedia failed for $token: ${e.message}")
|
||||
Log.w(TAG, "fetchMedia failed: ${e.message}")
|
||||
Result.failure(e)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMedia unexpected error for $token: ${e.message}")
|
||||
Log.w(TAG, "fetchMedia unexpected error: ${e.message}")
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
@@ -344,10 +344,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
// Build the URL via OkHttp's HttpUrl builder so query-param encoding
|
||||
// handles paths with slashes, spaces, and non-ASCII characters
|
||||
@@ -442,10 +440,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
val profile = profileName?.trim()?.ifBlank { null } ?: "default"
|
||||
val url = try {
|
||||
"$httpBase/api/profiles".toHttpUrl().newBuilder()
|
||||
@@ -543,10 +539,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = try {
|
||||
"$httpBase/context/injected".toHttpUrl()
|
||||
@@ -635,10 +629,8 @@ class RelayHttpClient(
|
||||
IllegalStateException("Relay not paired — session token missing")
|
||||
)
|
||||
}
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
val url = try {
|
||||
"$httpBase/phone/threads".toHttpUrl()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
@@ -754,10 +746,8 @@ class RelayHttpClient(
|
||||
if (relayUrl.isEmpty() || token.isNullOrBlank()) {
|
||||
return@withContext Result.failure(IllegalStateException("Relay is not configured and paired"))
|
||||
}
|
||||
val base = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val base = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
val url = try { "$base/relay/info".toHttpUrl() } catch (e: IllegalArgumentException) {
|
||||
return@withContext Result.failure(IOException("Invalid relay URL: ${e.message}"))
|
||||
}
|
||||
@@ -802,10 +792,8 @@ class RelayHttpClient(
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
val token = sessionTokenProvider()
|
||||
if (relayUrl.isEmpty() || token.isNullOrBlank()) return@withContext Result.success(null)
|
||||
val base = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val base = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.success(null)
|
||||
val url = runCatching { "$base/relay/model-capabilities".toHttpUrl() }.getOrElse {
|
||||
return@withContext Result.success(null)
|
||||
}
|
||||
@@ -858,10 +846,8 @@ class RelayHttpClient(
|
||||
IllegalStateException("Relay not paired — session token missing")
|
||||
)
|
||||
}
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
val url = try {
|
||||
"$httpBase/relay/update-check".toHttpUrl()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
@@ -944,10 +930,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = "$httpBase/sessions".toHttpUrlOrNull()
|
||||
?: return@withContext Result.failure(
|
||||
@@ -1027,10 +1011,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = try {
|
||||
"$httpBase/sessions/".toHttpUrl().newBuilder()
|
||||
@@ -1121,10 +1103,8 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = try {
|
||||
"$httpBase/sessions/".toHttpUrl().newBuilder()
|
||||
@@ -1241,28 +1221,23 @@ class RelayHttpClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = trimmed
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val startedAtMs = System.currentTimeMillis()
|
||||
|
||||
val url = try {
|
||||
"$httpBase/health".toHttpUrl()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
val endpoints = RelayEndpointContract.parseOrNull(trimmed)
|
||||
if (endpoints == null) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = context?.getString(R.string.http_diag_url_invalid) ?: "Relay URL invalid",
|
||||
detail = e.message,
|
||||
detail = "Malformed or unsafe Relay URL",
|
||||
operation = operation,
|
||||
configuredUrl = relayUrl,
|
||||
suggestion = "Enter a Relay URL beginning with ws:// or wss://.",
|
||||
suggestion = "Enter a Relay URL with no credentials, query, or fragment.",
|
||||
)
|
||||
return@withContext Result.failure(
|
||||
IOException("Invalid relay URL: ${e.message}")
|
||||
IOException("Invalid relay URL")
|
||||
)
|
||||
}
|
||||
val url = endpoints.healthUrl.toHttpUrl()
|
||||
|
||||
// Fast-timeout client — we don't want Save & Test to hang the UI
|
||||
// for 10 seconds on a dead URL.
|
||||
|
||||
+26
-33
@@ -7,6 +7,9 @@ import com.hermesandroid.relay.data.ProfileSkillsResponse
|
||||
import com.hermesandroid.relay.data.ProfileSoulResponse
|
||||
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
|
||||
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
|
||||
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
|
||||
import com.hermesandroid.relay.data.RelaySkillToggleResult
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.SerializationException
|
||||
@@ -48,7 +51,10 @@ class RelayProfileInspectorClient(
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val relayUrlProvider: () -> String?,
|
||||
private val sessionTokenProvider: suspend () -> String?,
|
||||
) {
|
||||
) : LegacyProfileInspectorClient {
|
||||
|
||||
private fun relayHttpBaseOrNull(url: String): String? =
|
||||
RelayEndpointContract.parseOrNull(url)?.httpBaseUrl
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayProfileInspector"
|
||||
@@ -79,19 +85,19 @@ class RelayProfileInspectorClient(
|
||||
|
||||
|
||||
/** Fetch `GET /api/profiles/{name}/config`. */
|
||||
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
|
||||
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
|
||||
get(profileName, "config", ProfileConfigResponse.serializer())
|
||||
|
||||
/** Fetch `GET /api/profiles/{name}/skills`. */
|
||||
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
|
||||
override suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
|
||||
get(profileName, "skills", ProfileSkillsResponse.serializer())
|
||||
|
||||
/** Fetch `GET /api/profiles/{name}/soul`. */
|
||||
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
|
||||
override suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
|
||||
get(profileName, "soul", ProfileSoulResponse.serializer())
|
||||
|
||||
/** Fetch `GET /api/profiles/{name}/memory`. */
|
||||
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
|
||||
override suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
|
||||
get(profileName, "memory", ProfileMemoryResponse.serializer())
|
||||
|
||||
/**
|
||||
@@ -108,7 +114,7 @@ class RelayProfileInspectorClient(
|
||||
* would be a protocol violation; we send empty-string for an empty
|
||||
* SOUL.
|
||||
*/
|
||||
suspend fun updateSoul(
|
||||
override suspend fun updateSoul(
|
||||
profileName: String,
|
||||
content: String,
|
||||
): Result<ProfileSoulUpdateResponse> = withContext(Dispatchers.IO) {
|
||||
@@ -137,7 +143,7 @@ class RelayProfileInspectorClient(
|
||||
* Used for both creating a new memory entry (the relay writes the
|
||||
* file if missing) and updating an existing entry.
|
||||
*/
|
||||
suspend fun updateMemoryEntry(
|
||||
override suspend fun updateMemoryEntry(
|
||||
profileName: String,
|
||||
filename: String,
|
||||
content: String,
|
||||
@@ -189,10 +195,8 @@ class RelayProfileInspectorClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val encodedName = URLEncoder.encode(profileName, "UTF-8").replace("+", "%20")
|
||||
|
||||
@@ -270,10 +274,10 @@ class RelayProfileInspectorClient(
|
||||
* server" snackbar and ghost out the toggle. When the real
|
||||
* implementation lands server-side, this method needs no change.
|
||||
*/
|
||||
suspend fun updateSkillToggle(
|
||||
override suspend fun updateSkillToggle(
|
||||
skillName: String,
|
||||
enabled: Boolean,
|
||||
): Result<SkillToggleResult> = withContext(Dispatchers.IO) {
|
||||
): Result<RelaySkillToggleResult> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
return@withContext Result.failure(
|
||||
@@ -287,10 +291,8 @@ class RelayProfileInspectorClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
val url = try {
|
||||
"$httpBase/api/skills/toggle".toHttpUrl()
|
||||
@@ -319,8 +321,8 @@ class RelayProfileInspectorClient(
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
when (response.code) {
|
||||
in 200..299 -> Result.success(SkillToggleResult.Ok)
|
||||
501 -> Result.success(SkillToggleResult.NotImplemented)
|
||||
in 200..299 -> Result.success(RelaySkillToggleResult.Ok)
|
||||
501 -> Result.success(RelaySkillToggleResult.NotImplemented)
|
||||
401, 403 -> Result.failure(
|
||||
IOException("Unauthorized — re-pair with the relay")
|
||||
)
|
||||
@@ -348,15 +350,13 @@ class RelayProfileInspectorClient(
|
||||
* "not implemented" and any 2xx as "supported". The relay serves
|
||||
* OPTIONS via aiohttp's CORS handling by default.
|
||||
*/
|
||||
suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
|
||||
override suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) return@withContext false
|
||||
val sessionToken = sessionTokenProvider() ?: return@withContext false
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext false
|
||||
|
||||
val url = try {
|
||||
"$httpBase/api/skills/toggle".toHttpUrl()
|
||||
@@ -402,11 +402,6 @@ class RelayProfileInspectorClient(
|
||||
* answered 501 — not implemented yet" without inventing magic
|
||||
* error strings.
|
||||
*/
|
||||
sealed class SkillToggleResult {
|
||||
data object Ok : SkillToggleResult()
|
||||
data object NotImplemented : SkillToggleResult()
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort pull of a `detail` or `error` string out of a relay
|
||||
* 400 body. Falls back to the first 120 chars of the payload when
|
||||
@@ -448,10 +443,8 @@ class RelayProfileInspectorClient(
|
||||
)
|
||||
}
|
||||
|
||||
val httpBase = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
val httpBase = relayHttpBaseOrNull(relayUrl)
|
||||
?: return@withContext Result.failure(IOException("Invalid relay URL"))
|
||||
|
||||
// Percent-encode the profile name for splicing into the path —
|
||||
// profile names are typically ASCII identifiers but nothing
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.EnhancedVoiceOverrides
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.RealtimeConversationContextMessage
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -2616,13 +2617,7 @@ class RelayVoiceClient(
|
||||
private fun resolveHttpBase(): String? {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) return null
|
||||
val normalized = relayUrl
|
||||
.replace(Regex("^wss://", RegexOption.IGNORE_CASE), "https://")
|
||||
.replace(Regex("^ws://", RegexOption.IGNORE_CASE), "http://")
|
||||
.trimEnd('/')
|
||||
// Reject a malformed base up front so callers' url("$base/…") can't throw
|
||||
// IllegalArgumentException on the IO dispatcher (relay half of #131).
|
||||
return if (normalized.toHttpUrlOrNull() != null) normalized else null
|
||||
return RelayEndpointContract.parseOrNull(relayUrl)?.httpBaseUrl
|
||||
}
|
||||
|
||||
private fun resolveWebSocketBase(): String? {
|
||||
@@ -2633,10 +2628,7 @@ class RelayVoiceClient(
|
||||
private fun toWebSocketBase(relayUrl: String?): String? {
|
||||
val trimmed = relayUrl?.trim().orEmpty()
|
||||
if (trimmed.isEmpty()) return null
|
||||
return trimmed
|
||||
.replace(Regex("^https://", RegexOption.IGNORE_CASE), "wss://")
|
||||
.replace(Regex("^http://", RegexOption.IGNORE_CASE), "ws://")
|
||||
.trimEnd('/')
|
||||
return RelayEndpointContract.parseOrNull(trimmed)?.webSocketBaseUrl
|
||||
}
|
||||
|
||||
private suspend fun resolveBearerToken(): String? {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
|
||||
/** Secret-free failure raised before OkHttp sees a malformed credential. */
|
||||
class InvalidCredentialException internal constructor(message: String) : IOException(message)
|
||||
|
||||
/**
|
||||
* Normalize only harmless surrounding horizontal whitespace. Credentials are
|
||||
* otherwise single-line visible ASCII: embedded whitespace, CR/LF, controls,
|
||||
* and non-ASCII input are rejected instead of repaired or logged.
|
||||
*/
|
||||
fun normalizeCredentialForHeader(raw: String, label: String): String {
|
||||
val normalized = raw.trim(' ', '\t')
|
||||
if (normalized.any { it < '!' || it > '~' }) {
|
||||
throw InvalidCredentialException(
|
||||
"Invalid $label — enter or import a single-line value.",
|
||||
)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
fun Request.Builder.bearerAuthorization(
|
||||
rawCredential: String,
|
||||
label: String,
|
||||
): Request.Builder {
|
||||
val credential = normalizeCredentialForHeader(rawCredential, label)
|
||||
if (credential.isEmpty()) return this
|
||||
return header("Authorization", "Bearer $credential")
|
||||
}
|
||||
|
||||
fun Request.Builder.credentialHeader(
|
||||
name: String,
|
||||
rawCredential: String,
|
||||
label: String,
|
||||
): Request.Builder {
|
||||
val credential = normalizeCredentialForHeader(rawCredential, label)
|
||||
if (credential.isEmpty()) return this
|
||||
return header(name, credential)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
|
||||
@@ -55,6 +56,8 @@ data class RouteProbeOutcome(
|
||||
*/
|
||||
enum class EndpointSurface {
|
||||
Standard,
|
||||
Dashboard,
|
||||
Api,
|
||||
Relay,
|
||||
}
|
||||
|
||||
@@ -109,6 +112,8 @@ class EndpointResolver(
|
||||
* expected path for plain JVM tests.
|
||||
*/
|
||||
private val context: Context? = null,
|
||||
/** Route-aware client for pinned plugin proxy probes. */
|
||||
private val clientForCandidate: ((EndpointCandidate) -> OkHttpClient?)? = null,
|
||||
) {
|
||||
|
||||
/**
|
||||
@@ -196,8 +201,13 @@ class EndpointResolver(
|
||||
val authority = when (surface) {
|
||||
EndpointSurface.Standard ->
|
||||
candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()
|
||||
EndpointSurface.Dashboard ->
|
||||
routeAuthority(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url).orEmpty()
|
||||
EndpointSurface.Api ->
|
||||
routeAuthority(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url).orEmpty()
|
||||
EndpointSurface.Relay ->
|
||||
routeAuthority(candidate.relay?.url).orEmpty()
|
||||
candidate.pluginProxyRoutesOrNull()?.authority
|
||||
?: routeAuthority(candidate.relay?.url).orEmpty()
|
||||
}
|
||||
return "${surface.name.lowercase()}|${candidate.role}|$authority"
|
||||
}
|
||||
@@ -239,11 +249,16 @@ class EndpointResolver(
|
||||
val eligible = candidates.filter { probeTarget(it, surface) != null }
|
||||
if (eligible.isEmpty()) return null
|
||||
|
||||
// Strict priority: sort ascending so priority-0 lands first. Grouping
|
||||
// preserves emitted order within a priority class (DNS SRV parity).
|
||||
val groups = eligible.groupBy { it.priority }.toSortedMap()
|
||||
// Supported routes always run before experimental routes. Priority is
|
||||
// strict inside each stability tier, so Reach remains available as a
|
||||
// last-resort fallback without displacing Tailscale or direct TLS.
|
||||
val supported = eligible.filterNot { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
|
||||
val experimental = eligible.filter { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
|
||||
val groups = (supported.groupBy { it.priority }.toSortedMap().values +
|
||||
experimental.groupBy { it.priority }.toSortedMap().values)
|
||||
|
||||
for ((priority, group) in groups) {
|
||||
for (group in groups) {
|
||||
val priority = group.first().priority
|
||||
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
|
||||
val winner = raceGroup(group, surface)
|
||||
if (winner != null) {
|
||||
@@ -356,6 +371,8 @@ class EndpointResolver(
|
||||
val startedAtMs = clock()
|
||||
val operation = when (surface) {
|
||||
EndpointSurface.Standard -> "Dashboard or API route health probe"
|
||||
EndpointSurface.Dashboard -> "Dashboard route health probe"
|
||||
EndpointSurface.Api -> "API route health probe"
|
||||
EndpointSurface.Relay -> "Relay route health probe"
|
||||
}
|
||||
val target = probeTarget(candidate, surface)
|
||||
@@ -375,7 +392,7 @@ class EndpointResolver(
|
||||
recordOutcome(candidate, surface, reachable = false, detail = "Invalid route URL")
|
||||
return false
|
||||
}
|
||||
val fastClient = httpClient.newBuilder()
|
||||
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
|
||||
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
@@ -480,6 +497,29 @@ class EndpointResolver(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
): ProbeTarget? {
|
||||
if (surface == EndpointSurface.Dashboard) {
|
||||
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { base ->
|
||||
return ProbeTarget(base, "$base/api/status", "/dashboard/api/status")
|
||||
}
|
||||
candidate.dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }?.let { base ->
|
||||
return ProbeTarget(base, "$base/api/status", "/api/status")
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (surface == EndpointSurface.Api) {
|
||||
candidate.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { base ->
|
||||
return ProbeTarget(base, "$base/health", "/api/health")
|
||||
}
|
||||
candidate.api?.url?.let { base -> return ProbeTarget(base, "$base/health", "/health") }
|
||||
return null
|
||||
}
|
||||
if (surface == EndpointSurface.Relay) candidate.pluginProxyRoutesOrNull()?.let { proxy ->
|
||||
return ProbeTarget(
|
||||
baseUrl = proxy.relayHttpUrl,
|
||||
requestUrl = "${proxy.relayHttpUrl}/health",
|
||||
path = "/relay/health",
|
||||
)
|
||||
}
|
||||
if (surface == EndpointSurface.Relay) {
|
||||
return relayProbeTarget(candidate)
|
||||
}
|
||||
@@ -509,26 +549,24 @@ class EndpointResolver(
|
||||
private fun relayProbeTarget(candidate: EndpointCandidate): ProbeTarget? {
|
||||
candidate.relay?.url
|
||||
?.trim()
|
||||
?.trimEnd('/')
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { relayUrl ->
|
||||
val httpBase = when {
|
||||
relayUrl.startsWith("ws://", ignoreCase = true) ->
|
||||
"http://${relayUrl.substringAfter("://")}"
|
||||
relayUrl.startsWith("wss://", ignoreCase = true) ->
|
||||
"https://${relayUrl.substringAfter("://")}"
|
||||
else -> return null
|
||||
}
|
||||
val endpoints = RelayEndpointContract.parseOrNull(relayUrl) ?: return null
|
||||
return ProbeTarget(
|
||||
baseUrl = relayUrl,
|
||||
requestUrl = "$httpBase/health",
|
||||
path = "/health",
|
||||
baseUrl = endpoints.webSocketUrl,
|
||||
requestUrl = endpoints.healthUrl,
|
||||
path = endpoints.healthUrl.toHttpUrlOrNull()?.encodedPath ?: return null,
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun probeRequestUrlForTest(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
): String? = probeTarget(candidate, surface)?.requestUrl
|
||||
|
||||
/**
|
||||
* Map a probe exception to a short, actionable string for the Routes
|
||||
* card. The TLS case is the headline: a route saved with `https://`
|
||||
@@ -546,6 +584,8 @@ class EndpointResolver(
|
||||
|
||||
private fun EndpointSurface.diagnosticTarget(): String = when (this) {
|
||||
EndpointSurface.Standard -> "Dashboard or API server"
|
||||
EndpointSurface.Dashboard -> "Dashboard"
|
||||
EndpointSurface.Api -> "API server"
|
||||
EndpointSurface.Relay -> "Relay"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.isValidHermesReach
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Socket
|
||||
import java.net.SocketAddress
|
||||
import java.net.SocketException
|
||||
import java.net.URI
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import java.util.ArrayDeque
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.net.SocketFactory
|
||||
|
||||
private const val REACH_PROTOCOL_VERSION = 1
|
||||
private const val REACH_MAX_FRAME_BYTES = 1024 * 1024
|
||||
internal const val REACH_MAX_QUEUED_FRAMES = 32
|
||||
internal const val REACH_MAX_QUEUED_BYTES = 8 * 1024 * 1024
|
||||
private const val REACH_MATCH_TIMEOUT_MS = 10_000L
|
||||
|
||||
/**
|
||||
* Connection metadata for Hermes Reach's outer WSS rendezvous.
|
||||
*
|
||||
* This is deliberately transport-only. The inner HTTPS/WSS origin and its
|
||||
* pairing-authenticated SPKI pin continue to be owned by [PluginProxyRoutes],
|
||||
* so broker reachability can never weaken Secure Link trust.
|
||||
*/
|
||||
data class HermesReachRoute(
|
||||
val brokerUrl: String,
|
||||
val hostId: String,
|
||||
val credentialKind: String,
|
||||
val token: String,
|
||||
) {
|
||||
fun tunnelUrlOrNull(): String? {
|
||||
if (hostId.isBlank() || token.isBlank()) return null
|
||||
if (credentialKind !in setOf("bootstrap", "route")) return null
|
||||
val uri = runCatching { URI(brokerUrl.trim()) }.getOrNull() ?: return null
|
||||
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return null
|
||||
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
|
||||
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" && it != "/v1/connect" }) return null
|
||||
val authority = buildString {
|
||||
append(if (':' in uri.host) "[${uri.host}]" else uri.host)
|
||||
if (uri.port > 0 && uri.port != 443) append(":${uri.port}")
|
||||
}
|
||||
return "wss://$authority/v1/connect"
|
||||
}
|
||||
}
|
||||
|
||||
fun EndpointCandidate.hermesReachRouteOrNull(): HermesReachRoute? {
|
||||
val metadata = broker?.takeIf { it.isValidHermesReach() } ?: return null
|
||||
if (pluginProxyRoutesOrNull() == null) return null
|
||||
return HermesReachRoute(
|
||||
brokerUrl = metadata.url,
|
||||
hostId = metadata.hostId,
|
||||
credentialKind = metadata.credentialKind,
|
||||
token = metadata.token,
|
||||
)
|
||||
}
|
||||
|
||||
/** Build the pinned inner Secure Link client over an outer Hermes Reach WSS. */
|
||||
fun buildHermesReachClient(
|
||||
baseBuilder: OkHttpClient.Builder,
|
||||
outerClient: OkHttpClient,
|
||||
candidate: EndpointCandidate,
|
||||
sessionTokenProvider: () -> String?,
|
||||
includeRelaySessionHeader: Boolean = true,
|
||||
): OkHttpClient? {
|
||||
val secureLink = candidate.pluginProxyRoutesOrNull() ?: return null
|
||||
val reach = candidate.hermesReachRouteOrNull() ?: return null
|
||||
return buildPluginProxyClient(
|
||||
baseBuilder = baseBuilder,
|
||||
routes = secureLink,
|
||||
sessionTokenProvider = sessionTokenProvider,
|
||||
includeRelaySessionHeader = includeRelaySessionHeader,
|
||||
rawSocketFactory = HermesReachSocketFactory(outerClient, reach),
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class ReachRegistration(
|
||||
val type: String = "register",
|
||||
@SerialName("protocol_version") val protocolVersion: Int = REACH_PROTOCOL_VERSION,
|
||||
val role: String = "client",
|
||||
@SerialName("host_id") val hostId: String,
|
||||
@SerialName("connection_id") val connectionId: String,
|
||||
@SerialName("credential_kind") val credentialKind: String,
|
||||
val token: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class ReachControl(
|
||||
val type: String? = null,
|
||||
@SerialName("protocol_version") val protocolVersion: Int? = null,
|
||||
@SerialName("stream_id") val streamId: String? = null,
|
||||
val code: String? = null,
|
||||
)
|
||||
|
||||
internal object HermesReachHandshake {
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = false
|
||||
encodeDefaults = true
|
||||
}
|
||||
|
||||
fun registration(route: HermesReachRoute, connectionId: String): String = json.encodeToString(
|
||||
ReachRegistration(
|
||||
hostId = route.hostId,
|
||||
connectionId = connectionId,
|
||||
credentialKind = route.credentialKind,
|
||||
token = route.token,
|
||||
),
|
||||
)
|
||||
|
||||
fun validateMatched(payload: String): String? {
|
||||
val control = runCatching { json.decodeFromString<ReachControl>(payload) }
|
||||
.getOrElse { return "Hermes Reach returned an invalid match response" }
|
||||
if (control.type == "error") {
|
||||
return "Hermes Reach rejected the route (${control.code ?: "unknown"})"
|
||||
}
|
||||
val streamIdValid = control.streamId?.let(::isCanonicalId) == true
|
||||
if (control.type != "matched" ||
|
||||
control.protocolVersion != REACH_PROTOCOL_VERSION ||
|
||||
!streamIdValid
|
||||
) {
|
||||
return "Hermes Reach returned a mismatched route response"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun isCanonicalId(value: String): Boolean {
|
||||
if (value.isBlank() || '=' in value) return false
|
||||
val decoded = runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull() ?: return false
|
||||
return decoded.size == 16 && Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw socket factory that carries bytes through Hermes Reach. OkHttp layers
|
||||
* the normal Secure Link TLS socket factory over the returned socket, so SNI,
|
||||
* hostname verification, and the QR SPKI pin all apply to the inner endpoint.
|
||||
*/
|
||||
class HermesReachSocketFactory(
|
||||
private val outerClient: OkHttpClient,
|
||||
private val route: HermesReachRoute,
|
||||
) : SocketFactory() {
|
||||
init {
|
||||
require(route.tunnelUrlOrNull() != null) { "Invalid Hermes Reach route" }
|
||||
}
|
||||
|
||||
override fun createSocket(): Socket = HermesReachSocket(outerClient, route)
|
||||
|
||||
override fun createSocket(host: String?, port: Int): Socket =
|
||||
createSocket().apply { connect(InetSocketAddress(host, port)) }
|
||||
|
||||
override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket =
|
||||
createSocket().apply {
|
||||
if (localHost != null) bind(InetSocketAddress(localHost, localPort))
|
||||
connect(InetSocketAddress(host, port))
|
||||
}
|
||||
|
||||
override fun createSocket(host: InetAddress?, port: Int): Socket =
|
||||
createSocket().apply { connect(InetSocketAddress(host, port)) }
|
||||
|
||||
override fun createSocket(
|
||||
address: InetAddress?,
|
||||
port: Int,
|
||||
localAddress: InetAddress?,
|
||||
localPort: Int,
|
||||
): Socket = createSocket().apply {
|
||||
if (localAddress != null) bind(InetSocketAddress(localAddress, localPort))
|
||||
connect(InetSocketAddress(address, port))
|
||||
}
|
||||
}
|
||||
|
||||
private class HermesReachSocket(
|
||||
private val outerClient: OkHttpClient,
|
||||
private val route: HermesReachRoute,
|
||||
) : Socket() {
|
||||
private val inbound = ReachInputStream()
|
||||
private val matchLatch = CountDownLatch(1)
|
||||
private val connectionId = randomConnectionId()
|
||||
@Volatile private var matchError: IOException? = null
|
||||
@Volatile private var webSocket: WebSocket? = null
|
||||
@Volatile private var connected = false
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var matched = false
|
||||
@Volatile private var remote: InetSocketAddress? = null
|
||||
private var readTimeoutMs: Int = 0
|
||||
|
||||
private val outbound = object : OutputStream() {
|
||||
override fun write(value: Int) = write(byteArrayOf(value.toByte()))
|
||||
|
||||
override fun write(bytes: ByteArray, offset: Int, length: Int) {
|
||||
if (length == 0) return
|
||||
if (!matched || closed) throw SocketException("Hermes Reach tunnel is not open")
|
||||
var cursor = offset
|
||||
var remaining = length
|
||||
while (remaining > 0) {
|
||||
val count = minOf(remaining, REACH_MAX_FRAME_BYTES)
|
||||
val accepted = webSocket?.send(ByteString.of(*bytes.copyOfRange(cursor, cursor + count))) == true
|
||||
if (!accepted) throw SocketException("Hermes Reach could not queue tunnel bytes")
|
||||
cursor += count
|
||||
remaining -= count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun connect(endpoint: SocketAddress?) = connect(endpoint, REACH_MATCH_TIMEOUT_MS.toInt())
|
||||
|
||||
override fun connect(endpoint: SocketAddress?, timeout: Int) {
|
||||
if (connected) throw SocketException("Socket is already connected")
|
||||
if (closed) throw SocketException("Socket is closed")
|
||||
remote = endpoint as? InetSocketAddress
|
||||
?: throw SocketException("Hermes Reach requires an internet socket target")
|
||||
val request = Request.Builder().url(requireNotNull(route.tunnelUrlOrNull())).build()
|
||||
webSocket = outerClient.newWebSocket(request, listener)
|
||||
val waitMs = minOf(
|
||||
timeout.takeIf { it > 0 }?.toLong() ?: REACH_MATCH_TIMEOUT_MS,
|
||||
REACH_MATCH_TIMEOUT_MS,
|
||||
)
|
||||
if (!matchLatch.await(waitMs, TimeUnit.MILLISECONDS)) {
|
||||
closeWithError(IOException("Hermes Reach host match timed out"))
|
||||
}
|
||||
matchError?.let { throw it }
|
||||
if (!matched) throw IOException("Hermes Reach closed before matching the host")
|
||||
connected = true
|
||||
}
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
val registration = HermesReachHandshake.registration(route, connectionId)
|
||||
if (!webSocket.send(registration)) {
|
||||
closeWithError(IOException("Hermes Reach registration could not be sent"))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
if (matched) {
|
||||
closeWithError(IOException("Hermes Reach sent text after matching"))
|
||||
return
|
||||
}
|
||||
HermesReachHandshake.validateMatched(text)?.let { message ->
|
||||
closeWithError(IOException(message))
|
||||
return
|
||||
}
|
||||
matched = true
|
||||
matchLatch.countDown()
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
if (!matched) {
|
||||
closeWithError(IOException("Hermes Reach sent bytes before matching"))
|
||||
return
|
||||
}
|
||||
if (bytes.size > REACH_MAX_FRAME_BYTES) {
|
||||
closeWithError(IOException("Hermes Reach frame exceeds 1 MiB"))
|
||||
return
|
||||
}
|
||||
if (!inbound.offer(bytes.toByteArray())) {
|
||||
closeWithError(IOException("Hermes Reach receive queue exceeded its safe limit"))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
webSocket.close(code, null)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
if (!matched) matchError = IOException("Hermes Reach closed before matching the host")
|
||||
closed = true
|
||||
inbound.close(matchError)
|
||||
matchLatch.countDown()
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
closeWithError(IOException("Hermes Reach connection failed", t))
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeWithError(error: IOException) {
|
||||
matchError = error
|
||||
closed = true
|
||||
webSocket?.cancel()
|
||||
inbound.close(error)
|
||||
matchLatch.countDown()
|
||||
}
|
||||
|
||||
override fun getInputStream(): InputStream {
|
||||
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
|
||||
inbound.readTimeoutMs = readTimeoutMs
|
||||
return inbound
|
||||
}
|
||||
|
||||
override fun getOutputStream(): OutputStream {
|
||||
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
|
||||
return outbound
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
webSocket?.close(1000, null)
|
||||
inbound.close(null)
|
||||
matchLatch.countDown()
|
||||
}
|
||||
|
||||
override fun isConnected(): Boolean = connected
|
||||
override fun isClosed(): Boolean = closed
|
||||
override fun getRemoteSocketAddress(): SocketAddress? = remote
|
||||
override fun getInetAddress(): InetAddress? = remote?.address
|
||||
override fun getPort(): Int = remote?.port ?: 0
|
||||
override fun setSoTimeout(timeout: Int) { readTimeoutMs = timeout }
|
||||
override fun getSoTimeout(): Int = readTimeoutMs
|
||||
override fun setTcpNoDelay(on: Boolean) = Unit
|
||||
override fun getTcpNoDelay(): Boolean = true
|
||||
override fun setKeepAlive(on: Boolean) = Unit
|
||||
override fun getKeepAlive(): Boolean = true
|
||||
override fun setReuseAddress(on: Boolean) = Unit
|
||||
override fun getReuseAddress(): Boolean = false
|
||||
}
|
||||
|
||||
internal class ReachInputStream : InputStream() {
|
||||
private val chunks = ArrayDeque<ByteArray>()
|
||||
private var offset = 0
|
||||
private var queuedBytes = 0
|
||||
private var terminalError: IOException? = null
|
||||
private var closed = false
|
||||
@Volatile var readTimeoutMs: Int = 0
|
||||
|
||||
@Synchronized
|
||||
fun offer(bytes: ByteArray): Boolean {
|
||||
if (closed) return false
|
||||
if (chunks.size >= REACH_MAX_QUEUED_FRAMES || queuedBytes + bytes.size > REACH_MAX_QUEUED_BYTES) {
|
||||
return false
|
||||
}
|
||||
chunks.addLast(bytes)
|
||||
queuedBytes += bytes.size
|
||||
(this as java.lang.Object).notifyAll()
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close(error: IOException?) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
terminalError = error
|
||||
(this as java.lang.Object).notifyAll()
|
||||
}
|
||||
|
||||
override fun read(): Int {
|
||||
val one = ByteArray(1)
|
||||
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun read(target: ByteArray, targetOffset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
val started = System.nanoTime()
|
||||
while (chunks.isEmpty() && !closed) {
|
||||
val waitMs = if (readTimeoutMs > 0) {
|
||||
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)
|
||||
(readTimeoutMs - elapsed).coerceAtLeast(0)
|
||||
} else 0L
|
||||
if (readTimeoutMs > 0 && waitMs == 0L) throw java.net.SocketTimeoutException("Hermes Reach read timed out")
|
||||
(this as java.lang.Object).wait(if (readTimeoutMs > 0) waitMs else 0L)
|
||||
}
|
||||
if (chunks.isEmpty()) {
|
||||
terminalError?.let { throw it }
|
||||
return -1
|
||||
}
|
||||
val chunk = chunks.first()
|
||||
val count = minOf(length, chunk.size - offset)
|
||||
chunk.copyInto(target, targetOffset, offset, offset + count)
|
||||
offset += count
|
||||
queuedBytes -= count
|
||||
if (offset == chunk.size) {
|
||||
chunks.remove(chunk)
|
||||
offset = 0
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
|
||||
private fun randomConnectionId(): String {
|
||||
val bytes = ByteArray(16).also(SecureRandom()::nextBytes)
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import com.hermesandroid.relay.data.isValidPinnedProxy
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import java.net.URI
|
||||
import java.security.KeyStore
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.CertificateException
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
import javax.net.ssl.X509TrustManager
|
||||
import javax.net.SocketFactory
|
||||
|
||||
/** Runtime endpoints exposed beneath one plugin-owned pinned-TLS origin. */
|
||||
data class PluginProxyRoutes(
|
||||
val authority: String,
|
||||
val host: String,
|
||||
val port: Int,
|
||||
val relayHttpUrl: String,
|
||||
val relayWebSocketUrl: String,
|
||||
val apiBaseUrl: String?,
|
||||
val dashboardBaseUrl: String?,
|
||||
val pinSha256: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Resolve and validate the pairing-advertised proxy contract. Invalid or
|
||||
* incomplete advertisements are never treated as secure routes.
|
||||
*/
|
||||
fun ProxyEndpoint.toPluginProxyRoutesOrNull(): PluginProxyRoutes? {
|
||||
if (!isValidPinnedProxy()) return null
|
||||
val base = url.trim().trimEnd('/')
|
||||
val uri = runCatching { URI(base) }.getOrNull() ?: return null
|
||||
if (!uri.scheme.equals("https", ignoreCase = true)) return null
|
||||
val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return null
|
||||
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
|
||||
val rawPath = uri.rawPath.orEmpty()
|
||||
if (rawPath.isNotEmpty() && rawPath != "/") return null
|
||||
val port = if (uri.port > 0) uri.port else 443
|
||||
val pin = pinSha256!!.trim()
|
||||
val authority = "$host:$port"
|
||||
val wsBase = "wss://${formatHost(host)}${if (port == 443) "" else ":$port"}$rawPath"
|
||||
.trimEnd('/')
|
||||
val surfaces = surfaces.map(String::lowercase).toSet()
|
||||
return PluginProxyRoutes(
|
||||
authority = authority,
|
||||
host = host,
|
||||
port = port,
|
||||
relayHttpUrl = "$base/relay",
|
||||
relayWebSocketUrl = "$wsBase/relay/ws",
|
||||
apiBaseUrl = "$base/api".takeIf { "api" in surfaces },
|
||||
dashboardBaseUrl = "$base/dashboard".takeIf { "dashboard" in surfaces },
|
||||
pinSha256 = pin,
|
||||
)
|
||||
}
|
||||
|
||||
fun EndpointCandidate.pluginProxyRoutesOrNull(): PluginProxyRoutes? =
|
||||
proxy?.toPluginProxyRoutesOrNull()
|
||||
|
||||
private fun formatHost(host: String): String = if (':' in host) "[$host]" else host
|
||||
|
||||
/**
|
||||
* Build a client that trusts the system normally, plus exactly the
|
||||
* pairing-advertised SPKI for this proxy. The authority guard keeps a pin
|
||||
* scoped to host *and port*; OkHttp's CertificatePinner alone is host-only.
|
||||
*/
|
||||
fun buildPluginProxyClient(
|
||||
baseBuilder: OkHttpClient.Builder,
|
||||
routes: PluginProxyRoutes,
|
||||
sessionTokenProvider: () -> String?,
|
||||
includeRelaySessionHeader: Boolean = true,
|
||||
rawSocketFactory: SocketFactory? = null,
|
||||
): OkHttpClient {
|
||||
val expectedHost = routes.host
|
||||
val expectedPort = routes.port
|
||||
val systemTrust = systemTrustManager()
|
||||
val pinnedTrust = PinnedOrSystemTrustManager(systemTrust, routes.pinSha256)
|
||||
val sslContext = SSLContext.getInstance("TLS").apply {
|
||||
init(null, arrayOf(pinnedTrust), SecureRandom())
|
||||
}
|
||||
|
||||
if (rawSocketFactory != null) baseBuilder.socketFactory(rawSocketFactory)
|
||||
return baseBuilder
|
||||
.sslSocketFactory(sslContext.socketFactory, pinnedTrust)
|
||||
.certificatePinner(
|
||||
CertificatePinner.Builder().add(expectedHost, routes.pinSha256).build(),
|
||||
)
|
||||
.addNetworkInterceptor(Interceptor { chain ->
|
||||
val requestUrl = chain.request().url
|
||||
if (!requestUrl.host.equals(expectedHost, ignoreCase = true) ||
|
||||
requestUrl.port != expectedPort
|
||||
) {
|
||||
throw java.io.IOException("Pinned proxy redirect left its paired authority")
|
||||
}
|
||||
val token = sessionTokenProvider().takeIf { includeRelaySessionHeader }
|
||||
?.takeIf { it.isNotBlank() }
|
||||
val request = if (token != null) {
|
||||
chain.request().newBuilder()
|
||||
.credentialHeader(
|
||||
"X-Hermes-Relay-Session",
|
||||
token,
|
||||
"Relay session credential",
|
||||
)
|
||||
.build()
|
||||
} else {
|
||||
chain.request()
|
||||
}
|
||||
chain.proceed(request)
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun systemTrustManager(): X509TrustManager {
|
||||
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
|
||||
factory.init(null as KeyStore?)
|
||||
return factory.trustManagers.filterIsInstance<X509TrustManager>().single()
|
||||
}
|
||||
|
||||
private class PinnedOrSystemTrustManager(
|
||||
private val system: X509TrustManager,
|
||||
private val expectedPin: String,
|
||||
) : X509TrustManager {
|
||||
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) =
|
||||
system.checkClientTrusted(chain, authType)
|
||||
|
||||
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
|
||||
val certificates = chain?.takeIf { it.isNotEmpty() }
|
||||
?: throw CertificateException("Proxy supplied no certificate chain")
|
||||
val systemAccepted = runCatching { system.checkServerTrusted(chain, authType) }.isSuccess
|
||||
if (systemAccepted) return
|
||||
|
||||
val leaf = certificates.first()
|
||||
leaf.checkValidity()
|
||||
val actual = "sha256/" + java.util.Base64.getEncoder().encodeToString(
|
||||
MessageDigest.getInstance("SHA-256").digest(leaf.publicKey.encoded),
|
||||
)
|
||||
if (!MessageDigest.isEqual(actual.toByteArray(), expectedPin.toByteArray())) {
|
||||
throw CertificateException("Plugin proxy certificate does not match the paired pin")
|
||||
}
|
||||
}
|
||||
|
||||
override fun getAcceptedIssuers(): Array<X509Certificate> = system.acceptedIssuers
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import kotlin.random.Random
|
||||
|
||||
/** Full-jitter retry delay in the inclusive range 0..[capMs]. */
|
||||
internal fun fullJitterDelayMs(
|
||||
capMs: Long,
|
||||
unit: Double = Random.nextDouble(),
|
||||
): Long {
|
||||
if (capMs <= 0L) return 0L
|
||||
val boundedUnit = unit.coerceIn(0.0, Math.nextDown(1.0))
|
||||
return (boundedUnit * (capMs + 1.0)).toLong().coerceAtMost(capMs)
|
||||
}
|
||||
@@ -90,12 +90,9 @@ class ChatHandler {
|
||||
// Fallback form (no relay): `MEDIA:/absolute/path` — relay wasn't
|
||||
// reachable when the tool fired, so we render an "unavailable"
|
||||
// placeholder instead of attempting a fetch.
|
||||
private val mediaRelayRegex = Regex("""MEDIA:hermes-relay://([A-Za-z0-9_-]+)""")
|
||||
// `/.+?` (not `/\S+`) so absolute paths containing spaces — e.g.
|
||||
// `MEDIA:/mnt/media/Coralee Adshade/undressher.jpg` — still match. The
|
||||
// trailing `\s*$` trims any trailing whitespace; non-greedy keeps the
|
||||
// capture to the path. OkHttp re-encodes the space for /media/by-path.
|
||||
private val mediaBarePathRegex = Regex("""^\s*MEDIA:(/.+?)\s*$""")
|
||||
private val mediaRelayPayloadRegex = Regex("""^hermes-relay://([A-Za-z0-9_-]+)$""")
|
||||
private val mediaMarkerPrefixRegex = Regex("MEDIA:")
|
||||
private val windowsAbsoluteMediaPathRegex = Regex("""^[A-Za-z]:[\\/].+""")
|
||||
// Rich card marker — single line, full JSON object payload.
|
||||
//
|
||||
// Agents emit:
|
||||
@@ -188,6 +185,7 @@ class ChatHandler {
|
||||
* post-stream finalize reconciliation pass.
|
||||
*/
|
||||
private var mediaLineBuffer = StringBuilder()
|
||||
private var mediaFenceDelimiter: String? = null
|
||||
private val dispatchedMediaMarkers = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
@@ -473,7 +471,12 @@ class ChatHandler {
|
||||
* across the history reconcile; idempotent on the proactive [messageId] so a
|
||||
* re-delivered push (e.g. an outbound-buffer flush) never double-posts.
|
||||
*/
|
||||
fun addAgentThreadMessage(text: String, messageId: String?, agentName: String?) {
|
||||
fun addAgentThreadMessage(
|
||||
text: String,
|
||||
messageId: String?,
|
||||
agentName: String?,
|
||||
arrivedWhileAway: Boolean = false,
|
||||
) {
|
||||
val id = messageId?.let { "proactive-$it" } ?: "proactive-${java.util.UUID.randomUUID()}"
|
||||
_messages.update { list ->
|
||||
if (messageId != null && list.any { it.id == id }) return@update list
|
||||
@@ -483,6 +486,7 @@ class ChatHandler {
|
||||
content = text,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
agentName = agentName,
|
||||
badges = if (arrivedWhileAway) listOf("While away") else emptyList(),
|
||||
clientOnly = true,
|
||||
)
|
||||
(list + msg).let { if (it.size > MAX_MESSAGES) it.drop(it.size - MAX_MESSAGES) else it }
|
||||
@@ -526,6 +530,42 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [messageId] can be addressed without downgrading a durable
|
||||
* transcript to an ordinal-only rewind. A wholly legacy transcript has no
|
||||
* row ids and remains compatible with older Gateways. Once any visible
|
||||
* user turn has a durable row id, the selected turn must have one too;
|
||||
* otherwise the caller must refresh instead of guessing by position.
|
||||
*/
|
||||
fun hasSafeGatewayRewindAddress(messageId: String): Boolean {
|
||||
val userTurns = _messages.value.filter { it.isGatewayRewindUser() }
|
||||
val target = userTurns.firstOrNull { it.matchesIdentity(messageId) } ?: return false
|
||||
return target.rowId != null || userTurns.none { it.rowId != null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebind visible user turns after Gateway rewrites a truncated durable
|
||||
* prefix. The response is positional in the same user-ordinal space used
|
||||
* for edit/regenerate. Missing entries clear cached ids so a later rewind
|
||||
* cannot accidentally send an archived pre-rewrite row id.
|
||||
*/
|
||||
fun rebindSurvivorUserRowIds(rowIds: List<Long?>) {
|
||||
var ordinal = 0
|
||||
_messages.update { messages ->
|
||||
messages.map { message ->
|
||||
if (!message.isGatewayRewindUser()) return@map message
|
||||
val rebound = rowIds.getOrNull(ordinal)
|
||||
ordinal += 1
|
||||
if (message.rowId == rebound) message else message.copy(rowId = rebound)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ChatMessage.isGatewayRewindUser(): Boolean =
|
||||
role == MessageRole.USER &&
|
||||
!id.startsWith("voice-intent-") &&
|
||||
!id.startsWith("steer-")
|
||||
|
||||
fun replaceMessageContent(messageId: String, content: String) {
|
||||
_messages.update { messages ->
|
||||
messages.map { message ->
|
||||
@@ -1176,12 +1216,14 @@ class ChatHandler {
|
||||
// Drop any pending line buffers / dedupe state so a fresh session
|
||||
// doesn't inherit leftovers from the previous one.
|
||||
mediaLineBuffer.clear()
|
||||
mediaFenceDelimiter = null
|
||||
dispatchedMediaMarkers.clear()
|
||||
annotationLineBuffer.clear()
|
||||
activeAnnotationTools.clear()
|
||||
cardLineBuffer.clear()
|
||||
dispatchedCardMarkers.clear()
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1497,6 +1539,8 @@ class ChatHandler {
|
||||
// this as the same visible row across the post-turn reload.
|
||||
prior.copy(
|
||||
id = messageId,
|
||||
rowId = item.resolvedRowId,
|
||||
reactions = item.reactions,
|
||||
role = role,
|
||||
content = cleanedContent,
|
||||
attachments = carriedAttachments,
|
||||
@@ -1527,6 +1571,8 @@ class ChatHandler {
|
||||
// nothing local to carry).
|
||||
ChatMessage(
|
||||
id = messageId,
|
||||
rowId = item.resolvedRowId,
|
||||
reactions = item.reactions,
|
||||
role = role,
|
||||
content = cleanedContent,
|
||||
attachments = carriedAttachments,
|
||||
@@ -1599,7 +1645,7 @@ class ChatHandler {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (relay, reload): token=${hit.token}")
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
@@ -1771,7 +1817,7 @@ class ChatHandler {
|
||||
for (line in text.lines()) {
|
||||
val t = line.trim()
|
||||
if (t.isEmpty()) continue
|
||||
if (mediaRelayRegex.containsMatchIn(t) || mediaBarePathRegex.containsMatchIn(t)) continue
|
||||
if (parseMediaMarkerLine(t).isNotEmpty()) continue
|
||||
if (PersistedImageReferenceParser.parse(t).paths.isNotEmpty()) continue
|
||||
if (cardMarkerRegex.containsMatchIn(t)) continue
|
||||
if (sb.isNotEmpty()) sb.append('\n')
|
||||
@@ -1788,6 +1834,51 @@ class ChatHandler {
|
||||
data class BarePath(val path: String) : MediaMarkerHit
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one marker-only line using upstream-compatible wrappers and
|
||||
* boundaries. Prose and malformed examples remain ordinary text; a whole
|
||||
* inline-code or emphasis wrapper is accepted, as are adjacent markers,
|
||||
* sentence-final punctuation, POSIX paths, and Windows absolute paths.
|
||||
*/
|
||||
private fun parseMediaMarkerLine(line: String): List<MediaMarkerHit> {
|
||||
val trimmed = line.trim()
|
||||
if (trimmed.isEmpty() || trimmed.startsWith("```") || trimmed.startsWith("~~~")) {
|
||||
return emptyList()
|
||||
}
|
||||
val starts = mediaMarkerPrefixRegex.findAll(trimmed).map { it.range.first }.toList()
|
||||
if (starts.isEmpty()) return emptyList()
|
||||
val prefix = trimmed.substring(0, starts.first())
|
||||
if (prefix.any { !it.isWhitespace() && it !in "`*_~" }) return emptyList()
|
||||
|
||||
val hits = ArrayList<MediaMarkerHit>(starts.size)
|
||||
for ((index, start) in starts.withIndex()) {
|
||||
val payloadStart = start + "MEDIA:".length
|
||||
val payloadEnd = starts.getOrNull(index + 1) ?: trimmed.length
|
||||
val payload = trimmed.substring(payloadStart, payloadEnd)
|
||||
.trim()
|
||||
.trimEnd { it in "`*_~.,;:)}]" }
|
||||
.trim()
|
||||
if (payload.isEmpty()) return emptyList()
|
||||
val relay = mediaRelayPayloadRegex.matchEntire(payload)
|
||||
when {
|
||||
relay != null -> hits += MediaMarkerHit.RelayToken(relay.groupValues[1])
|
||||
payload.startsWith("/") || windowsAbsoluteMediaPathRegex.matches(payload) ->
|
||||
hits += MediaMarkerHit.BarePath(payload)
|
||||
else -> return emptyList()
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
private fun fenceDelimiter(line: String): String? {
|
||||
val trimmed = line.trimStart()
|
||||
return when {
|
||||
trimmed.startsWith("```") -> "```"
|
||||
trimmed.startsWith("~~~") -> "~~~"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan loaded (non-streaming) message content line-by-line for media
|
||||
* markers, append hits to [out], and return the content with matched
|
||||
@@ -1800,24 +1891,20 @@ class ChatHandler {
|
||||
out: MutableList<Pair<String, MediaMarkerHit>>,
|
||||
): String {
|
||||
var cleaned = content
|
||||
var openFence: String? = null
|
||||
for (rawLine in content.lines()) {
|
||||
val trimmed = rawLine.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
|
||||
val relayMatch = mediaRelayRegex.find(trimmed)
|
||||
if (relayMatch != null) {
|
||||
out.add(messageId to MediaMarkerHit.RelayToken(relayMatch.groupValues[1]))
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
.replace("\n$rawLine", "")
|
||||
.replace("$rawLine\n", "")
|
||||
.replace(rawLine, "")
|
||||
val delimiter = fenceDelimiter(rawLine)
|
||||
if (delimiter != null) {
|
||||
openFence = if (openFence == delimiter) null else if (openFence == null) delimiter else openFence
|
||||
continue
|
||||
}
|
||||
if (openFence != null) continue
|
||||
|
||||
val bareMatch = mediaBarePathRegex.find(trimmed)
|
||||
if (bareMatch != null) {
|
||||
out.add(messageId to MediaMarkerHit.BarePath(bareMatch.groupValues[1]))
|
||||
val hits = parseMediaMarkerLine(trimmed)
|
||||
if (hits.isNotEmpty()) {
|
||||
hits.forEach { out.add(messageId to it) }
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
.replace("\n$rawLine", "")
|
||||
@@ -1984,6 +2071,11 @@ class ChatHandler {
|
||||
title = resolvedTitle,
|
||||
model = item.model,
|
||||
messageCount = item.messageCount ?: 0,
|
||||
inputTokens = item.inputTokens ?: 0,
|
||||
outputTokens = item.outputTokens ?: 0,
|
||||
actualCostUsd = item.actualCostUsd,
|
||||
estimatedCostUsd = item.estimatedCostUsd,
|
||||
isActive = item.isActive,
|
||||
updatedAt = activityAtMs,
|
||||
startedAt = startedAtMs,
|
||||
lastActivityAt = lastActivityAtMs,
|
||||
@@ -1995,6 +2087,13 @@ class ChatHandler {
|
||||
hasModelConfig = item.hasModelConfig,
|
||||
pinned = item.pinned,
|
||||
archived = item.archived,
|
||||
workingDirectory = item.cwd,
|
||||
gitBranch = item.gitBranch,
|
||||
gitRepoRoot = item.gitRepoRoot,
|
||||
pullRequestNumber = item.pullRequest?.number,
|
||||
pullRequestUrl = item.pullRequest?.url,
|
||||
pullRequestState = item.pullRequest?.state,
|
||||
pullRequestDraft = item.pullRequest?.draft == true,
|
||||
)
|
||||
}.sortedByDescending { it.activityTimestamp }
|
||||
// Preserve the active session's optimistic row when the server list
|
||||
@@ -2265,6 +2364,18 @@ class ChatHandler {
|
||||
val trimmed = line.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
|
||||
fenceDelimiter(line)?.let { delimiter ->
|
||||
mediaFenceDelimiter = if (mediaFenceDelimiter == delimiter) {
|
||||
null
|
||||
} else if (mediaFenceDelimiter == null) {
|
||||
delimiter
|
||||
} else {
|
||||
mediaFenceDelimiter
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (mediaFenceDelimiter != null) continue
|
||||
|
||||
if (tryDispatchMediaMarker(messageId, trimmed)) {
|
||||
stripLineFromContent(messageId, trimmed)
|
||||
}
|
||||
@@ -2394,29 +2505,26 @@ class ChatHandler {
|
||||
* Returns true when a marker was matched so the caller can strip the line.
|
||||
*/
|
||||
private fun tryDispatchMediaMarker(messageId: String, line: String): Boolean {
|
||||
val relayMatch = mediaRelayRegex.find(line)
|
||||
if (relayMatch != null) {
|
||||
val token = relayMatch.groupValues[1]
|
||||
val dedupeKey = "$messageId:relay:$token"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (relay): token=$token")
|
||||
onMediaAttachmentRequested(messageId, token)
|
||||
val hits = parseMediaMarkerLine(line)
|
||||
for (hit in hits) {
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker accepted from Relay stream")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
val bareMatch = mediaBarePathRegex.find(line)
|
||||
if (bareMatch != null) {
|
||||
val path = bareMatch.groupValues[1]
|
||||
val dedupeKey = "$messageId:bare:$path"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path, unavailable): $path")
|
||||
onMediaBarePathRequested(messageId, path)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
return hits.isNotEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2555,10 +2663,11 @@ class ChatHandler {
|
||||
if (mediaLineBuffer.isNotEmpty()) {
|
||||
val remaining = mediaLineBuffer.toString().trim()
|
||||
mediaLineBuffer.clear()
|
||||
if (remaining.isNotEmpty() && tryDispatchMediaMarker(messageId, remaining)) {
|
||||
if (mediaFenceDelimiter == null && remaining.isNotEmpty() && tryDispatchMediaMarker(messageId, remaining)) {
|
||||
stripLineFromContent(messageId, remaining)
|
||||
}
|
||||
}
|
||||
mediaFenceDelimiter = null
|
||||
|
||||
// Post-stream reconciliation: re-scan the final content for markers
|
||||
// that raced with stripLineFromContent during streaming.
|
||||
@@ -2567,12 +2676,16 @@ class ChatHandler {
|
||||
if (!msg.matchesIdentity(messageId) || msg.role != MessageRole.ASSISTANT) return@map msg
|
||||
var cleaned = msg.content
|
||||
var changed = false
|
||||
var openFence: String? = null
|
||||
for (rawLine in msg.content.lines()) {
|
||||
val trimmed = rawLine.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
if (mediaRelayRegex.containsMatchIn(trimmed) ||
|
||||
mediaBarePathRegex.containsMatchIn(trimmed)
|
||||
) {
|
||||
val delimiter = fenceDelimiter(rawLine)
|
||||
if (delimiter != null) {
|
||||
openFence = if (openFence == delimiter) null else if (openFence == null) delimiter else openFence
|
||||
continue
|
||||
}
|
||||
if (openFence == null && parseMediaMarkerLine(trimmed).isNotEmpty()) {
|
||||
tryDispatchMediaMarker(messageId, trimmed)
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
@@ -2903,6 +3016,7 @@ class ChatHandler {
|
||||
* [onStreamComplete] / [clearMessages].
|
||||
*/
|
||||
private val subagentLabels = mutableMapOf<Int, String>()
|
||||
private val subagentIds = mutableMapOf<Int, String>()
|
||||
|
||||
/**
|
||||
* Apply one gateway `subagent.*` lifecycle event to the streaming
|
||||
@@ -2918,6 +3032,9 @@ class ChatHandler {
|
||||
when (event.phase) {
|
||||
GatewaySubagentEvent.Phase.START -> {
|
||||
if (label != null) subagentLabels[event.taskIndex] = label
|
||||
event.subagentId?.takeIf(String::isNotBlank)?.let {
|
||||
subagentIds[event.taskIndex] = it
|
||||
}
|
||||
}
|
||||
|
||||
GatewaySubagentEvent.Phase.TOOL -> {
|
||||
@@ -2932,6 +3049,8 @@ class ChatHandler {
|
||||
isComplete = false,
|
||||
taskIndex = event.taskIndex,
|
||||
taskLabel = laneLabel,
|
||||
subagentId = event.subagentId?.takeIf(String::isNotBlank)
|
||||
?: subagentIds[event.taskIndex],
|
||||
)
|
||||
_messages.update { messages ->
|
||||
val target = messages.findLast {
|
||||
@@ -2971,6 +3090,7 @@ class ChatHandler {
|
||||
// "interrupted" lanes never finished — not a success either.
|
||||
val failed = event.status == "failed" || event.status == "interrupted"
|
||||
val laneLabel = subagentLabels.remove(event.taskIndex) ?: label
|
||||
val subagentId = subagentIds.remove(event.taskIndex) ?: event.subagentId
|
||||
val summaryId = "subagent-${event.taskIndex}-${syntheticToolSeq++}"
|
||||
_messages.update { messages ->
|
||||
messages.map { msg ->
|
||||
@@ -3003,6 +3123,7 @@ class ChatHandler {
|
||||
completedAt = System.currentTimeMillis(),
|
||||
taskIndex = event.taskIndex,
|
||||
taskLabel = laneLabel,
|
||||
subagentId = subagentId,
|
||||
)
|
||||
}
|
||||
msg.copy(toolCalls = withSummary)
|
||||
@@ -3224,6 +3345,7 @@ class ChatHandler {
|
||||
.filterNot { msg ->
|
||||
msg.matchesIdentity(messageId) &&
|
||||
msg.role == MessageRole.ASSISTANT &&
|
||||
msg.badges.isEmpty() &&
|
||||
msg.toolCalls.isEmpty() &&
|
||||
msg.backgroundTask == null &&
|
||||
msg.thinkingContent.isBlank() &&
|
||||
@@ -3260,6 +3382,7 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
fun onStreamError(message: String) {
|
||||
@@ -3289,6 +3412,7 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
fun onThinkingDelta(messageId: String, delta: String) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
/**
|
||||
* User-reviewed input for upstream `cron.manage` creation.
|
||||
*
|
||||
* Repeat is intentionally bounded on the client. Upstream treats zero and
|
||||
* negative values as an unlimited schedule, which is unsafe when the user
|
||||
* explicitly chose a finite run count.
|
||||
*/
|
||||
data class CronCreationDraft(
|
||||
val name: String,
|
||||
val schedule: String,
|
||||
val prompt: String,
|
||||
val repeat: Int? = null,
|
||||
val profile: String? = null,
|
||||
) {
|
||||
fun validated(): Result<CronCreationDraft> = runCatching {
|
||||
val cleanName = name.trim()
|
||||
val cleanSchedule = schedule.trim()
|
||||
val cleanPrompt = prompt.trim()
|
||||
require(cleanName.isNotEmpty()) { "Schedule name is required" }
|
||||
require(cleanSchedule.isNotEmpty()) { "Schedule is required" }
|
||||
require(cleanPrompt.isNotEmpty()) { "Task instructions are required" }
|
||||
require(repeat == null || repeat in MIN_REPEAT..MAX_REPEAT) {
|
||||
"Run count must be between $MIN_REPEAT and $MAX_REPEAT"
|
||||
}
|
||||
copy(
|
||||
name = cleanName,
|
||||
schedule = cleanSchedule,
|
||||
prompt = cleanPrompt,
|
||||
profile = profile?.trim()?.takeIf(String::isNotEmpty),
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MIN_REPEAT = 1
|
||||
const val MAX_REPEAT = 999
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse an optional finite-count field without ever coercing invalid input to unlimited. */
|
||||
internal fun parseFiniteRepeat(value: String): Result<Int?> = runCatching {
|
||||
val clean = value.trim()
|
||||
if (clean.isEmpty()) return@runCatching null
|
||||
val parsed = clean.toIntOrNull() ?: throw IllegalArgumentException("Run count must be a whole number")
|
||||
require(parsed in CronCreationDraft.MIN_REPEAT..CronCreationDraft.MAX_REPEAT) {
|
||||
"Run count must be between ${CronCreationDraft.MIN_REPEAT} and ${CronCreationDraft.MAX_REPEAT}"
|
||||
}
|
||||
parsed
|
||||
}
|
||||
+509
-6
@@ -7,9 +7,12 @@ import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPullRequest
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPullRequestScanResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPruneFilters
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPrunePreview
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPruneResult
|
||||
import com.hermesandroid.relay.network.upstream.models.RepositoryPullRequestListResponse
|
||||
import com.hermesandroid.relay.auth.SecureStoreCache
|
||||
import com.hermesandroid.relay.auth.SessionTokenStore
|
||||
import com.hermesandroid.relay.auth.buildRawTokenStore
|
||||
@@ -35,13 +38,18 @@ import okhttp3.CookieJar
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
import okio.BufferedSink
|
||||
|
||||
// Status/session/provider snapshots are @Serializable so the Manage tab's
|
||||
// disk cache (DashboardManageDiskCache) can persist Loaded entries verbatim.
|
||||
@@ -58,6 +66,29 @@ data class DashboardStatus(
|
||||
@SerialName("gateway_mode") val gatewayMode: String? = null,
|
||||
val gateways: List<DashboardGatewayTopology> = emptyList(),
|
||||
val componentHealth: DashboardComponentHealthRollup = DashboardComponentHealthRollup(),
|
||||
val memory: DashboardMemoryStatus? = null,
|
||||
val disk: DashboardDiskStatus? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DashboardMemoryStatus(
|
||||
val pressure: String,
|
||||
@SerialName("gateway_rss_mb") val gatewayRssMb: Int? = null,
|
||||
@SerialName("system_total_mb") val systemTotalMb: Int? = null,
|
||||
@SerialName("system_available_mb") val systemAvailableMb: Int? = null,
|
||||
@SerialName("swap_used_mb") val swapUsedMb: Int? = null,
|
||||
@SerialName("sampled_at") val sampledAt: String? = null,
|
||||
@SerialName("last_boot_unclean") val lastBootUnclean: Boolean = false,
|
||||
@SerialName("last_boot_suspected_oom") val lastBootSuspectedOom: Boolean = false,
|
||||
@SerialName("boot_id") val bootId: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DashboardDiskStatus(
|
||||
val pressure: String,
|
||||
@SerialName("total_mb") val totalMb: Int? = null,
|
||||
@SerialName("free_mb") val freeMb: Int? = null,
|
||||
@SerialName("used_percent") val usedPercent: Double? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -67,6 +98,23 @@ data class DashboardGatewayTopology(
|
||||
@SerialName("served_profiles") val servedProfiles: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Return only profiles the launch gateway positively reports as served.
|
||||
*
|
||||
* `/api/status.profiles` is the installed-profile inventory. Selective
|
||||
* multiplex serving can exclude an installed profile, so that list must never
|
||||
* authorize construction of a `/p/<profile>` API fallback route.
|
||||
*/
|
||||
internal fun DashboardStatus.multiplexServedProfiles(): List<String> {
|
||||
if (!gatewayMode.equals("multiplex", ignoreCase = true)) return emptyList()
|
||||
return gateways.firstOrNull { it.profile.equals("default", ignoreCase = true) }
|
||||
?.servedProfiles
|
||||
.orEmpty()
|
||||
.map(String::trim)
|
||||
.filter(String::isNotBlank)
|
||||
.distinct()
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class DashboardComponentHealthRollup(
|
||||
val supported: Boolean = false,
|
||||
@@ -173,6 +221,71 @@ data class DashboardCustomEndpointValidation(
|
||||
val models: List<String>,
|
||||
)
|
||||
|
||||
internal class BoundedStreamRequestBody(
|
||||
private val declaredLength: Long?,
|
||||
private val limitBytes: Long,
|
||||
private val openStream: () -> InputStream,
|
||||
) : RequestBody() {
|
||||
init {
|
||||
require(limitBytes > 0)
|
||||
require(declaredLength == null || declaredLength >= 0)
|
||||
require(declaredLength == null || declaredLength <= limitBytes) {
|
||||
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit."
|
||||
}
|
||||
}
|
||||
|
||||
override fun contentType() = "application/zip".toMediaType()
|
||||
|
||||
override fun contentLength(): Long = declaredLength ?: -1L
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
openStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var written = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > limitBytes) {
|
||||
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit.")
|
||||
}
|
||||
sink.write(buffer, 0, read)
|
||||
}
|
||||
if (declaredLength != null && written != declaredLength) {
|
||||
throw IOException("Backup archive changed while it was being read.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun copyBounded(
|
||||
input: InputStream,
|
||||
output: OutputStream,
|
||||
declaredLength: Long?,
|
||||
limitBytes: Long,
|
||||
): Long {
|
||||
require(limitBytes > 0)
|
||||
require(declaredLength == null || declaredLength >= 0)
|
||||
require(declaredLength == null || declaredLength <= limitBytes) {
|
||||
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit."
|
||||
}
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var written = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > limitBytes) {
|
||||
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit.")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
if (declaredLength != null && written != declaredLength) {
|
||||
throw IOException("Backup archive changed while it was being downloaded.")
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/** One entry from `GET /api/audio/elevenlabs/voices` — non-secret voice metadata. */
|
||||
data class ElevenLabsVoice(
|
||||
val voiceId: String,
|
||||
@@ -206,8 +319,14 @@ class DashboardApiClient(
|
||||
isLenient = true
|
||||
coerceInputValues = true
|
||||
},
|
||||
private val nowMillis: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
private val baseUrl: String = baseUrl.trim().trimEnd('/')
|
||||
private val sessionPrScanLock = Any()
|
||||
private val sessionPrScannedAt = mutableMapOf<String, Long>()
|
||||
private val sessionPrScanWasTerminal = mutableMapOf<String, Boolean>()
|
||||
private val sessionPullRequests = mutableMapOf<String, SessionPullRequest>()
|
||||
private var sessionPrScanSupported: Boolean? = null
|
||||
|
||||
/**
|
||||
* Resolve a request URL without ever throwing. okhttp's
|
||||
@@ -500,6 +619,7 @@ class DashboardApiClient(
|
||||
name: String,
|
||||
cloneFromDefault: Boolean = true,
|
||||
description: String? = null,
|
||||
mcpServers: List<String> = emptyList(),
|
||||
): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/profiles",
|
||||
@@ -507,9 +627,167 @@ class DashboardApiClient(
|
||||
put("name", name)
|
||||
put("clone_from_default", cloneFromDefault)
|
||||
if (!description.isNullOrBlank()) put("description", description)
|
||||
if (mcpServers.isNotEmpty()) {
|
||||
put("mcp_servers", JsonArray(mcpServers.map(::JsonPrimitive)))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/** Create a host-owned Hermes backup, distinct from Android settings export. */
|
||||
suspend fun createServerBackup(): Result<JsonObject> =
|
||||
postJsonObject("/api/ops/backup")
|
||||
|
||||
/** Download only archives created inside upstream's guarded dashboard backup directory. */
|
||||
suspend fun downloadServerBackup(
|
||||
archive: String,
|
||||
openOutput: () -> OutputStream,
|
||||
): Result<String> = download(
|
||||
path = "/api/ops/backup/download?archive=${queryValue(archive)}",
|
||||
operation = "Hermes backup",
|
||||
openOutput = openOutput,
|
||||
)
|
||||
|
||||
/** Import a server-local archive path after the user confirms the destructive restore. */
|
||||
suspend fun importServerBackup(archive: String): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/ops/import",
|
||||
payload = buildJsonObject { put("archive", archive) },
|
||||
)
|
||||
|
||||
/** Upload an Android-selected zip to upstream's guarded staging directory and start import. */
|
||||
suspend fun uploadServerBackup(
|
||||
filename: String,
|
||||
contentLength: Long?,
|
||||
openStream: () -> InputStream,
|
||||
force: Boolean = false,
|
||||
): Result<JsonObject> = withContext(Dispatchers.IO) {
|
||||
val path = "/api/ops/import-upload"
|
||||
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
|
||||
val body = MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("force", force.toString())
|
||||
.addFormDataPart(
|
||||
"file",
|
||||
filename.ifBlank { "hermes-backup.zip" },
|
||||
runCatching {
|
||||
BoundedStreamRequestBody(contentLength, MAX_BACKUP_TRANSFER_BYTES, openStream)
|
||||
}.getOrElse { return@withContext Result.failure(it) },
|
||||
)
|
||||
.build()
|
||||
executeJson(Request.Builder().url(httpUrl).post(body).build(), path)
|
||||
}
|
||||
|
||||
suspend fun getLearningNode(id: String, profile: String? = null): Result<JsonObject> =
|
||||
getJsonObject("/api/learning/node?id=${queryValue(id)}${profileQuerySuffix(profile)}")
|
||||
|
||||
suspend fun updateLearningNode(
|
||||
id: String,
|
||||
content: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/learning/node",
|
||||
payload = buildJsonObject {
|
||||
put("id", id)
|
||||
put("content", content)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun deleteLearningNode(id: String, profile: String? = null): Result<JsonObject> =
|
||||
deleteJsonObjectWithBody(
|
||||
path = "/api/learning/node",
|
||||
payload = buildJsonObject {
|
||||
put("id", id)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun selectMemoryProvider(provider: String): Result<JsonObject> =
|
||||
putJsonObject(
|
||||
path = "/api/memory/provider",
|
||||
payload = buildJsonObject { put("provider", provider) },
|
||||
)
|
||||
|
||||
/** Activate an already-configured provider inside the selected upstream profile. */
|
||||
suspend fun activateMemoryProvider(provider: String, profile: String? = null): Result<JsonObject> =
|
||||
updateMemoryProviderConfig(provider, JsonObject(emptyMap()), profile)
|
||||
|
||||
suspend fun getMemoryProviderConfig(
|
||||
provider: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = getJsonObject(
|
||||
"/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun updateMemoryProviderConfig(
|
||||
provider: String,
|
||||
values: JsonObject,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
|
||||
payload = buildJsonObject { put("values", values) },
|
||||
)
|
||||
|
||||
suspend fun setupMemoryProvider(provider: String): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/memory/providers/${pathSegment(provider)}/setup",
|
||||
// Dependency installation is host-global upstream. Do not submit
|
||||
// profile-owned values through this unscoped route.
|
||||
payload = buildJsonObject { put("values", JsonObject(emptyMap())) },
|
||||
)
|
||||
|
||||
suspend fun startWhatsAppOnboarding(
|
||||
mode: String,
|
||||
allowedUsers: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = postJsonObject(
|
||||
path = "/api/messaging/whatsapp/onboarding/start",
|
||||
payload = buildJsonObject {
|
||||
put("mode", mode)
|
||||
put("allowed_users", allowedUsers)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun getWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
|
||||
getJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
|
||||
|
||||
suspend fun applyWhatsAppOnboarding(
|
||||
pairingId: String,
|
||||
mode: String,
|
||||
allowedUsers: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = postJsonObject(
|
||||
path = "/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}/apply",
|
||||
payload = buildJsonObject {
|
||||
put("mode", mode)
|
||||
put("allowed_users", allowedUsers)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun cancelWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
|
||||
deleteJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
|
||||
|
||||
suspend fun setMessagingPlatformEnabled(
|
||||
platform: String,
|
||||
enabled: Boolean,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/messaging/platforms/${pathSegment(platform)}${profileQuery(profile)}",
|
||||
payload = buildJsonObject {
|
||||
put("enabled", enabled)
|
||||
put("env", JsonObject(emptyMap()))
|
||||
put("clear_env", JsonArray(emptyList()))
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun testMessagingPlatform(platform: String, profile: String? = null): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
"/api/messaging/platforms/${pathSegment(platform)}/test${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun setProfileDescription(name: String, description: String): Result<JsonObject> =
|
||||
putJsonObject(
|
||||
path = "/api/profiles/${pathSegment(name)}/description",
|
||||
@@ -605,15 +883,16 @@ class DashboardApiClient(
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getCustomEndpoints(): Result<DashboardCustomEndpoints> =
|
||||
getJsonObject("/api/providers/custom-endpoints")
|
||||
suspend fun getCustomEndpoints(profile: String? = null): Result<DashboardCustomEndpoints> =
|
||||
getJsonObject("/api/providers/custom-endpoints${profileQuery(profile)}")
|
||||
.mapCatching(::parseCustomEndpoints)
|
||||
|
||||
suspend fun saveCustomEndpoint(
|
||||
draft: DashboardCustomEndpointDraft,
|
||||
profile: String? = null,
|
||||
): Result<DashboardCustomEndpoints> =
|
||||
postJsonObject(
|
||||
"/api/providers/custom-endpoints",
|
||||
"/api/providers/custom-endpoints${profileQuery(profile)}",
|
||||
customEndpointPayload(draft),
|
||||
).mapCatching(::parseCustomEndpoints)
|
||||
|
||||
@@ -634,13 +913,19 @@ class DashboardApiClient(
|
||||
|
||||
suspend fun activateCustomEndpoint(
|
||||
id: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> =
|
||||
postJsonObject("/api/providers/custom-endpoints/${pathSegment(id)}/activate")
|
||||
postJsonObject(
|
||||
"/api/providers/custom-endpoints/${pathSegment(id)}/activate${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun deleteCustomEndpoint(
|
||||
id: String,
|
||||
profile: String? = null,
|
||||
): Result<DashboardCustomEndpoints> =
|
||||
deleteJsonObject("/api/providers/custom-endpoints/${pathSegment(id)}")
|
||||
deleteJsonObject(
|
||||
"/api/providers/custom-endpoints/${pathSegment(id)}${profileQuery(profile)}",
|
||||
)
|
||||
.mapCatching(::parseCustomEndpoints)
|
||||
|
||||
suspend fun installMcpCatalogEntry(
|
||||
@@ -749,9 +1034,157 @@ class DashboardApiClient(
|
||||
pageSessions.forEach { sessions.putIfAbsent(it.id, it) }
|
||||
if (pageSessions.size < page.limit) break
|
||||
}
|
||||
Result.success(sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)))
|
||||
Result.success(
|
||||
enrichSessionWorkState(
|
||||
sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)),
|
||||
fixedProfile = profile?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: DEFAULT_SESSION_PROFILE_SCOPE,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the bounded, authoritative session window across every profile.
|
||||
* Every usable row must retain its owning profile; rows without one are
|
||||
* skipped rather than risking a cross-profile transcript or mutation.
|
||||
*/
|
||||
suspend fun listAllProfileSessions(
|
||||
limit: Int = SESSION_LIST_WINDOW_LIMIT,
|
||||
): Result<List<SessionItem>> = withContext(Dispatchers.IO) {
|
||||
val boundedLimit = limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)
|
||||
val result = getJson(
|
||||
"/api/profiles/sessions?limit=$boundedLimit&offset=0&order=recent" +
|
||||
"&min_messages=1&archived=include&profile=all",
|
||||
).mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(SessionListResponse.serializer(), root)
|
||||
(parsed.sessions ?: parsed.items ?: parsed.data ?: emptyList())
|
||||
.filter { it.id.isNotBlank() && !it.profile.isNullOrBlank() }
|
||||
.distinctBy { "${it.profile}:${it.id}" }
|
||||
.take(boundedLimit)
|
||||
}
|
||||
if (result.isFailure) return@withContext result
|
||||
Result.success(enrichSessionWorkState(result.getOrThrow(), fixedProfile = null))
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach the PR a coding session created using the current upstream
|
||||
* transcript-backed endpoint. Repository and branch already arrive on the
|
||||
* list row. Missing/older endpoints are deliberately ignored, leaving the
|
||||
* original rows intact. Active misses retry on a bounded cadence; terminal
|
||||
* rows get one final scan and resolved associations remain cached.
|
||||
*/
|
||||
private suspend fun enrichSessionWorkState(
|
||||
sessions: List<SessionItem>,
|
||||
fixedProfile: String?,
|
||||
): List<SessionItem> {
|
||||
val candidates = sessions.filter {
|
||||
it.id.isNotBlank() &&
|
||||
(!it.gitRepoRoot.isNullOrBlank() || !it.gitBranch.isNullOrBlank() || !it.cwd.isNullOrBlank())
|
||||
}
|
||||
val duplicateIds = if (fixedProfile == null) {
|
||||
candidates.groupingBy { it.id }.eachCount().filterValues { it > 1 }.keys
|
||||
} else {
|
||||
emptySet()
|
||||
}
|
||||
val now = nowMillis()
|
||||
val pending = synchronized(sessionPrScanLock) {
|
||||
candidates.filter { session ->
|
||||
if (session.id in duplicateIds) return@filter false
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
val scannedAt = sessionPrScannedAt[key]
|
||||
val resolved = sessionPullRequests[key] != null
|
||||
!resolved && when {
|
||||
scannedAt == null -> true
|
||||
session.endedAt != null -> sessionPrScanWasTerminal[key] != true
|
||||
else -> now - scannedAt >= ACTIVE_SESSION_PR_MISS_TTL_MILLIS
|
||||
}
|
||||
}
|
||||
}
|
||||
val pendingIds = pending.map { it.id }.distinct()
|
||||
if (pendingIds.isNotEmpty()) {
|
||||
val payload = buildJsonObject {
|
||||
put("ids", JsonArray(pendingIds.map { JsonPrimitive(it) }))
|
||||
}
|
||||
val scan = postJsonObject("/api/profiles/sessions/pull-requests", payload)
|
||||
.mapCatching { root ->
|
||||
json.decodeFromJsonElement(SessionPullRequestScanResponse.serializer(), root)
|
||||
}
|
||||
synchronized(sessionPrScanLock) {
|
||||
// A legacy 404 is a compatibility outcome, not a session-list failure.
|
||||
// Avoid hammering an unsupported host on every drawer refresh.
|
||||
if (scan.isSuccess || sessionPrScanSupported == null) {
|
||||
sessionPrScanSupported = scan.isSuccess
|
||||
}
|
||||
pending.forEach { session ->
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
sessionPrScannedAt[key] = now
|
||||
sessionPrScanWasTerminal[key] = session.endedAt != null
|
||||
scan.getOrNull()?.pullRequests?.get(session.id)?.takeIf {
|
||||
it.number > 0 && it.url.isNotBlank()
|
||||
}?.let { pullRequest ->
|
||||
sessionPullRequests[key] = pullRequest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
refreshPullRequestStates(candidates, fixedProfile)
|
||||
val pullRequests = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
|
||||
return sessions.map { session ->
|
||||
session.copy(pullRequest = pullRequests[sessionWorkKey(session, fixedProfile)])
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh current PR lifecycle state using upstream's repo-scoped GitHub view. */
|
||||
private suspend fun refreshPullRequestStates(
|
||||
sessions: List<SessionItem>,
|
||||
fixedProfile: String?,
|
||||
) {
|
||||
if (synchronized(sessionPrScanLock) { sessionPrScanSupported } != true) return
|
||||
val known = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
|
||||
sessions.groupBy { (it.gitRepoRoot ?: it.cwd).orEmpty().trim() }
|
||||
.filterKeys { it.isNotBlank() }
|
||||
.forEach { (path, repositorySessions) ->
|
||||
val branches = repositorySessions.mapNotNull { it.gitBranch?.trim() }
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
val numbers = repositorySessions.mapNotNull {
|
||||
known[sessionWorkKey(it, fixedProfile)]?.number
|
||||
}
|
||||
.filter { it > 0 }
|
||||
.distinct()
|
||||
if (branches.isEmpty() && numbers.isEmpty()) return@forEach
|
||||
val payload = buildJsonObject {
|
||||
put("path", path)
|
||||
put("branches", JsonArray(branches.map { JsonPrimitive(it) }))
|
||||
put("numbers", JsonArray(numbers.map { JsonPrimitive(it) }))
|
||||
}
|
||||
val response = postJsonObject("/api/git/review/pr-list", payload)
|
||||
.mapCatching { root ->
|
||||
json.decodeFromJsonElement(RepositoryPullRequestListResponse.serializer(), root)
|
||||
}
|
||||
.getOrNull()
|
||||
?: return@forEach
|
||||
if (!response.ghReady) return@forEach
|
||||
synchronized(sessionPrScanLock) {
|
||||
repositorySessions.forEach { session ->
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
val recovered = sessionPullRequests[key]
|
||||
val current = response.prs.firstOrNull { pr ->
|
||||
recovered != null && pr.number == recovered.number
|
||||
} ?: response.prs.firstOrNull { pr ->
|
||||
!session.gitBranch.isNullOrBlank() && pr.branch == session.gitBranch
|
||||
}
|
||||
if (current != null && current.number > 0 && current.url.isNotBlank()) {
|
||||
sessionPullRequests[key] = current
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sessionWorkKey(session: SessionItem, fixedProfile: String?): String =
|
||||
"${fixedProfile ?: session.profile.orEmpty()}\u0000${session.id}"
|
||||
|
||||
/**
|
||||
* A session's message history, scoped to its owning profile via the dashboard
|
||||
* `GET /api/sessions/{id}/messages?profile=`. Required twin of [listSessions]:
|
||||
@@ -1074,8 +1507,44 @@ class DashboardApiClient(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun download(
|
||||
path: String,
|
||||
operation: String,
|
||||
openOutput: () -> OutputStream,
|
||||
): Result<String> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder().url(httpUrl).get().build()
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return@withContext Result.failure(apiFailure(response, operation))
|
||||
val disposition = response.header("Content-Disposition").orEmpty()
|
||||
val filename = Regex("filename=\\\"?([^\\\";]+)").find(disposition)?.groupValues?.get(1)
|
||||
?: "hermes-backup.zip"
|
||||
val body = response.body
|
||||
val declaredLength = body.contentLength().takeIf { it >= 0 }
|
||||
if (declaredLength != null && declaredLength > MAX_BACKUP_TRANSFER_BYTES) {
|
||||
throw IOException("Backup archive exceeds the ${MAX_BACKUP_TRANSFER_BYTES / (1024 * 1024)} MB download limit.")
|
||||
}
|
||||
openOutput().use { output ->
|
||||
body.byteStream().use { input ->
|
||||
copyBounded(input, output, declaredLength, MAX_BACKUP_TRANSFER_BYTES)
|
||||
}
|
||||
}
|
||||
Result.success(filename)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val JSON_MEDIA = "application/json; charset=utf-8".toMediaType()
|
||||
private const val DEFAULT_SESSION_PROFILE_SCOPE = "__dashboard_default__"
|
||||
internal const val ACTIVE_SESSION_PR_MISS_TTL_MILLIS = 60_000L
|
||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||
// client-side avoids uploading a body the Dashboard will reject.
|
||||
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
|
||||
|
||||
fun pathSegment(value: String): String =
|
||||
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
@@ -1133,6 +1602,11 @@ class DashboardApiClient(
|
||||
return if (trimmed.isBlank()) "" else "?profile=${pathSegment(trimmed)}"
|
||||
}
|
||||
|
||||
private fun profileQuerySuffix(profile: String?): String {
|
||||
val trimmed = profile?.trim().orEmpty()
|
||||
return if (trimmed.isBlank()) "" else "&profile=${queryValue(trimmed)}"
|
||||
}
|
||||
|
||||
private fun profileLimitQuery(profile: String?, limit: Int): String {
|
||||
val params = buildList {
|
||||
val trimmed = profile?.trim().orEmpty()
|
||||
@@ -1260,6 +1734,35 @@ class DashboardApiClient(
|
||||
gatewayMode = root.stringField("gateway_mode"),
|
||||
gateways = gateways,
|
||||
componentHealth = parseComponentHealth(root),
|
||||
memory = parseMemoryStatus(root["memory"] as? JsonObject),
|
||||
disk = parseDiskStatus(root["disk"] as? JsonObject),
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseMemoryStatus(obj: JsonObject?): DashboardMemoryStatus? {
|
||||
obj ?: return null
|
||||
val pressure = obj.stringField("pressure")?.lowercase() ?: return null
|
||||
return DashboardMemoryStatus(
|
||||
pressure = pressure,
|
||||
gatewayRssMb = obj.intField("gateway_rss_mb"),
|
||||
systemTotalMb = obj.intField("system_total_mb"),
|
||||
systemAvailableMb = obj.intField("system_available_mb"),
|
||||
swapUsedMb = obj.intField("swap_used_mb"),
|
||||
sampledAt = obj.stringField("sampled_at"),
|
||||
lastBootUnclean = obj.booleanField("last_boot_unclean") ?: false,
|
||||
lastBootSuspectedOom = obj.booleanField("last_boot_suspected_oom") ?: false,
|
||||
bootId = obj.stringField("boot_id"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseDiskStatus(obj: JsonObject?): DashboardDiskStatus? {
|
||||
obj ?: return null
|
||||
val pressure = obj.stringField("pressure")?.lowercase() ?: return null
|
||||
return DashboardDiskStatus(
|
||||
pressure = pressure,
|
||||
totalMb = obj.intField("total_mb"),
|
||||
freeMb = obj.intField("free_mb"),
|
||||
usedPercent = (obj["used_percent"] as? JsonPrimitive)?.contentOrNull?.toDoubleOrNull(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+1038
-48
File diff suppressed because it is too large
Load Diff
+42
-13
@@ -207,7 +207,11 @@ class GatewayEventMapper(
|
||||
}
|
||||
else -> syntheticToolId(name)
|
||||
}
|
||||
val argsPreview = payload.string("args_text")
|
||||
val argsPreview = payload?.get("args")
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
?: payload.string("args_text")
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: payload.string("context")?.takeIf { it.isNotBlank() }
|
||||
callbacks.onToolCallStart(toolId, name, argsPreview)
|
||||
@@ -256,6 +260,13 @@ class GatewayEventMapper(
|
||||
}
|
||||
callbacks.onUsage(parseGatewayUsage(payload?.get("usage") as? JsonObject))
|
||||
if (failed) {
|
||||
callbacks.onFailure(
|
||||
GatewayTurnFailure(
|
||||
error = error?.takeIf { it.isNotBlank() }
|
||||
?: text.orEmpty().ifBlank { "Turn failed" },
|
||||
recoverable = payload.boolean("recoverable") == true,
|
||||
),
|
||||
)
|
||||
callbacks.onStatusUpdate(
|
||||
ERROR_STATUS_KIND,
|
||||
error?.takeIf { it.isNotBlank() } ?: text.orEmpty().ifBlank { "Turn failed" },
|
||||
@@ -294,6 +305,7 @@ class GatewayEventMapper(
|
||||
// text; thinking/progress carry text only.
|
||||
preview = payload.string("tool_preview") ?: payload.string("text"),
|
||||
durationSeconds = payload.double("duration_seconds"),
|
||||
subagentId = payload.string("subagent_id"),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -439,15 +451,26 @@ class GatewayEventMapper(
|
||||
}
|
||||
|
||||
fun interactionRequest(type: String, payload: JsonObject?): GatewayAsk? = when (type) {
|
||||
"clarify.request" -> GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
|
||||
?.takeIf { it.isNotEmpty() },
|
||||
timeoutSeconds = CLARIFY_TIMEOUT_SECONDS,
|
||||
)
|
||||
"clarify.request" -> {
|
||||
val choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
|
||||
?.filter { it.isNotEmpty() }
|
||||
?.distinct()
|
||||
?.take(MAX_CLARIFY_CHOICES)
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = choices,
|
||||
multiSelect = payload.boolean("multi_select") == true && choices != null,
|
||||
// Current upstream owns expiry through clarify.expire and
|
||||
// does not advertise its configurable deadline. Never
|
||||
// invent a local deadline; consume future additive
|
||||
// metadata only when it is present and positive.
|
||||
timeoutSeconds = payload.int("timeout_seconds")?.coerceAtLeast(0) ?: 0,
|
||||
)
|
||||
}
|
||||
|
||||
"approval.request" -> GatewayAsk(
|
||||
kind = GatewayAsk.Kind.APPROVAL,
|
||||
@@ -556,9 +579,9 @@ class GatewayEventMapper(
|
||||
}
|
||||
}
|
||||
|
||||
// Upstream `_block()` timeouts per ask kind (server.py) — the blocked thread
|
||||
// resolves to "" when these elapse. Approval has none (session-scoped).
|
||||
private const val CLARIFY_TIMEOUT_SECONDS = 300
|
||||
// Upstream clarify tool accepts at most four choices. Sudo/secret retain fixed
|
||||
// `_block()` timeouts; clarify is configurable and expires authoritatively.
|
||||
private const val MAX_CLARIFY_CHOICES = 4
|
||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
||||
|
||||
@@ -578,6 +601,12 @@ private fun JsonObject?.approvalChoices(): List<String>? =
|
||||
(this?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.lowercase() }
|
||||
?.filter { it in setOf("once", "session", "always", "deny") }
|
||||
// Scope-denial flags are authoritative. Current upstream protected-
|
||||
// instruction requests set both flags false, but gateway event builders
|
||||
// can still include the broader session choice in `choices`.
|
||||
// Never offer a scope the request explicitly forbids.
|
||||
?.filterNot { it == "session" && this.boolean("allow_session") == false }
|
||||
?.filterNot { it == "always" && this.boolean("allow_permanent") == false }
|
||||
?.distinct()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
|
||||
|
||||
+10
@@ -8,6 +8,7 @@ import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
@@ -157,6 +158,15 @@ class GatewayKeepAliveService : Service() {
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
// Per-app locale changes recreate MainActivity but intentionally keep
|
||||
// this foreground service (and its Gateway socket) alive. Re-post the
|
||||
// existing notification so its localized title/body follow the new
|
||||
// application resources without restarting either owner.
|
||||
startForegroundNotification()
|
||||
}
|
||||
|
||||
private fun applyState(
|
||||
persistent: Boolean,
|
||||
turns: ActiveTurnKeepAliveRegistry.Snapshot,
|
||||
|
||||
@@ -218,13 +218,15 @@ data class GatewayAsk(
|
||||
val text: String,
|
||||
/** Server-advertised answers for clarify and approval requests. */
|
||||
val choices: List<String>? = null,
|
||||
/** Clarify-only: several advertised choices may be returned together. */
|
||||
val multiSelect: Boolean = false,
|
||||
/** Approval-only: the smart observer denied and the owner may override once. */
|
||||
val smartDenied: Boolean = false,
|
||||
/** Secret-only: the env var the value will be stored under. */
|
||||
val envVar: String? = null,
|
||||
/**
|
||||
* Upstream blocking timeout (clarify/secret 300s, sudo 120s). 0 means no
|
||||
* countdown — approvals are session-scoped and never expire on their own.
|
||||
* Server-advertised blocking timeout. 0 means no client countdown; the
|
||||
* authoritative `*.expire` event still retires the interaction.
|
||||
*/
|
||||
val timeoutSeconds: Int,
|
||||
) {
|
||||
@@ -270,6 +272,7 @@ data class GatewaySubagentEvent(
|
||||
val toolName: String? = null,
|
||||
val preview: String? = null,
|
||||
val durationSeconds: Double? = null,
|
||||
val subagentId: String? = null,
|
||||
) {
|
||||
enum class Phase { START, THINKING, TOOL, PROGRESS, COMPLETE }
|
||||
}
|
||||
@@ -547,6 +550,12 @@ data class GatewaySessionModel(
|
||||
val fast: Boolean? = null,
|
||||
)
|
||||
|
||||
/** Structured terminal failure carried by Gateway `message.complete`. */
|
||||
data class GatewayTurnFailure(
|
||||
val error: String,
|
||||
val recoverable: Boolean,
|
||||
)
|
||||
|
||||
/** Result of the gateway `config.get {key:"reasoning"}` RPC. */
|
||||
data class GatewayReasoningSettings(
|
||||
val effort: String,
|
||||
@@ -615,6 +624,10 @@ class GatewayTurnCallbacks(
|
||||
val onInteractionRequest: (GatewayAsk) -> Unit,
|
||||
/** Server declared a pending interaction expired; clear only the matching card. */
|
||||
val onInteractionExpired: (GatewayAskExpiry) -> Unit,
|
||||
/** Existing durable session could not be rebound; no prompt was submitted. */
|
||||
val onResumeFailure: (String) -> Unit = { _ -> },
|
||||
/** Terminal `message.complete {status:"error"}` without prose inspection. */
|
||||
val onFailure: (GatewayTurnFailure) -> Unit = { _ -> },
|
||||
/**
|
||||
* Gateway `status.update` lifecycle line — model fallback, retries, and
|
||||
* errors (often emoji-prefixed: 🔄 fallback, ⏳ retry, ❌ error). Default
|
||||
|
||||
@@ -6,6 +6,9 @@ import android.util.Log
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.AppAnalytics
|
||||
import com.hermesandroid.relay.network.shutdownOffMainThread
|
||||
import com.hermesandroid.relay.network.shared.InvalidCredentialException
|
||||
import com.hermesandroid.relay.network.shared.bearerAuthorization
|
||||
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
|
||||
import com.hermesandroid.relay.network.upstream.models.CreateSessionRequest
|
||||
import com.hermesandroid.relay.network.upstream.models.HermesSseEvent
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
@@ -431,15 +434,20 @@ private class RetryingEventSource(
|
||||
*/
|
||||
class HermesApiClient(
|
||||
baseUrl: String,
|
||||
private val apiKey: String,
|
||||
apiKey: String,
|
||||
httpClient: OkHttpClient? = null,
|
||||
private val json: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
}
|
||||
},
|
||||
okHttpClient: OkHttpClient? = null,
|
||||
) {
|
||||
@Volatile
|
||||
private var lastCapabilities: ServerCapabilities? = null
|
||||
private val baseUrl: String = baseUrl.trimEnd('/')
|
||||
private val apiCredential = runCatching {
|
||||
normalizeCredentialForHeader(apiKey, "API credential")
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HermesApiClient"
|
||||
@@ -479,7 +487,7 @@ class HermesApiClient(
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private val client: OkHttpClient = OkHttpClient.Builder()
|
||||
private val client: OkHttpClient = httpClient ?: okHttpClient ?: OkHttpClient.Builder()
|
||||
.readTimeout(5, TimeUnit.MINUTES)
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
@@ -538,6 +546,8 @@ class HermesApiClient(
|
||||
HealthCheckResult.Unhealthy("Server not found — check the hostname")
|
||||
} catch (e: java.net.SocketTimeoutException) {
|
||||
HealthCheckResult.Unhealthy("Connection timed out — is the server running?")
|
||||
} catch (e: InvalidCredentialException) {
|
||||
HealthCheckResult.Unhealthy(e.message ?: "Invalid API credential")
|
||||
} catch (e: IOException) {
|
||||
val msg = e.message ?: ""
|
||||
when {
|
||||
@@ -2021,9 +2031,8 @@ class HermesApiClient(
|
||||
|
||||
private fun authRequest(url: String): Request.Builder {
|
||||
val builder = Request.Builder().url(url)
|
||||
if (apiKey.isNotBlank()) {
|
||||
builder.header("Authorization", "Bearer $apiKey")
|
||||
}
|
||||
val credential = apiCredential.getOrElse { throw it }
|
||||
builder.bearerAuthorization(credential, "API credential")
|
||||
return builder
|
||||
}
|
||||
|
||||
@@ -2040,10 +2049,12 @@ class HermesApiClient(
|
||||
*/
|
||||
private fun authRequestOrNull(url: String): Request.Builder? {
|
||||
val builder = buildApiRequestOrNull(url) ?: return null
|
||||
if (apiKey.isNotBlank()) {
|
||||
builder.header("Authorization", "Bearer $apiKey")
|
||||
}
|
||||
return builder
|
||||
return runCatching {
|
||||
builder.bearerAuthorization(
|
||||
apiCredential.getOrElse { throw it },
|
||||
"API credential",
|
||||
)
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2061,7 +2072,8 @@ class HermesApiClient(
|
||||
|
||||
/** Human message for a base URL that fails to parse (#131). */
|
||||
private fun invalidBaseUrlMessage(): String =
|
||||
"Invalid server address ($baseUrl) — edit the connection's API URL or re-pair."
|
||||
apiCredential.exceptionOrNull()?.message
|
||||
?: "Invalid server address ($baseUrl) — edit the connection's API URL or re-pair."
|
||||
|
||||
/**
|
||||
* Make attachment drops on the SSE fallback transports explicit
|
||||
|
||||
+30
-6
@@ -4,6 +4,8 @@ import android.content.Context
|
||||
import com.hermesandroid.relay.auth.SessionTokenStore
|
||||
import com.hermesandroid.relay.auth.SecureStoreCache
|
||||
import com.hermesandroid.relay.auth.buildRawTokenStore
|
||||
import com.hermesandroid.relay.network.shared.bearerAuthorization
|
||||
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
|
||||
import java.io.EOFException
|
||||
import java.io.IOException
|
||||
import java.io.InterruptedIOException
|
||||
@@ -75,11 +77,13 @@ class EncryptedNativeDashboardTokenStore(
|
||||
|
||||
override fun load(): NativeDashboardTokens? =
|
||||
store.getString(TOKEN_KEY)?.let { raw ->
|
||||
runCatching { json.decodeFromString<NativeDashboardTokens>(raw) }.getOrNull()
|
||||
runCatching {
|
||||
json.decodeFromString<NativeDashboardTokens>(raw).normalizedForStorage()
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
override fun save(tokens: NativeDashboardTokens) {
|
||||
store.putString(TOKEN_KEY, json.encodeToString(tokens))
|
||||
store.putString(TOKEN_KEY, json.encodeToString(tokens.normalizedForStorage()))
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
@@ -140,7 +144,16 @@ class NativeDashboardAuthClient(
|
||||
.addQueryParameter("code_challenge_method", "S256")
|
||||
.addQueryParameter("redirect_uri", redirectUri)
|
||||
.addQueryParameter("state", state)
|
||||
.apply { provider?.takeIf(String::isNotBlank)?.let { addQueryParameter("provider", it) } }
|
||||
// Match the official Desktop client for Nous-hosted gateways: the
|
||||
// gateway selects its single native-eligible provider. The provider
|
||||
// name advertised to UI clients is presentation/configuration data,
|
||||
// not a stable native-broker identifier. Other providers retain the
|
||||
// explicit selector for direct client use and tests.
|
||||
.apply {
|
||||
provider
|
||||
?.takeIf { it.isNotBlank() && !it.equals("nous", ignoreCase = true) }
|
||||
?.let { addQueryParameter("provider", it) }
|
||||
}
|
||||
.build()
|
||||
.toString()
|
||||
val generation = NativeTokenRefreshCoordinator.beginAuthorization(
|
||||
@@ -441,7 +454,7 @@ class DashboardBearerAuth(
|
||||
val tokens = usableTokens(forceRefresh = false, failedAccessToken = null)
|
||||
val request = tokens?.let {
|
||||
chain.request().newBuilder()
|
||||
.header("Authorization", "Bearer ${it.accessToken}")
|
||||
.bearerAuthorization(it.accessToken, "Dashboard credential")
|
||||
.build()
|
||||
} ?: chain.request()
|
||||
return chain.proceed(request)
|
||||
@@ -455,9 +468,12 @@ class DashboardBearerAuth(
|
||||
forceRefresh = true,
|
||||
failedAccessToken = failedAccessToken,
|
||||
) ?: return null
|
||||
val next = "Bearer ${tokens.accessToken}"
|
||||
val accessToken = normalizeCredentialForHeader(tokens.accessToken, "Dashboard credential")
|
||||
val next = "Bearer $accessToken"
|
||||
if (next == previous) return null
|
||||
return response.request.newBuilder().header("Authorization", next).build()
|
||||
return response.request.newBuilder()
|
||||
.bearerAuthorization(accessToken, "Dashboard credential")
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun usableTokens(
|
||||
@@ -487,6 +503,14 @@ class DashboardBearerAuth(
|
||||
}
|
||||
}
|
||||
|
||||
private fun NativeDashboardTokens.normalizedForStorage(): NativeDashboardTokens = copy(
|
||||
accessToken = normalizeCredentialForHeader(accessToken, "Dashboard credential")
|
||||
.also { require(it.isNotEmpty()) { "Dashboard credential is empty" } },
|
||||
refreshToken = if (refreshToken.isEmpty()) "" else {
|
||||
normalizeCredentialForHeader(refreshToken, "Dashboard refresh credential")
|
||||
},
|
||||
)
|
||||
|
||||
internal class NativeDashboardAuthHttpException(
|
||||
val statusCode: Int,
|
||||
) : IOException("Dashboard native authentication failed (HTTP $statusCode)")
|
||||
|
||||
+59
-3
@@ -22,7 +22,7 @@ private const val CALLBACK_PATH = "/callback"
|
||||
private const val MAX_REQUEST_LINE_BYTES = 8 * 1024
|
||||
private const val MAX_HEADER_BYTES = 16 * 1024
|
||||
private const val ACCEPT_POLL_MILLIS = 500
|
||||
internal const val DEFAULT_NATIVE_SIGN_IN_TIMEOUT_MILLIS = 2 * 60 * 1000L
|
||||
internal const val DEFAULT_NATIVE_SIGN_IN_TIMEOUT_MILLIS = 5 * 60 * 1000L
|
||||
internal val NATIVE_SIGN_IN_RETURN_URI = "${BuildConfig.APPLICATION_ID}://return"
|
||||
|
||||
private enum class CallbackPage(
|
||||
@@ -46,6 +46,48 @@ private enum class CallbackPage(
|
||||
message = "No session details were saved from this attempt.",
|
||||
guidance = "Return to Hermes Relay and start sign-in again.",
|
||||
),
|
||||
AuthorizationRejected(
|
||||
modifier = "failure",
|
||||
eyebrow = "Provider sign-in",
|
||||
title = "Sign-in was not completed",
|
||||
message = "The provider returned without an approved authorization for Hermes.",
|
||||
guidance = "Return to Hermes Relay and start again if you still want to sign in.",
|
||||
),
|
||||
CodeRejected(
|
||||
modifier = "failure",
|
||||
eyebrow = "Hosted Hermes callback",
|
||||
title = "Hermes rejected the sign-in code",
|
||||
message = "Google sign-in finished, but hosted Hermes could not exchange its one-time callback code for a session.",
|
||||
guidance = "Return to Hermes Relay and start a fresh sign-in attempt.",
|
||||
),
|
||||
GatewayUnavailable(
|
||||
modifier = "failure",
|
||||
eyebrow = "Hosted Hermes callback",
|
||||
title = "Hosted Hermes could not finish sign-in",
|
||||
message = "The callback reached Hermes Relay, but the hosted Hermes sign-in service was unavailable.",
|
||||
guidance = "Return to Hermes Relay, wait a moment, and try again.",
|
||||
),
|
||||
TransportFailure(
|
||||
modifier = "failure",
|
||||
eyebrow = "Secure sign-in connection",
|
||||
title = "Could not reach hosted Hermes",
|
||||
message = "Google sign-in finished, but the secure connection back to hosted Hermes was interrupted.",
|
||||
guidance = "Return to Hermes Relay and retry on a stable connection.",
|
||||
),
|
||||
ResponseUnsupported(
|
||||
modifier = "failure",
|
||||
eyebrow = "Hosted Hermes callback",
|
||||
title = "Hermes returned an unsupported session",
|
||||
message = "The hosted gateway answered, but its sign-in response was not compatible with this app.",
|
||||
guidance = "Return to Hermes Relay and check for app and hosted Hermes updates.",
|
||||
),
|
||||
SessionStorageFailure(
|
||||
modifier = "failure",
|
||||
eyebrow = "Secure session storage",
|
||||
title = "The session could not be saved",
|
||||
message = "Google sign-in finished, but Android could not securely save the Hermes session on this device.",
|
||||
guidance = "Return to Hermes Relay and try again. If it repeats, check the app's diagnostics.",
|
||||
),
|
||||
Rejected(
|
||||
modifier = "rejected",
|
||||
eyebrow = "Protected callback",
|
||||
@@ -194,14 +236,14 @@ class NativeDashboardSignInCoordinator(
|
||||
writeResponse(
|
||||
socket,
|
||||
status = "400 Bad Request",
|
||||
page = CallbackPage.Failure,
|
||||
page = CallbackPage.AuthorizationRejected,
|
||||
)
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
writeResponse(
|
||||
socket,
|
||||
status = "400 Bad Request",
|
||||
page = CallbackPage.Failure,
|
||||
page = callbackFailurePage(error),
|
||||
)
|
||||
throw error
|
||||
}
|
||||
@@ -296,6 +338,20 @@ class NativeDashboardSignInCoordinator(
|
||||
}
|
||||
}
|
||||
|
||||
private fun callbackFailurePage(error: Throwable): CallbackPage {
|
||||
val stage = nativeDashboardSignInFailureStage(error)
|
||||
return when {
|
||||
stage == "token_http_400" -> CallbackPage.CodeRejected
|
||||
stage == "callback_error" -> CallbackPage.AuthorizationRejected
|
||||
stage == "token_http_429" || stage.startsWith("token_http_5") ->
|
||||
CallbackPage.GatewayUnavailable
|
||||
stage == "token_shape" -> CallbackPage.ResponseUnsupported
|
||||
stage == "token_store" -> CallbackPage.SessionStorageFailure
|
||||
stage.startsWith("token_transport") -> CallbackPage.TransportFailure
|
||||
else -> CallbackPage.Failure
|
||||
}
|
||||
}
|
||||
|
||||
private fun callbackPageHtml(page: CallbackPage): String = """
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
+154
-2
@@ -1,21 +1,27 @@
|
||||
package com.hermesandroid.relay.network.upstream.models
|
||||
|
||||
import com.hermesandroid.relay.data.MessageReaction
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.descriptors.PrimitiveKind
|
||||
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
|
||||
import kotlinx.serialization.encoding.Decoder
|
||||
import kotlinx.serialization.encoding.Encoder
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonDecoder
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonEncoder
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.Instant
|
||||
|
||||
/**
|
||||
@@ -76,6 +82,56 @@ object FlexibleIdNonNullSerializer : KSerializer<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Unknown-safe durable SQLite row id used by current Gateway history. */
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
object FlexibleLongSerializer : KSerializer<Long?> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("FlexibleLong", PrimitiveKind.LONG)
|
||||
|
||||
override fun deserialize(decoder: Decoder): Long? {
|
||||
return try {
|
||||
val jsonDecoder = decoder as? JsonDecoder
|
||||
?: return decoder.decodeLong()
|
||||
(jsonDecoder.decodeJsonElement() as? JsonPrimitive)?.longOrNull
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: Long?) {
|
||||
if (value != null) encoder.encodeLong(value) else encoder.encodeNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard versions may expose SQLite JSON columns either as an object or as
|
||||
* their raw JSON string. Normalize both shapes so persisted presentation data
|
||||
* (notably message reactions) survives a history reload on every supported
|
||||
* upstream version.
|
||||
*/
|
||||
object FlexibleJsonObjectSerializer : KSerializer<JsonObject?> {
|
||||
override val descriptor = JsonObject.serializer().descriptor
|
||||
|
||||
override fun deserialize(decoder: Decoder): JsonObject? {
|
||||
return try {
|
||||
val jsonDecoder = decoder as? JsonDecoder ?: return null
|
||||
when (val element = jsonDecoder.decodeJsonElement()) {
|
||||
is JsonObject -> element
|
||||
is JsonPrimitive -> element.content.takeIf { it.isNotBlank() }
|
||||
?.let { Json.parseToJsonElement(it) as? JsonObject }
|
||||
else -> null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: JsonObject?) {
|
||||
val jsonEncoder = encoder as? JsonEncoder
|
||||
?: throw SerializationException("FlexibleJsonObjectSerializer requires JSON")
|
||||
jsonEncoder.encodeJsonElement(value ?: JsonNull)
|
||||
}
|
||||
}
|
||||
|
||||
/** Timestamp serializer for Hermes session metadata.
|
||||
*
|
||||
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
|
||||
@@ -113,6 +169,32 @@ object FlexibleTimestampSerializer : KSerializer<Double?> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Boolean serializer for session flags backed by SQLite integer columns.
|
||||
*
|
||||
* Older Dashboard responses can expose those columns as `0` / `1` instead of
|
||||
* JSON booleans. Accept the equivalent primitive forms without making arbitrary
|
||||
* numbers or strings truthy, and always serialize back to a real JSON boolean.
|
||||
*/
|
||||
object FlexibleBooleanSerializer : KSerializer<Boolean> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("FlexibleBoolean", PrimitiveKind.BOOLEAN)
|
||||
|
||||
override fun deserialize(decoder: Decoder): Boolean {
|
||||
val jsonDecoder = decoder as? JsonDecoder ?: return decoder.decodeBoolean()
|
||||
val element = jsonDecoder.decodeJsonElement()
|
||||
val value = (element as? JsonPrimitive)?.content?.trim()?.lowercase()
|
||||
return when (value) {
|
||||
"true", "1" -> true
|
||||
"false", "0" -> false
|
||||
else -> throw SerializationException("Expected a boolean-compatible value, got $element")
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: Boolean) {
|
||||
encoder.encodeBoolean(value)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Session CRUD responses ---
|
||||
|
||||
@Serializable
|
||||
@@ -142,6 +224,8 @@ data class SessionItem(
|
||||
val preview: String? = null,
|
||||
val model: String? = null,
|
||||
val source: String? = null,
|
||||
/** Owning profile on the cross-profile `/api/profiles/sessions` endpoint. */
|
||||
val profile: String? = null,
|
||||
@SerialName("started_at")
|
||||
@Serializable(with = FlexibleTimestampSerializer::class)
|
||||
val startedAt: Double? = null,
|
||||
@@ -164,15 +248,50 @@ data class SessionItem(
|
||||
@SerialName("tool_call_count") val toolCallCount: Int? = null,
|
||||
@SerialName("input_tokens") val inputTokens: Int? = null,
|
||||
@SerialName("output_tokens") val outputTokens: Int? = null,
|
||||
@SerialName("has_model_config") val hasModelConfig: Boolean = false,
|
||||
@SerialName("actual_cost_usd") val actualCostUsd: Double? = null,
|
||||
@SerialName("estimated_cost_usd") val estimatedCostUsd: Double? = null,
|
||||
@SerialName("is_active") val isActive: Boolean = false,
|
||||
@SerialName("has_model_config")
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val hasModelConfig: Boolean = false,
|
||||
/** Durable flags returned by current Dashboard and API-server session resources. */
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val pinned: Boolean = false,
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val archived: Boolean = false,
|
||||
/** Optional workspace metadata added by newer Dashboard session lists. */
|
||||
val cwd: String? = null,
|
||||
@SerialName("git_branch") val gitBranch: String? = null,
|
||||
@SerialName("git_repo_root") val gitRepoRoot: String? = null,
|
||||
/** Best-effort association from the Dashboard's read-only transcript scan. */
|
||||
val pullRequest: SessionPullRequest? = null,
|
||||
) {
|
||||
val resolvedLastActivity: Double?
|
||||
get() = lastActive ?: lastActivity ?: lastActivityAt ?: updatedAt
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SessionPullRequest(
|
||||
val number: Int,
|
||||
val url: String,
|
||||
val branch: String? = null,
|
||||
val state: String? = null,
|
||||
val draft: Boolean = false,
|
||||
val title: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SessionPullRequestScanResponse(
|
||||
@SerialName("pull_requests") val pullRequests: Map<String, SessionPullRequest> = emptyMap(),
|
||||
val scanned: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RepositoryPullRequestListResponse(
|
||||
val ghReady: Boolean = false,
|
||||
val prs: List<SessionPullRequest> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CreateSessionRequest(
|
||||
val title: String? = null,
|
||||
@@ -263,6 +382,9 @@ data class MessageItem(
|
||||
@SerialName("session_id")
|
||||
@Serializable(with = FlexibleIdSerializer::class)
|
||||
val sessionId: String? = null,
|
||||
@SerialName("row_id")
|
||||
@Serializable(with = FlexibleLongSerializer::class)
|
||||
val rowId: Long? = null,
|
||||
val role: String,
|
||||
val content: JsonElement? = null,
|
||||
@SerialName("tool_calls") val toolCalls: JsonElement? = null,
|
||||
@@ -273,7 +395,9 @@ data class MessageItem(
|
||||
val timestamp: Double? = null,
|
||||
@SerialName("finish_reason") val finishReason: String? = null,
|
||||
@SerialName("display_kind") val displayKind: String? = null,
|
||||
@SerialName("display_metadata") val displayMetadata: JsonObject? = null,
|
||||
@SerialName("display_metadata")
|
||||
@Serializable(with = FlexibleJsonObjectSerializer::class)
|
||||
val displayMetadata: JsonObject? = null,
|
||||
// Reasoning persisted with the assistant message (upstream serializes
|
||||
// both names; reasoning is the canonical one). Restored into
|
||||
// ChatMessage.thinkingContent so the Thought-process block survives a
|
||||
@@ -281,11 +405,24 @@ data class MessageItem(
|
||||
val reasoning: String? = null,
|
||||
@SerialName("reasoning_content") val reasoningContent: String? = null,
|
||||
) {
|
||||
/**
|
||||
* Dashboard history uses the SQLite row id as numeric `id`; Gateway
|
||||
* history exposes the same value explicitly as `row_id`. Match Desktop by
|
||||
* accepting either representation so persisted rows remain directly
|
||||
* reactable after reload.
|
||||
*/
|
||||
val resolvedRowId: Long?
|
||||
get() = rowId ?: id?.toLongOrNull()
|
||||
|
||||
/** Reasoning text under whichever field name the server used. */
|
||||
val resolvedReasoning: String?
|
||||
get() = reasoning?.takeIf { it.isNotBlank() }
|
||||
?: reasoningContent?.takeIf { it.isNotBlank() }
|
||||
|
||||
/** Persisted tapbacks stored by Hermes in display_metadata.reactions. */
|
||||
val reactions: List<MessageReaction>
|
||||
get() = parseMessageReactions(displayMetadata?.get("reactions"))
|
||||
|
||||
/** Extract content as plain text string. Handles both string and array-of-parts formats. */
|
||||
val contentText: String?
|
||||
get() = when (content) {
|
||||
@@ -313,6 +450,21 @@ data class MessageItem(
|
||||
}
|
||||
}
|
||||
|
||||
fun parseMessageReactions(element: JsonElement?): List<MessageReaction> =
|
||||
(element as? JsonArray).orEmpty().mapNotNull { raw ->
|
||||
val reaction = raw as? JsonObject ?: return@mapNotNull null
|
||||
val emoji = (reaction["emoji"] as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() }
|
||||
?: return@mapNotNull null
|
||||
val author = (reaction["author"] as? JsonPrimitive)?.content
|
||||
?.takeIf { it == "user" || it == "agent" }
|
||||
?: return@mapNotNull null
|
||||
MessageReaction(
|
||||
emoji = emoji,
|
||||
author = author,
|
||||
at = (reaction["at"] as? JsonPrimitive)?.doubleOrNull ?: 0.0,
|
||||
)
|
||||
}
|
||||
|
||||
// --- SSE streaming events from /api/sessions/{id}/chat/stream ---
|
||||
//
|
||||
// Hermes WebAPI event types (from server source):
|
||||
|
||||
+8
-4
@@ -9,6 +9,7 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
@@ -47,10 +48,13 @@ object ProactiveMessageNotifier {
|
||||
/**
|
||||
* Tap route — opens Chat, where the message lives as a Thread. Must match
|
||||
* `Screen.Chat.route()` in RelayApp. Routed via the EXTRA_NAV_ROUTE deep-link
|
||||
* path (MainActivity → NavRouteRequest → RelayApp collector). Opening the
|
||||
* exact Thread by chat_id is a follow-up (see TODO).
|
||||
* path (MainActivity → NavRouteRequest → RelayApp collector), carrying the
|
||||
* `chat_id` so RelayApp opens the exact real or provisional Thread.
|
||||
*/
|
||||
private const val TAP_ROUTE = "chat"
|
||||
private fun tapRoute(chatId: String?): String =
|
||||
chatId?.takeIf { it.isNotBlank() }
|
||||
?.let { "chat?proactiveChatId=${Uri.encode(it)}" }
|
||||
?: "chat"
|
||||
|
||||
/**
|
||||
* Post (or replace) a proactive-message notification.
|
||||
@@ -80,7 +84,7 @@ object ProactiveMessageNotifier {
|
||||
|
||||
val tapIntent = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
putExtra(MainActivity.EXTRA_NAV_ROUTE, TAP_ROUTE)
|
||||
putExtra(MainActivity.EXTRA_NAV_ROUTE, tapRoute(chatId))
|
||||
}
|
||||
val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
// Distinct requestCode per slot so each notification gets its own
|
||||
|
||||
@@ -68,6 +68,7 @@ import com.hermesandroid.relay.plugins.document.PluginSpacing
|
||||
import com.hermesandroid.relay.plugins.document.PluginTextStyle
|
||||
import com.hermesandroid.relay.plugins.document.PluginTone
|
||||
import com.hermesandroid.relay.plugins.document.PluginValue
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.components.rememberAccessibleMotionState
|
||||
|
||||
sealed interface PluginInteraction {
|
||||
@@ -340,7 +341,7 @@ private fun PluginProgress(
|
||||
private fun DefaultPluginAsset(contentDescription: String, modifier: Modifier) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clip(appearanceRoundedCornerShape(12.dp))
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
|
||||
@@ -90,6 +90,29 @@ object ReliabilityCenter {
|
||||
writer.execute { runCatching { target.append(report) } }
|
||||
}
|
||||
|
||||
/** Persist a bounded, content-free checkpoint before a user-requested chat reset. */
|
||||
fun recordSessionCheckpoint(context: Context, evidence: SessionResetEvidence) {
|
||||
initialize(context)
|
||||
val report = ReliabilityReport(
|
||||
reportId = ReliabilityReport.newId("checkpoint"),
|
||||
appSessionId = appSessionId,
|
||||
timeIso = Instant.now().toString(),
|
||||
kind = ReliabilityKind.SessionCheckpoint,
|
||||
owner = ReliabilityOwner.Android,
|
||||
severity = ReliabilitySeverity.Info,
|
||||
summary = "Chat context reset",
|
||||
recovery = "The prior context remains on Hermes when it had a stored session.",
|
||||
reportRecommended = false,
|
||||
technicalDetail = evidence.technicalDetail(),
|
||||
routeRole = evidence.transport,
|
||||
environment = environment(),
|
||||
)
|
||||
// A pre-reset checkpoint is useful only if it lands before state is
|
||||
// replaced. The store is tiny and atomically rewritten, so persist it
|
||||
// synchronously instead of queueing behind later failures.
|
||||
runCatching { store?.append(report) }
|
||||
}
|
||||
|
||||
fun reports(context: Context): List<ReliabilityReport> {
|
||||
initialize(context)
|
||||
return store?.readAll().orEmpty()
|
||||
|
||||
@@ -15,6 +15,7 @@ const val RELIABILITY_SCHEMA_VERSION = 1
|
||||
enum class ReliabilityKind {
|
||||
FatalCrash,
|
||||
AnrSignal,
|
||||
SessionCheckpoint,
|
||||
RecoverableProductError,
|
||||
Connectivity,
|
||||
Authentication,
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.hermesandroid.relay.reliability
|
||||
|
||||
/**
|
||||
* Content-free evidence captured immediately before Android replaces a chat
|
||||
* context. Deliberately excludes prompts, message text, IDs, profile names,
|
||||
* URLs, paths, attachments, and tool arguments/results.
|
||||
*/
|
||||
data class SessionResetEvidence(
|
||||
val reason: String,
|
||||
val transport: String,
|
||||
val messageCount: Int,
|
||||
val toolCount: Int,
|
||||
val queuedCount: Int,
|
||||
val pendingAttachmentCount: Int,
|
||||
val hadStoredSession: Boolean,
|
||||
val turnActive: Boolean,
|
||||
val askPending: Boolean,
|
||||
) {
|
||||
fun technicalDetail(): String = buildString {
|
||||
appendLine("reason=${reason.safeToken()}")
|
||||
appendLine("transport=${transport.safeToken()}")
|
||||
appendLine("messages=${messageCount.coerceAtLeast(0)}")
|
||||
appendLine("tools=${toolCount.coerceAtLeast(0)}")
|
||||
appendLine("queued=${queuedCount.coerceAtLeast(0)}")
|
||||
appendLine("pending_attachments=${pendingAttachmentCount.coerceAtLeast(0)}")
|
||||
appendLine("had_stored_session=$hadStoredSession")
|
||||
appendLine("turn_active=$turnActive")
|
||||
append("ask_pending=$askPending")
|
||||
}
|
||||
|
||||
private fun String.safeToken(): String =
|
||||
lowercase().replace(Regex("[^a-z0-9_.-]"), "_").take(40).ifBlank { "unknown" }
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import androidx.lifecycle.ViewModelStore
|
||||
import com.hermesandroid.relay.HermesRelayApp
|
||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||
import com.hermesandroid.relay.data.VoiceSettings
|
||||
import com.hermesandroid.relay.data.PersistentChatComposerDraftStore
|
||||
import java.io.File
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
@@ -70,7 +72,13 @@ class HermesProcessRuntime internal constructor(
|
||||
}
|
||||
|
||||
val chatViewModel: ChatViewModel by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
|
||||
viewModelProvider[ChatViewModel::class.java]
|
||||
viewModelProvider[ChatViewModel::class.java].also { chat ->
|
||||
chat.installComposerDraftStore(
|
||||
PersistentChatComposerDraftStore(
|
||||
File(application.noBackupFilesDir, "chat-composer-drafts"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val voiceViewModel: VoiceViewModel by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
|
||||
|
||||
@@ -142,8 +142,8 @@ internal class HermesRuntimeBinder(
|
||||
voiceHandoffReporter = connection::recordVoiceHandoff,
|
||||
bargeInPreferences = BargeInPreferencesRepository(application),
|
||||
vadEngineFactory = { VadEngine(application) },
|
||||
bargeInListenerFactory = { vad, audioSessionIdProvider ->
|
||||
BargeInListener.create(application, vad, audioSessionIdProvider)
|
||||
bargeInListenerFactory = { vad ->
|
||||
BargeInListener.create(application, vad)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -175,13 +175,26 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
chat.setDisplayProfileProvider { connection.effectiveDisplayProfile.value }
|
||||
chat.setDisplayAliasProvider { connection.profileDisplayAlias.value }
|
||||
chat.setProfileSessionLister { connection.listProfileScopedSessions() }
|
||||
chat.setProfileMessageLoaderWithMode(connection::loadProfileScopedMessages)
|
||||
chat.setLockedProfileNameProvider { connection.lockedProfileName.value }
|
||||
chat.setProfileSelectionHandler { profile ->
|
||||
if (!connection.isProfileSelectionAllowed(profile?.name)) {
|
||||
false
|
||||
} else {
|
||||
connection.selectProfile(profile)
|
||||
true
|
||||
}
|
||||
}
|
||||
chat.setProfileSessionLister { profileName ->
|
||||
connection.listProfileScopedSessions(profileName)
|
||||
}
|
||||
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
|
||||
connection.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
}
|
||||
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
|
||||
chat.profileSessionDeleter = connection::deleteProfileScopedSession
|
||||
chat.profileSessionRenamer = connection::renameProfileScopedSession
|
||||
chat.profileSessionPinner = connection::setProfileScopedSessionPinned
|
||||
chat.profileSessionArchiver = connection::setProfileScopedSessionArchived
|
||||
chat.profileSessionDeleter = connection::deleteSession
|
||||
chat.profileSessionRenamer = connection::renameSession
|
||||
chat.profileSessionPinner = connection::setSessionPinned
|
||||
chat.profileSessionArchiver = connection::setSessionArchived
|
||||
chat.onSessionChanged = connection::saveLastSessionId
|
||||
chat.setDemoModeWiring(
|
||||
isDemo = { connection.isDemoMode.value },
|
||||
@@ -281,20 +294,29 @@ internal class HermesRuntimeBinder(
|
||||
) { ready, connectionId, profileName, sessionId ->
|
||||
ProfileContextInputs(ready, connectionId, profileName, sessionId)
|
||||
}
|
||||
combine(contextInputs, connection.profileSelectionSettled) { inputs, settled ->
|
||||
inputs.copy(profileSelectionSettled = settled)
|
||||
combine(
|
||||
contextInputs,
|
||||
connection.profileSelectionSettled,
|
||||
connection.lockedProfileName,
|
||||
) { inputs, settled, lockedProfileName ->
|
||||
inputs.copy(
|
||||
profileSelectionSettled = settled,
|
||||
profileLocked = lockedProfileName != null,
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
profileContextReady.value = false
|
||||
if (!inputs.chatReady) return@collectLatest
|
||||
if (!inputs.profileSelectionSettled) delay(PROFILE_SETTLE_BACKSTOP_MS)
|
||||
else delay(PROFILE_CONTEXT_COALESCE_MS)
|
||||
chat.switchProfileContext(
|
||||
contextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = inputs.connectionId,
|
||||
profileName = inputs.profileName,
|
||||
),
|
||||
sessionId = inputs.sessionId,
|
||||
val contextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = inputs.connectionId,
|
||||
profileName = inputs.profileName,
|
||||
)
|
||||
if (inputs.profileLocked) {
|
||||
chat.switchProfileContext(contextKey, inputs.sessionId)
|
||||
} else {
|
||||
chat.reconcileProfileContext(contextKey, inputs.sessionId)
|
||||
}
|
||||
chat.refreshSessions()
|
||||
profileContextReady.value = true
|
||||
}
|
||||
@@ -436,6 +458,7 @@ internal class HermesRuntimeBinder(
|
||||
val profileName: String?,
|
||||
val sessionId: String?,
|
||||
val profileSelectionSettled: Boolean = false,
|
||||
val profileLocked: Boolean = false,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
|
||||
@@ -75,6 +75,7 @@ import androidx.navigation.navArgument
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.HermesRelayApp
|
||||
import com.hermesandroid.relay.ui.components.CrashReportGate
|
||||
import com.hermesandroid.relay.ui.components.CandidateBuildBanner
|
||||
import com.hermesandroid.relay.ui.components.DemoModeBanner
|
||||
import com.hermesandroid.relay.ui.components.DemoUnavailableContent
|
||||
import com.hermesandroid.relay.ui.components.MessageBannerHost
|
||||
@@ -96,6 +97,7 @@ import com.hermesandroid.relay.ui.components.avatar.LocalFloatingPet
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalPetPlaybackSpeed
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalPetStabilize
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetLoader
|
||||
import com.hermesandroid.relay.ui.components.avatar.toAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.SphereAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.resolveBackgroundAvatar
|
||||
import com.hermesandroid.relay.ui.components.FloatingPetCompanion
|
||||
@@ -116,6 +118,7 @@ import com.hermesandroid.relay.ui.components.PowerFeatureGateStatus
|
||||
import com.hermesandroid.relay.ui.components.RelayStatusStrip
|
||||
import com.hermesandroid.relay.ui.components.UnattendedGlobalBanner
|
||||
import com.hermesandroid.relay.ui.components.UpdateAvailableBanner
|
||||
import com.hermesandroid.relay.ui.components.HostResourcePressureBanner
|
||||
import com.hermesandroid.relay.ui.components.rememberUpdateAvailability
|
||||
import com.hermesandroid.relay.ui.components.resolveChatTransportStatus
|
||||
import com.hermesandroid.relay.ui.components.WhatsNewDialog
|
||||
@@ -123,6 +126,7 @@ import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.BridgePreferencesRepository
|
||||
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.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
@@ -139,6 +143,7 @@ import com.hermesandroid.relay.ui.onboarding.OnboardingScreen
|
||||
import com.hermesandroid.relay.ui.screens.AboutScreen
|
||||
import com.hermesandroid.relay.ui.screens.AnalyticsScreen
|
||||
import com.hermesandroid.relay.ui.screens.AppearanceSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.CustomThemeScreen
|
||||
import com.hermesandroid.relay.ui.screens.CustomPetGuideScreen
|
||||
import com.hermesandroid.relay.ui.screens.PetdexBrowseScreen
|
||||
import com.hermesandroid.relay.ui.screens.BridgeCoreScreen
|
||||
@@ -336,17 +341,20 @@ sealed class Screen(
|
||||
// NavHost, and the NavigationBarItem click must navigate via [route]()
|
||||
// so no unresolved `{openAgentSheet}` leaks into the destination.
|
||||
data object Chat : Screen(
|
||||
"chat?openAgentSheet={openAgentSheet}&sessionId={sessionId}&profile={profile}",
|
||||
"chat?openAgentSheet={openAgentSheet}&sessionId={sessionId}&profile={profile}" +
|
||||
"&proactiveChatId={proactiveChatId}",
|
||||
"Chat",
|
||||
Icons.AutoMirrored.Filled.Chat,
|
||||
) {
|
||||
const val ARG_OPEN_AGENT_SHEET: String = "openAgentSheet"
|
||||
const val ARG_SESSION_ID: String = "sessionId"
|
||||
const val ARG_PROFILE: String = "profile"
|
||||
const val ARG_PROACTIVE_CHAT_ID: String = "proactiveChatId"
|
||||
fun route(
|
||||
openAgentSheet: Boolean = false,
|
||||
sessionId: String? = null,
|
||||
profile: String? = null,
|
||||
proactiveChatId: String? = null,
|
||||
): String {
|
||||
val params = buildList {
|
||||
if (openAgentSheet) add("$ARG_OPEN_AGENT_SHEET=true")
|
||||
@@ -356,6 +364,9 @@ sealed class Screen(
|
||||
profile?.takeIf { it.isNotBlank() }?.let {
|
||||
add("$ARG_PROFILE=${android.net.Uri.encode(it)}")
|
||||
}
|
||||
proactiveChatId?.takeIf { it.isNotBlank() }?.let {
|
||||
add("$ARG_PROACTIVE_CHAT_ID=${android.net.Uri.encode(it)}")
|
||||
}
|
||||
}
|
||||
return if (params.isEmpty()) "chat" else "chat?${params.joinToString("&")}"
|
||||
}
|
||||
@@ -469,6 +480,7 @@ sealed class Screen(
|
||||
data object ChatSettings : Screen("settings/chat", "Chat", Icons.Filled.Settings)
|
||||
data object MediaSettings : Screen("settings/media", "Media", Icons.Filled.Settings)
|
||||
data object AppearanceSettings : Screen("settings/appearance", "Appearance", Icons.Filled.Settings)
|
||||
data object CustomTheme : Screen("settings/appearance/custom-theme", "Custom", Icons.Filled.Settings)
|
||||
data object PetdexBrowse : Screen("settings/appearance/petdex", "Petdex", Icons.Filled.Settings)
|
||||
data object CustomPetGuide : Screen("settings/appearance/custom-pet", "Create a pet", Icons.Filled.Settings)
|
||||
data object Analytics : Screen("settings/analytics", "Analytics", Icons.Filled.Settings)
|
||||
@@ -618,21 +630,11 @@ fun RelayApp() {
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val relayVoiceReady by connectionViewModel.relayVoiceReady.collectAsState()
|
||||
|
||||
// Profile Inspector client. Shares the same lazy relay URL + bearer
|
||||
// token providers as the voice client so any rotation/re-pair is
|
||||
// automatically picked up on the next fetch. Process-stable via
|
||||
// remember {} so the OkHttpClient isn't rebuilt on recomposition.
|
||||
val profileInspectorClient = remember {
|
||||
RelayProfileInspectorClient(
|
||||
okHttpClient = okhttp3.OkHttpClient.Builder()
|
||||
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build(),
|
||||
relayUrlProvider = { connectionViewModel.effectiveRelayUrl.value },
|
||||
sessionTokenProvider = {
|
||||
(connectionViewModel.authState.value as? AuthState.Paired)?.token
|
||||
},
|
||||
)
|
||||
val profileInspectorHttpClient = remember {
|
||||
okhttp3.OkHttpClient.Builder()
|
||||
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
// === PHASE3-status: sync granular phone-status settings to chat ===
|
||||
val appContextEnabled by connectionViewModel.appContextEnabled.collectAsState()
|
||||
@@ -706,6 +708,7 @@ fun RelayApp() {
|
||||
val appFontId by connectionViewModel.appFont.collectAsState()
|
||||
val appearanceAccent by connectionViewModel.appearanceAccent.collectAsState()
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
val activeCustomTheme by connectionViewModel.activeCustomTheme.collectAsState()
|
||||
|
||||
// Resolve the active sphere skin (built-in / adaptive / user-loaded) and
|
||||
// publish it + the full available set so every MorphingSphere picks it up
|
||||
@@ -745,8 +748,12 @@ fun RelayApp() {
|
||||
) {
|
||||
value = withContext(Dispatchers.IO) { PetLoader.loadPets(sphereContext) }
|
||||
}
|
||||
val activeFloatingPet = remember(floatingPetId, availablePets) {
|
||||
availablePets.firstOrNull { it.id == floatingPetId }
|
||||
val hermesPetState by connectionViewModel.hermesPetState.collectAsState()
|
||||
val upstreamProfilePet = remember(hermesPetState.active) {
|
||||
hermesPetState.active?.toAvatar()
|
||||
}
|
||||
val activeFloatingPet = remember(floatingPetId, availablePets, upstreamProfilePet) {
|
||||
availablePets.firstOrNull { it.id == floatingPetId } ?: upstreamProfilePet
|
||||
}
|
||||
var floatingPetMenuExpanded by remember(activeFloatingPet?.id) { mutableStateOf(false) }
|
||||
val activeBackgroundAvatar = remember(backgroundAvatarId, availablePets) {
|
||||
@@ -862,6 +869,7 @@ fun RelayApp() {
|
||||
appFontId = appFontId,
|
||||
accentHex = appearanceAccent,
|
||||
shapeId = appearanceShape,
|
||||
customTheme = activeCustomTheme,
|
||||
) {
|
||||
// Surface a crash report from a previous session, if any. Renders a
|
||||
// platform Dialog (own window) so tree position is z-order-agnostic;
|
||||
@@ -891,6 +899,7 @@ fun RelayApp() {
|
||||
// ChatViewModel isn't available where ConnectionViewModel builds the
|
||||
// handler, so the session sink is set here at the app root where both
|
||||
// ViewModels are in scope.
|
||||
val proactiveSummaryResources = LocalContext.current.resources
|
||||
LaunchedEffect(connectionViewModel, chatViewModel) {
|
||||
connectionViewModel.proactiveMessageHandler.toSession = { msg ->
|
||||
val text = buildString {
|
||||
@@ -899,6 +908,15 @@ fun RelayApp() {
|
||||
}
|
||||
chatViewModel.injectProactiveMessage(text)
|
||||
}
|
||||
connectionViewModel.proactiveMessageHandler.onBacklogDelivered = { count ->
|
||||
UiMessageBus.info(
|
||||
proactiveSummaryResources.getQuantityString(
|
||||
R.plurals.proactive_messages_arrived_while_away,
|
||||
count,
|
||||
count,
|
||||
),
|
||||
)
|
||||
}
|
||||
// Agent Thread reply path: a send from the chat composer while a
|
||||
// source=phone Thread is open routes over the relay proactive
|
||||
// channel (continues the gateway phone session) instead of a normal
|
||||
@@ -910,7 +928,8 @@ fun RelayApp() {
|
||||
chatViewModel.onProactiveReplyAck(clientMsgId, status)
|
||||
}
|
||||
// Unified Threads: render an inbound agent message inline in the open
|
||||
// Thread (suppressing the notification/inbox) when it belongs there.
|
||||
// Thread when it belongs there. Surfacing semantics still decide
|
||||
// independently whether a system notification is also required.
|
||||
connectionViewModel.proactiveMessageHandler.injectIntoThread = { msg ->
|
||||
chatViewModel.injectThreadMessage(msg)
|
||||
}
|
||||
@@ -1374,19 +1393,48 @@ fun RelayApp() {
|
||||
}
|
||||
val masterEnabled by masterEnabledFlow.collectAsState(initial = false)
|
||||
val unattendedEnabled by unattendedEnabledFlow.collectAsState(initial = false)
|
||||
val activeBridgePolicy by (connectionViewModel.bridgeSafety?.activeCapabilityPolicy
|
||||
?: remember { kotlinx.coroutines.flow.MutableStateFlow(
|
||||
com.hermesandroid.relay.bridge.BridgeCapabilityPolicy(),
|
||||
) })
|
||||
.collectAsState()
|
||||
val timedScreenControlActive = activeBridgePolicy.allows(
|
||||
com.hermesandroid.relay.bridge.BridgeCapability.SCREEN_CONTROL,
|
||||
System.currentTimeMillis(),
|
||||
)
|
||||
// Sideload-only: googlePlay has no wake lock and the unattended
|
||||
// flag never gets written there — gating here is defence in depth
|
||||
// and makes the check cheap via R8 in release builds.
|
||||
val showUnattendedBanner = BuildFlavor.isSideload &&
|
||||
masterEnabled &&
|
||||
unattendedEnabled &&
|
||||
timedScreenControlActive &&
|
||||
!suppressGlobalChrome &&
|
||||
!showStartupSphere &&
|
||||
!voiceUiState.voiceMode
|
||||
val showCandidateBanner = CandidateBuild.isCandidate &&
|
||||
!voiceUiState.voiceMode &&
|
||||
!showStartupSphere
|
||||
// Persistent Demo-mode strip — visible on every demo surface so the
|
||||
// user always knows the chat is sample data with no live server, and
|
||||
// can exit into the real Connect flow with one tap.
|
||||
val showDemoBanner = isDemoMode && !voiceUiState.voiceMode
|
||||
val hostResourcePressure by connectionViewModel.hostResourcePressure.collectAsState()
|
||||
val showHostResourcePressure = hostResourcePressure.needsAttention &&
|
||||
!isDemoMode && !voiceUiState.voiceMode && !showStartupSphere
|
||||
val hostResourcePressureText = buildList {
|
||||
if (hostResourcePressure.lastBootSuspectedOom) {
|
||||
add(stringResource(R.string.host_resource_recent_oom))
|
||||
}
|
||||
when (hostResourcePressure.memoryPressure) {
|
||||
"critical" -> add(stringResource(R.string.host_resource_memory_critical))
|
||||
"elevated" -> add(stringResource(R.string.host_resource_memory_elevated))
|
||||
}
|
||||
when (hostResourcePressure.diskPressure) {
|
||||
"critical" -> add(stringResource(R.string.host_resource_disk_critical))
|
||||
"elevated" -> add(stringResource(R.string.host_resource_disk_elevated))
|
||||
}
|
||||
}.distinct().joinToString(" ")
|
||||
// Transient info/status banner (UiMessageBus) — thin, takes its own
|
||||
// space, auto-dismisses. Folded into the inset accounting below so a
|
||||
// child TopAppBar doesn't double-pad when this banner owns the top edge.
|
||||
@@ -1493,6 +1541,18 @@ fun RelayApp() {
|
||||
DemoModeBanner(onConnect = exitDemoToConnect)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = showHostResourcePressure,
|
||||
enter = fadeIn(tween(200)),
|
||||
exit = fadeOut(tween(200)),
|
||||
) {
|
||||
HostResourcePressureBanner(
|
||||
text = hostResourcePressureText,
|
||||
critical = hostResourcePressure.critical,
|
||||
includeStatusBarPadding = !showUnattendedBanner && !showDemoBanner,
|
||||
)
|
||||
}
|
||||
|
||||
// Connection status intentionally has NO top-of-screen surface (no
|
||||
// banner, no strip, no float). Chat/agent status rides the chat header
|
||||
// subtitle; the relay socket rides the bottom RelayStatusStrip cue. See
|
||||
@@ -1503,7 +1563,7 @@ fun RelayApp() {
|
||||
// that banner already padded the top — avoid double padding).
|
||||
MessageBannerHost(
|
||||
includeStatusBarPadding =
|
||||
!showUnattendedBanner && !showDemoBanner,
|
||||
!showUnattendedBanner && !showDemoBanner && !showHostResourcePressure,
|
||||
)
|
||||
|
||||
// The update banner AND the connection-status indicator now render as
|
||||
@@ -1543,7 +1603,8 @@ fun RelayApp() {
|
||||
// The connection-status toast is now a floating overlay and
|
||||
// doesn't occupy space above the Scaffold, so it no longer
|
||||
// participates in the top-inset accounting.
|
||||
if (showUnattendedBanner || showDemoBanner || connectionChipVisible ||
|
||||
if (showUnattendedBanner || showDemoBanner || showHostResourcePressure ||
|
||||
connectionChipVisible ||
|
||||
showMessageBanner
|
||||
) {
|
||||
Modifier.consumeWindowInsets(WindowInsets.statusBars)
|
||||
@@ -1587,7 +1648,7 @@ fun RelayApp() {
|
||||
?: AgentDisplay.displayModelName(serverModelName)
|
||||
?: stringResource(R.string.status_model_pending)
|
||||
val safetyLabel = if (BuildFlavor.isSideload && masterEnabled) {
|
||||
if (unattendedEnabled) stringResource(R.string.status_safety_unattended)
|
||||
if (unattendedEnabled && timedScreenControlActive) stringResource(R.string.status_safety_unattended)
|
||||
else stringResource(R.string.status_safety_on)
|
||||
} else {
|
||||
stringResource(R.string.status_profile_format, profileLabel)
|
||||
@@ -1695,6 +1756,11 @@ fun RelayApp() {
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
navArgument(Screen.Chat.ARG_PROACTIVE_CHAT_ID) {
|
||||
type = NavType.StringType
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
),
|
||||
) { backStackEntry ->
|
||||
// Responsive bubble width based on screen width. The "Blend"
|
||||
@@ -1725,6 +1791,35 @@ fun RelayApp() {
|
||||
val requestedProfileRoute = backStackEntry.arguments
|
||||
?.getString(Screen.Chat.ARG_PROFILE)
|
||||
?.takeIf { it.isNotBlank() }
|
||||
val requestedProactiveChatId = backStackEntry.arguments
|
||||
?.getString(Screen.Chat.ARG_PROACTIVE_CHAT_ID)
|
||||
?.takeIf { it.isNotBlank() }
|
||||
val proactiveInboxEntries by connectionViewModel.inboxMessages.collectAsState()
|
||||
val phoneThreadChatIds by connectionViewModel.phoneThreadChatIds.collectAsState()
|
||||
LaunchedEffect(
|
||||
requestedProactiveChatId,
|
||||
proactiveInboxEntries,
|
||||
phoneThreadChatIds,
|
||||
) {
|
||||
val chatId = requestedProactiveChatId ?: return@LaunchedEffect
|
||||
val realSessionId = phoneThreadChatIds.entries
|
||||
.firstOrNull { it.value == chatId }
|
||||
?.key
|
||||
if (realSessionId != null) {
|
||||
chatViewModel.switchSession(realSessionId)
|
||||
} else {
|
||||
val entries = proactiveInboxEntries.filter {
|
||||
(it.connectionId == null || it.connectionId == activeConnectionId) &&
|
||||
(it.chatId ?: "phone") == chatId
|
||||
}
|
||||
if (entries.isEmpty()) return@LaunchedEffect
|
||||
chatViewModel.openProactiveThread(chatId, entries)
|
||||
}
|
||||
backStackEntry.arguments?.putString(
|
||||
Screen.Chat.ARG_PROACTIVE_CHAT_ID,
|
||||
null,
|
||||
)
|
||||
}
|
||||
LaunchedEffect(
|
||||
requestedSessionId,
|
||||
requestedProfileRoute,
|
||||
@@ -1739,12 +1834,18 @@ fun RelayApp() {
|
||||
.InteractionRequestNotifier.DEFAULT_PROFILE_ROUTE_VALUE
|
||||
}
|
||||
if (!profileSelectionSettled) return@LaunchedEffect
|
||||
if (!connectionViewModel.isProfileSelectionAllowed(targetProfile)) {
|
||||
backStackEntry.arguments?.putString(Screen.Chat.ARG_SESSION_ID, null)
|
||||
backStackEntry.arguments?.putString(Screen.Chat.ARG_PROFILE, null)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
if (effectiveSessionProfileName != targetProfile) {
|
||||
val selection = targetProfile?.let { name ->
|
||||
agentProfiles.firstOrNull { it.name == name }
|
||||
}
|
||||
if (targetProfile == null || selection != null) {
|
||||
connectionViewModel.selectProfile(selection)
|
||||
chatViewModel.activateGatewayProfile(selection)
|
||||
}
|
||||
return@LaunchedEffect
|
||||
}
|
||||
@@ -2241,6 +2342,7 @@ fun RelayApp() {
|
||||
composable(Screen.BridgeSafetySettings.route) {
|
||||
if (BuildFlavor.isSideload) {
|
||||
BridgeSafetySettingsScreen(
|
||||
connectionId = activeConnectionId,
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
} else {
|
||||
@@ -2518,6 +2620,13 @@ fun RelayApp() {
|
||||
onBack = { navController.popBackStack() },
|
||||
onBrowsePetdex = { navController.navigate(Screen.PetdexBrowse.route) },
|
||||
onCreatePet = { navController.navigate(Screen.CustomPetGuide.route) },
|
||||
onOpenCustomTheme = { navController.navigate(Screen.CustomTheme.route) },
|
||||
)
|
||||
}
|
||||
composable(Screen.CustomTheme.route) {
|
||||
CustomThemeScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Screen.PetdexBrowse.route) {
|
||||
@@ -2619,7 +2728,8 @@ fun RelayApp() {
|
||||
val sectionArg = backStackEntry.arguments
|
||||
?.getString(Screen.ProfileInspector.ARG_SECTION)
|
||||
?: Screen.ProfileInspector.SECTION_CONFIG
|
||||
if (coldStartAuthState !is AuthState.Paired) {
|
||||
val inspectorGatewayClient = connectionViewModel.activeGatewayChatClient()
|
||||
if (coldStartAuthState !is AuthState.Paired && inspectorGatewayClient == null) {
|
||||
PowerFeatureGateScreen(
|
||||
title = stringResource(R.string.screen_profile_inspector_label),
|
||||
summary = stringResource(R.string.power_gate_profile_inspector_summary),
|
||||
@@ -2647,8 +2757,18 @@ fun RelayApp() {
|
||||
// SavedStateHandle contains our
|
||||
// `profileName` arg automatically.
|
||||
val ssh = extras.createSavedStateHandle()
|
||||
// Freeze both transports to the connection that
|
||||
// owned this nav entry. A later connection/profile
|
||||
// switch cannot redirect an open editor's writes.
|
||||
val relayUrl = connectionViewModel.effectiveRelayUrl.value
|
||||
val relayToken = (connectionViewModel.authState.value as? AuthState.Paired)?.token
|
||||
return ProfileInspectorViewModel(
|
||||
client = profileInspectorClient,
|
||||
legacyClient = RelayProfileInspectorClient(
|
||||
okHttpClient = profileInspectorHttpClient,
|
||||
relayUrlProvider = { relayUrl },
|
||||
sessionTokenProvider = { relayToken },
|
||||
),
|
||||
gatewayClient = inspectorGatewayClient,
|
||||
savedStateHandle = ssh,
|
||||
) as T
|
||||
}
|
||||
@@ -2748,6 +2868,13 @@ fun RelayApp() {
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(WindowInsets.statusBars),
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = showCandidateBanner,
|
||||
enter = slideInVertically(tween(220)) { -it } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { -it } + fadeOut(tween(160)),
|
||||
) {
|
||||
CandidateBuildBanner()
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = availableUpdateStatus != null && !suppressGlobalChrome &&
|
||||
!showStartupSphere && !voiceUiState.voiceMode,
|
||||
|
||||
+39
-19
@@ -79,6 +79,7 @@ import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.auth.AuthState
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
@@ -407,7 +408,7 @@ fun ActiveCardFeaturesSection(
|
||||
)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)) {
|
||||
@@ -449,7 +450,7 @@ fun ActiveCardFeaturesSection(
|
||||
)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
@@ -657,7 +658,7 @@ fun ActiveCardAdvancedSection(
|
||||
if (apiEditorOpen) {
|
||||
Surface(
|
||||
color = Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Column(
|
||||
@@ -675,7 +676,7 @@ fun ActiveCardAdvancedSection(
|
||||
} else {
|
||||
Surface(
|
||||
color = Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
@@ -710,7 +711,7 @@ fun ActiveCardAdvancedSection(
|
||||
if (apiHelpOpen) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
shape = appearanceRoundedCornerShape(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.active_section_api_key_explainer),
|
||||
@@ -749,7 +750,7 @@ fun ActiveCardAdvancedSection(
|
||||
if (relayEditorOpen) {
|
||||
Surface(
|
||||
color = Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Column(
|
||||
@@ -791,7 +792,7 @@ fun ActiveCardAdvancedSection(
|
||||
if (pairingOpen) {
|
||||
Surface(
|
||||
color = Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
@@ -821,12 +822,21 @@ private fun ManualUrlSubsection(
|
||||
val apiServerUrl by connectionViewModel.apiServerUrl.collectAsState()
|
||||
val relayUrl by connectionViewModel.relayUrl.collectAsState()
|
||||
val apiKeyPresent by connectionViewModel.authManager.apiKeyPresent.collectAsState()
|
||||
val savedApiKeyError by connectionViewModel.authManager.apiKeyError.collectAsState()
|
||||
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
||||
|
||||
// Keyed on the backing URL so a connection switch refreshes the input.
|
||||
var apiUrlInput by remember(apiServerUrl) { mutableStateOf(apiServerUrl) }
|
||||
var apiKeyInput by remember { mutableStateOf("") }
|
||||
var apiKeyVisible by remember { mutableStateOf(false) }
|
||||
val apiKeySingleLineError = stringResource(R.string.api_credential_single_line_error)
|
||||
val inputApiKeyError = remember(apiKeyInput, apiKeySingleLineError) {
|
||||
if (apiKeyInput.trim(' ', '\t').any { it < '!' || it > '~' }) {
|
||||
apiKeySingleLineError
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
var relayUrlInput by remember(relayUrl) { mutableStateOf(relayUrl) }
|
||||
var isTestingApi by remember { mutableStateOf(false) }
|
||||
var apiVoiceSetupResult by remember {
|
||||
@@ -900,13 +910,14 @@ private fun ManualUrlSubsection(
|
||||
},
|
||||
supportingText = {
|
||||
Text(
|
||||
if (apiKeyPresent && apiKeyInput.isBlank()) {
|
||||
inputApiKeyError ?: savedApiKeyError ?: if (apiKeyPresent && apiKeyInput.isBlank()) {
|
||||
apiKeyStoredHint
|
||||
} else {
|
||||
apiKeyNeededHint
|
||||
},
|
||||
)
|
||||
},
|
||||
isError = inputApiKeyError != null || (apiKeyInput.isBlank() && savedApiKeyError != null),
|
||||
singleLine = true,
|
||||
visualTransformation = if (apiKeyVisible) {
|
||||
VisualTransformation.None
|
||||
@@ -962,7 +973,7 @@ private fun ManualUrlSubsection(
|
||||
).show()
|
||||
}
|
||||
},
|
||||
enabled = apiUrlInput.isNotBlank() && !isTestingApi,
|
||||
enabled = apiUrlInput.isNotBlank() && !isTestingApi && inputApiKeyError == null,
|
||||
) {
|
||||
Text(saveAndTestText)
|
||||
}
|
||||
@@ -1339,7 +1350,7 @@ private fun ManualPairingCodeSubsection(
|
||||
ManualPairStep(number = 2, title = step2RunCommand) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shape = RoundedCornerShape(6.dp),
|
||||
shape = appearanceRoundedCornerShape(6.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
@@ -1481,7 +1492,7 @@ fun ActiveCardSecurityPosture(
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
@@ -1570,7 +1581,7 @@ fun ActiveCardSecurityPosture(
|
||||
Text(text = stringResource(R.string.active_section_access), style = MaterialTheme.typography.titleSmall)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
@@ -1739,7 +1750,10 @@ fun ActiveCardRoutesSection(
|
||||
var routeEditorOriginal by remember(connection.id) {
|
||||
mutableStateOf<EndpointCandidate?>(null)
|
||||
}
|
||||
val hasTailscaleRoute = endpoints.any { it.role.equals("tailscale", ignoreCase = true) }
|
||||
val hasTailscaleRoute = hasConfiguredTailscaleRoute(
|
||||
endpoints = endpoints,
|
||||
primaryEndpointUrl = connection.primaryEndpointUrl,
|
||||
)
|
||||
val tailscalePreferred = preferredRole?.equals("tailscale", ignoreCase = true) == true
|
||||
val routeNeedsAttention = activeEndpoint == null && liveState != RelayUiState.Connected
|
||||
val showTailscaleUnavailableHint =
|
||||
@@ -1803,7 +1817,7 @@ fun ActiveCardRoutesSection(
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surface.copy(alpha = 0.5f)
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
@@ -1848,7 +1862,7 @@ fun ActiveCardRoutesSection(
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
},
|
||||
shape = RoundedCornerShape(6.dp),
|
||||
shape = appearanceRoundedCornerShape(6.dp),
|
||||
) {
|
||||
Text(
|
||||
text = if (dashboardReachable) {
|
||||
@@ -1942,7 +1956,7 @@ fun ActiveCardRoutesSection(
|
||||
if (showTailscaleUnavailableHint) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
shape = appearanceRoundedCornerShape(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
@@ -1991,7 +2005,7 @@ fun ActiveCardRoutesSection(
|
||||
// up. Offer the route editor directly.
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
shape = appearanceRoundedCornerShape(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
@@ -2053,7 +2067,7 @@ fun ActiveCardRoutesSection(
|
||||
)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
@@ -2090,7 +2104,7 @@ fun ActiveCardRoutesSection(
|
||||
}
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
@@ -2171,6 +2185,12 @@ fun ActiveCardRoutesSection(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun hasConfiguredTailscaleRoute(
|
||||
endpoints: List<EndpointCandidate>,
|
||||
primaryEndpointUrl: String,
|
||||
): Boolean = endpoints.any { it.role.equals("tailscale", ignoreCase = true) } ||
|
||||
Connection.inferRouteRole(primaryEndpointUrl) == "tailscale"
|
||||
|
||||
/**
|
||||
* Numbered step row for the Manual pairing code fallback. Tightly
|
||||
* coupled to its Card 3 layout — step badge sizing + content shape —
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user