Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0509e122ff | ||
|
|
57cc10835f | ||
|
|
8b12a056eb | ||
|
|
d8a6bf0ce6 | ||
|
|
9e96111813 | ||
|
|
42efc01d58 | ||
|
|
dc93d5eab2 | ||
|
|
cafbadc583 | ||
|
|
607c26660c | ||
|
|
3882b857e3 | ||
|
|
81c186c6ba | ||
|
|
4ad0709fbe | ||
|
|
0324c9f5dd | ||
|
|
f8c31f8b59 | ||
|
|
abb4bc0ced | ||
|
|
07b683fbb5 | ||
|
|
759ac490c9 | ||
|
|
150e375284 | ||
|
|
1f49f08dbe | ||
|
|
e96aa435f2 | ||
|
|
592affca40 | ||
|
|
7e5123b22f | ||
|
|
ad3786fb0b | ||
|
|
8bd67e3363 | ||
|
|
17cf12fff9 | ||
|
|
b55e798c3b | ||
|
|
a128e910f1 | ||
|
|
a7cbf377a0 | ||
|
|
9435d43b04 | ||
|
|
52170f76ea | ||
|
|
9871b0cb7c | ||
|
|
14500096c6 | ||
|
|
1ea84630d2 | ||
|
|
d98e0b113b | ||
|
|
ea2110fa14 | ||
|
|
43357a387d | ||
|
|
336475e451 | ||
|
|
13492610a8 | ||
|
|
4e75564d33 | ||
|
|
50adab99fa | ||
|
|
284f19d62d | ||
|
|
1302da4846 | ||
|
|
dc8e076836 | ||
|
|
ce5f9c7c98 | ||
|
|
ad4e9d7b81 | ||
|
|
774ab90ad5 | ||
|
|
b296b56bce | ||
|
|
a74ad0738f | ||
|
|
6bb186ee2b | ||
|
|
db4a6f37c7 | ||
|
|
0f19deae7f | ||
|
|
fa2d17338d | ||
|
|
bc2f2b0010 | ||
|
|
dcc8d54916 | ||
|
|
a1cc34e649 | ||
|
|
47e27f6ac9 | ||
|
|
e7f882f8b5 | ||
|
|
5e53d5cfd1 | ||
|
|
b21b9c225c | ||
|
|
971a9a7e39 | ||
|
|
635aaa44e7 | ||
|
|
e088469dbf | ||
|
|
2d202bdeac | ||
|
|
798441c1e1 | ||
|
|
b424678f44 | ||
|
|
d5210bcd5e | ||
|
|
6458a854a8 | ||
|
|
65fe37a2ba | ||
|
|
9ac10cf645 | ||
|
|
bd904e26e4 | ||
|
|
ba5a2c82a5 | ||
|
|
6119f3ba79 | ||
|
|
2bcdca09e9 | ||
|
|
e2e9cc72b7 | ||
|
|
ca555fd617 | ||
|
|
3b5e61e149 | ||
|
|
1d25985aca | ||
|
|
500cc83de6 | ||
|
|
7d3c761c6a | ||
|
|
2e097035fb | ||
|
|
280c20dbca | ||
|
|
86a570e72d | ||
|
|
cbe811fb52 | ||
|
|
ac2508c5ce | ||
|
|
2ad7de4cc9 | ||
|
|
5eb5d198f4 | ||
|
|
7a86b9cee7 | ||
|
|
60f93994f5 | ||
|
|
52e0e38a81 | ||
|
|
471595240b | ||
|
|
061512d330 | ||
|
|
1c59f44ad7 | ||
|
|
269a2b5b36 | ||
|
|
a6879aac6f | ||
|
|
a04930c946 | ||
|
|
b71fea701f | ||
|
|
af54cdddb3 | ||
|
|
a717278e95 | ||
|
|
19d5237ebb | ||
|
|
6fbb21f437 | ||
|
|
c7f54321ad | ||
|
|
e6b9933d46 | ||
|
|
c27ee439ef | ||
|
|
68fce1b1da | ||
|
|
4547031bba | ||
|
|
41e9acf4c2 | ||
|
|
a5f671c06c | ||
|
|
5372fc1fef | ||
|
|
6c5ecbb028 | ||
|
|
bd5a1c3335 | ||
|
|
2c740c9f04 | ||
|
|
3ec89680ed | ||
|
|
42860d38cd | ||
|
|
ef4b3bdb6c | ||
|
|
44bbb16cd3 | ||
|
|
1f5b7e68fc | ||
|
|
4bb8d6fa7b | ||
|
|
6395e73927 | ||
|
|
c956232b96 | ||
|
|
9814cdca55 | ||
|
|
0c337c9384 | ||
|
|
273e3f5aff | ||
|
|
179080d6d9 | ||
|
|
ac1f42b7d5 | ||
|
|
88591fca89 | ||
|
|
00c5f5daa2 | ||
|
|
69b6c005cd | ||
|
|
c902215a15 | ||
|
|
d39368bc51 | ||
|
|
414dc08b9f | ||
|
|
3b78a17bd7 | ||
|
|
a5efb9ec96 | ||
|
|
e5228f2089 | ||
|
|
c738a2c2c0 | ||
|
|
8ed6b35e76 | ||
|
|
c6d4a15226 | ||
|
|
22c8f76c72 | ||
|
|
a0161f51ef | ||
|
|
7aa3b1c697 | ||
|
|
e7112dda9e | ||
|
|
c1413c494f | ||
|
|
bb23e6ab48 | ||
|
|
816638b46a | ||
|
|
df0fe59b0b | ||
|
|
df4d4c8f2a | ||
|
|
398ad253f1 | ||
|
|
ad4bbb2c86 | ||
|
|
7c5894213d | ||
|
|
82c088aa89 | ||
|
|
ed599995d6 | ||
|
|
75feb55adf | ||
|
|
e20540d16f | ||
|
|
c932adbc7b | ||
|
|
23cec497ce | ||
|
|
1739dc36a2 | ||
|
|
c917a94fcb | ||
|
|
e1a72ee8af | ||
|
|
94f9ba4305 | ||
|
|
3186afdde8 | ||
|
|
0261a342cf | ||
|
|
f4c212f800 | ||
|
|
3bb294c6c3 | ||
|
|
dc73cc74b1 | ||
|
|
607bc95b73 | ||
|
|
3b4da0305e | ||
|
|
3af0092b8f | ||
|
|
9cfa4c8b8c | ||
|
|
a7c860a2e3 | ||
|
|
ed71b02b01 | ||
|
|
a90dc85466 | ||
|
|
67a60143cb | ||
|
|
c3276fa7e5 | ||
|
|
99ac20de35 | ||
|
|
0650102230 | ||
|
|
8d4f324717 | ||
|
|
c9ee5348bf | ||
|
|
ee2a7840a2 | ||
|
|
52dd399565 | ||
|
|
86a0421163 | ||
|
|
0e191f946d | ||
|
|
065912f2bf | ||
|
|
075138433e | ||
|
|
92e65bbfc2 | ||
|
|
7ccd4ac4c9 | ||
|
|
5739e17750 | ||
|
|
037f4e91c8 | ||
|
|
685c3c5a24 | ||
|
|
6dc18abc4d | ||
|
|
ee43a87cec | ||
|
|
ce961b81d9 | ||
|
|
c7b392b26f | ||
|
|
0a04efbbcf | ||
|
|
11977dad56 | ||
|
|
c8fea9c061 | ||
|
|
b0a8909dc7 | ||
|
|
57c236e7da | ||
|
|
8156a821eb | ||
|
|
b015acb063 | ||
|
|
f4b366389b | ||
|
|
e6368dada8 | ||
|
|
e55662e0e1 | ||
|
|
051844bc14 | ||
|
|
1e5ce986be | ||
|
|
06b24631e3 | ||
|
|
2d2e54ba79 | ||
|
|
ee59149b41 | ||
|
|
23a6231b20 | ||
|
|
a4fac4550a | ||
|
|
88ab48cfc0 | ||
|
|
7c03f8554f | ||
|
|
367e5d271c | ||
|
|
47a395ab76 | ||
|
|
e7cbed3c8f | ||
|
|
2f7bd843bc | ||
|
|
d1527d47e4 | ||
|
|
bc0853360a | ||
|
|
b72ab5aef2 | ||
|
|
40fcb80a7d | ||
|
|
ff64548085 | ||
|
|
35362b8895 | ||
|
|
ff7ca89b90 | ||
|
|
042f02b852 | ||
|
|
5fc85c1699 | ||
|
|
c01c6cf457 | ||
|
|
22780881e1 | ||
|
|
201e204290 | ||
|
|
eb8434e508 | ||
|
|
597b13e2db | ||
|
|
946b333109 | ||
|
|
8b3731b22f | ||
|
|
b76ba7a314 | ||
|
|
2c15bd4207 | ||
|
|
949add15b1 | ||
|
|
6a93d13ecb | ||
|
|
cbc02bb407 | ||
|
|
525f6b5fc0 | ||
|
|
de8f5558c2 | ||
|
|
58e8b1edb6 | ||
|
|
adcf4ded79 | ||
|
|
05d6ee4d7c | ||
|
|
d42fa91698 | ||
|
|
41cbafddba | ||
|
|
a2be512c45 | ||
|
|
6a66710763 | ||
|
|
8632ced503 | ||
|
|
ae18bbee24 | ||
|
|
9690071e7d | ||
|
|
698b45cbb3 | ||
|
|
55a838cb78 | ||
|
|
afa875d89f | ||
|
|
aff758fb99 | ||
|
|
8625963846 | ||
|
|
d367cd3a24 | ||
|
|
5bd0b2acaf | ||
|
|
6f0948ca01 | ||
|
|
541a7c078d | ||
|
|
e0b726de85 | ||
|
|
8865a31013 | ||
|
|
a199c35377 | ||
|
|
6a495b6e06 | ||
|
|
105da550e7 | ||
|
|
23c06d60b9 | ||
|
|
febc26fe35 | ||
|
|
28a906215d | ||
|
|
1617f75f1a | ||
|
|
dbf71a87f4 | ||
|
|
95ed8e6edb | ||
|
|
d26bf6c25b | ||
|
|
181e10f2ad | ||
|
|
78203fd8a1 | ||
|
|
c519502551 | ||
|
|
814afc56da | ||
|
|
1f055cb91f | ||
|
|
936b9bed8a | ||
|
|
dafa6f3a18 | ||
|
|
245362d58e | ||
|
|
857a1551f3 | ||
|
|
95e78e0657 | ||
|
|
00052d20d9 | ||
|
|
246d9f1010 | ||
|
|
e9f32673be | ||
|
|
7b390fa99f | ||
|
|
cd856da6a0 | ||
|
|
9a40aedb7d | ||
|
|
30eb70daa3 | ||
|
|
6be6cec201 | ||
|
|
4f5f3fac10 | ||
|
|
7f7112caf2 | ||
|
|
4c00e8edb7 | ||
|
|
44f0acec94 | ||
|
|
c8cd13e5bc | ||
|
|
ad4175bb6d | ||
|
|
6b7cb706e0 | ||
|
|
6031427ffb | ||
|
|
53dd21400a | ||
|
|
802a0b0844 | ||
|
|
7658329ca7 | ||
|
|
1622db0b23 | ||
|
|
41b724e072 | ||
|
|
2ec7b7aac9 | ||
|
|
bca3cd0e48 | ||
|
|
bb2f1e6c0c | ||
|
|
ff23d54332 | ||
|
|
a4a0575688 | ||
|
|
0509ac8377 | ||
|
|
3fdc2260dd | ||
|
|
1800bee7b1 | ||
|
|
4317b7c2b3 | ||
|
|
93fb30150e | ||
|
|
faf4281486 | ||
|
|
11dcafc2fe | ||
|
|
a57b2b66a1 | ||
|
|
f4acd351f5 | ||
|
|
8ee772f5fb | ||
|
|
6c27bc9cda | ||
|
|
460d6cd198 | ||
|
|
ce63030bcf | ||
|
|
bd9c077599 | ||
|
|
92f99a4120 | ||
|
|
85ba13bd04 | ||
|
|
81347e9c28 | ||
|
|
8d260c0eeb | ||
|
|
ea982c60d4 | ||
|
|
8f394e8b18 | ||
|
|
841e237905 | ||
|
|
6aad90144f | ||
|
|
c5df87cd28 | ||
|
|
01533337eb | ||
|
|
a4a0fb5741 | ||
|
|
a2ed48ab20 | ||
|
|
ef280979e9 | ||
|
|
0bb0a1e3e2 | ||
|
|
6421d47c96 | ||
|
|
523794995a | ||
|
|
1c9af237fb | ||
|
|
ea7c7cd3e2 | ||
|
|
41fa23a7f9 | ||
|
|
c6ad31972c | ||
|
|
7091fd7a4a | ||
|
|
9b903c87dc | ||
|
|
a05cc3c941 | ||
|
|
6dfa94b65e | ||
|
|
cef0771980 | ||
|
|
b900148f7f | ||
|
|
291fe2e88b | ||
|
|
e629cb4947 | ||
|
|
74100fb249 | ||
|
|
8aa27d6084 | ||
|
|
a894da5fda | ||
|
|
17446f13d0 | ||
|
|
89f2f772e2 | ||
|
|
3ae19758e4 | ||
|
|
734f8074d5 | ||
|
|
46502c1785 | ||
|
|
70b9c4e4e3 | ||
|
|
5e10864795 | ||
|
|
c8351e03c1 | ||
|
|
808dfd12a5 | ||
|
|
9ce41e366a | ||
|
|
4884d077b3 | ||
|
|
f47ca00998 | ||
|
|
e23ab3fbdf | ||
|
|
b862a0a875 | ||
|
|
318a02db49 | ||
|
|
80e636bc30 | ||
|
|
578c074797 | ||
|
|
23fa69e8d1 | ||
|
|
d688043a52 | ||
|
|
10f62d798c | ||
|
|
d80b3db329 | ||
|
|
d1e78f7e1c | ||
|
|
a1d8419dcd | ||
|
|
258e6f5390 | ||
|
|
76ead50c60 | ||
|
|
0213dbf5db | ||
|
|
3bddb6fc70 | ||
|
|
729d9ea620 | ||
|
|
0ef67814cf | ||
|
|
ee3b31d8ea | ||
|
|
6e95f6fe83 | ||
|
|
08ef5cd08e | ||
|
|
834763a213 | ||
|
|
e483617c09 | ||
|
|
8ef6b794b2 | ||
|
|
17d8a2374a | ||
|
|
274ae11160 | ||
|
|
9cebdb67e6 | ||
|
|
95aca51bd5 | ||
|
|
eb94bc92f2 | ||
|
|
4c0b3038de | ||
|
|
380a604ba5 | ||
|
|
20d7bfe633 | ||
|
|
ee300b3b15 | ||
|
|
68520549a1 | ||
|
|
2b75577fcf | ||
|
|
ff2f94922b | ||
|
|
711b2f945b | ||
|
|
526c5be5ae | ||
|
|
8e2f7d7084 | ||
|
|
ee98432095 | ||
|
|
b432e90dc0 | ||
|
|
aab1555004 | ||
|
|
a5ec94f669 | ||
|
|
7621b762e7 | ||
|
|
78b0f8c10c | ||
|
|
bb47acd8f6 | ||
|
|
7d4a0b6096 | ||
|
|
d3ff0ef3f7 | ||
|
|
0c5d61dfc1 | ||
|
|
ab8a300e8d | ||
|
|
5fa2416cf3 | ||
|
|
f350fe0b82 | ||
|
|
7ce0825f69 | ||
|
|
47b471acb4 | ||
|
|
3465b0b2a9 | ||
|
|
292cc94eb4 | ||
|
|
44d8fea138 | ||
|
|
3ff307ac6d | ||
|
|
621081b633 | ||
|
|
da8e822b66 | ||
|
|
0015a913f1 | ||
|
|
0f47e464f3 | ||
|
|
2411cf19b3 | ||
|
|
51b4edd52a | ||
|
|
d3c4e90696 | ||
|
|
26c8658eb7 | ||
|
|
cd7cad03ec | ||
|
|
6e2b2d6ca6 | ||
|
|
bea3021ef0 | ||
|
|
00a9a7efcb | ||
|
|
d8fbcd6b16 | ||
|
|
7a97b71844 | ||
|
|
ae51ae3ab1 | ||
|
|
1bdcab8fc0 | ||
|
|
0c77d010fa | ||
|
|
0c6edb3fe5 | ||
|
|
dc18209c3c | ||
|
|
69347adb34 | ||
|
|
43a809e41a | ||
|
|
a5cc0104bf | ||
|
|
86a0bebc0d | ||
|
|
04d9421c74 | ||
|
|
14401aa3c3 | ||
|
|
99897274c6 | ||
|
|
20c5b690a8 | ||
|
|
dc86c043bc | ||
|
|
d5cce4e390 | ||
|
|
ae9b22a9e6 | ||
|
|
96a9e8077e | ||
|
|
a97e6a2b14 | ||
|
|
4317da85fd | ||
|
|
45fde0ad9a | ||
|
|
94565e9d6d | ||
|
|
56c2e6fa07 | ||
|
|
28629f3d93 | ||
|
|
c9a5c767c6 | ||
|
|
0d1faf47a0 | ||
|
|
00288a2b3b | ||
|
|
8f52feffba | ||
|
|
524e319f95 | ||
|
|
647d1f9aea | ||
|
|
ee29e49361 | ||
|
|
e2073b7692 | ||
|
|
70b6d8ee5a | ||
|
|
1f5e50ccd7 | ||
|
|
5580c9d9bb | ||
|
|
2ebdf55501 | ||
|
|
ad107ea205 | ||
|
|
f5aeb27e5a | ||
|
|
fdaeb121d5 | ||
|
|
06c0df6304 | ||
|
|
71a2b3a7fb | ||
|
|
08545ed32d | ||
|
|
e791c6410b | ||
|
|
8c8c3975f2 | ||
|
|
41601d67ab | ||
|
|
366b424615 | ||
|
|
5cd9baaaab | ||
|
|
8acba9b353 | ||
|
|
26a612f088 | ||
|
|
65e48084cb | ||
|
|
1074ecc24f | ||
|
|
6dd6ce2d13 | ||
|
|
f2a23e32aa | ||
|
|
b60c5d9eeb | ||
|
|
9e201e54d7 | ||
|
|
630cc6d316 | ||
|
|
8bb503eb6d | ||
|
|
c223dc690d | ||
|
|
e16205d82a | ||
|
|
44e3bb75cd | ||
|
|
4834fcbdf5 | ||
|
|
1cec79517e | ||
|
|
676c37e5ca | ||
|
|
957be876a0 | ||
|
|
6b32c7aeef | ||
|
|
29706e1548 | ||
|
|
6579b621ff | ||
|
|
9b6fed9bdd | ||
|
|
4d90eef3d8 | ||
|
|
befe8399ab | ||
|
|
c10b87b94c | ||
|
|
478323893a | ||
|
|
5e9d8840ae | ||
|
|
e3512b9fa1 | ||
|
|
40eff9c5c6 | ||
|
|
accf464911 | ||
|
|
b26c2cc2a1 | ||
|
|
28e0c34227 | ||
|
|
35e95da6a7 | ||
|
|
484bfdc5dc | ||
|
|
fcddeeb810 | ||
|
|
49002b7141 | ||
|
|
326eb47df3 | ||
|
|
c7c24b2874 | ||
|
|
3e8e0728db | ||
|
|
b12712a79a | ||
|
|
1658439d05 | ||
|
|
ef1abdae3f | ||
|
|
eece12a815 | ||
|
|
0cdea3ad33 | ||
|
|
a8ca61297d | ||
|
|
5762cdf8af | ||
|
|
dff633c902 | ||
|
|
45d8a73609 | ||
|
|
390a4dd8d8 | ||
|
|
90ab705a88 | ||
|
|
054aab1c09 | ||
|
|
bae1762951 | ||
|
|
27705d8291 | ||
|
|
da7ea8ffe0 | ||
|
|
5c5c55d982 | ||
|
|
0208098687 | ||
|
|
34fc4c4693 |
@@ -1,38 +0,0 @@
|
||||
## Summary
|
||||
|
||||
<!-- Brief description of what this PR does -->
|
||||
|
||||
## Changes
|
||||
|
||||
-
|
||||
|
||||
## Verification
|
||||
|
||||
<!-- List the checks you ran, or explain why a check is not applicable. -->
|
||||
|
||||
-
|
||||
|
||||
## Lineage / contributor credit
|
||||
|
||||
<!--
|
||||
If this PR salvages or supersedes earlier work, link every source PR and name
|
||||
the original contributor(s). Preserve original commit authors where practical;
|
||||
otherwise use verified Co-authored-by trailers. Write "N/A" for original work.
|
||||
-->
|
||||
|
||||
- Source PR(s): N/A
|
||||
- Attribution preserved by: N/A
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Target branch is `dev`, unless this is a `dev` → `main` release PR or a focused production-tag hotfix PR to `main`
|
||||
- [ ] Android changes: lint and focused unit tests ran, or rationale is listed above
|
||||
- [ ] Translation changes: locale status/review references are accurate, `python scripts/check-android-locales.py` ran, and device/emulator review is documented, or N/A
|
||||
- [ ] Server changes: focused `python -m unittest ...` checks ran, or rationale is listed above
|
||||
- [ ] Desktop changes: `npm run build` or a narrower documented check ran, or rationale is listed above
|
||||
- [ ] Docs/site changes: docs build or link check ran, or rationale is listed above
|
||||
- [ ] UI changes were tested on emulator/device or desktop surface when applicable
|
||||
- [ ] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
|
||||
- [ ] CHANGELOG.md updated (if user-facing)
|
||||
- [ ] Public writing hygiene checked: no secrets, private infrastructure, personal names, or AI/process narration
|
||||
- [ ] Salvaged work links the source PR and preserves contributor authorship, or N/A
|
||||
@@ -5,9 +5,8 @@ not `AGENTS.md`) picks up the project's agent guidance.
|
||||
|
||||
**Read [AGENTS.md](../AGENTS.md) first — it is the single source of truth**
|
||||
for agent guidance: the entry point, the non-negotiables, and the public-repo
|
||||
writing hygiene. It links on to `CLAUDE.md` for the deep reference
|
||||
(architecture, upstream Hermes API, repository layout, per-language code style,
|
||||
the dev loop, and the Key Files map). Follow those; don't restate them here.
|
||||
writing hygiene. `CLAUDE.md` imports that same canonical file. Follow
|
||||
`AGENTS.md` and its linked project records; don't restate them here.
|
||||
|
||||
Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
|
||||
|
||||
@@ -17,6 +16,8 @@ Quick non-negotiables (the full list and rationale are in `AGENTS.md`):
|
||||
- **Conventional Commits**, `main`/`dev` branching — feature branches off
|
||||
`dev`, `--no-ff` merges, tags cut from `main`.
|
||||
- **Android:** Jetpack Compose (no XML), kotlinx.serialization (no Gson),
|
||||
OkHttp (no Ktor), `wss://` only; run `./gradlew lint` before pushing Kotlin.
|
||||
OkHttp (no Ktor), `wss://` only. Narrow local checks use the Android lane;
|
||||
pushed exact SHAs prefer `Android On-Demand` for heavy verification; full
|
||||
local pre-push remains an explicit fallback.
|
||||
- **Public repo:** no personal names, no private infrastructure, no
|
||||
AI/assistant self-narration in committed prose.
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
## Summary
|
||||
|
||||
<!-- Describe the user/developer outcome and why this change is needed. Link related issues, e.g. Closes #123. -->
|
||||
|
||||
## Changes
|
||||
|
||||
<!-- List the focused implementation changes. Avoid repeating the commit log. -->
|
||||
|
||||
-
|
||||
|
||||
## Verification
|
||||
|
||||
<!-- List exact commands and results. Say explicitly when a check was not run or when device/UI proof remains outstanding. -->
|
||||
|
||||
-
|
||||
|
||||
## Screenshots
|
||||
|
||||
<!-- UI change: include screenshots/video plus device, viewport, or emulator details. Otherwise write: No visual change. -->
|
||||
|
||||
## Compatibility / risk
|
||||
|
||||
<!-- Note Standard Hermes/upstream compatibility, migrations/state changes, security/privacy impact, rollout/rollback, or write N/A. -->
|
||||
|
||||
## Lineage / contributor credit
|
||||
|
||||
<!-- Preserve prior contributor work when replacing, salvaging, or rebuilding another PR. -->
|
||||
|
||||
- Source PR(s): N/A
|
||||
- Attribution preserved by: N/A
|
||||
|
||||
## Checklist
|
||||
|
||||
<!-- Check an item when satisfied or when its N/A rationale is stated above. -->
|
||||
|
||||
- [ ] Target branch is `dev`, unless this is a `dev` → `main` release PR or a focused production-tag hotfix PR to `main`
|
||||
- [ ] Scope is focused and related issues/PRs are linked
|
||||
- [ ] Android changes: lint and focused tests ran, or rationale is listed above
|
||||
- [ ] Translation changes: locale validation/review ran, or N/A is listed above
|
||||
- [ ] Server/plugin changes: focused tests ran, or N/A/rationale is listed above
|
||||
- [ ] Desktop changes: build/tests ran, or N/A/rationale is listed above
|
||||
- [ ] Docs/site changes: build or link/route checks ran, or N/A/rationale is listed above
|
||||
- [ ] UI changes were tested on a relevant device/emulator/desktop surface, or the missing proof is stated above
|
||||
- [ ] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
|
||||
- [ ] `CHANGELOG.md` is updated for user-visible changes, or N/A is listed above
|
||||
- [ ] Public writing hygiene checked: no secrets, private infrastructure, personal names, or AI/process narration
|
||||
- [ ] Salvaged/replacement work links source PRs and preserves contributor authorship, or N/A is listed above
|
||||
@@ -3,29 +3,46 @@
|
||||
function classifyCiPaths(paths) {
|
||||
const forceAll = paths.some((path) => [
|
||||
'.github/workflows/ci-required.yml',
|
||||
'.github/workflows/release-backmerge.yml',
|
||||
'.github/workflows/approve-release-train.yml',
|
||||
'.github/scripts/classify-ci-paths.cjs',
|
||||
'.github/scripts/classify-ci-paths.test.cjs',
|
||||
'scripts/plan_release_backmerge.py',
|
||||
'scripts/tests/plan_release_backmerge_test.py',
|
||||
].includes(path));
|
||||
const exact = (values) => paths.some((path) => values.includes(path));
|
||||
const under = (prefixes) => paths.some((path) => prefixes.some((prefix) => path.startsWith(prefix)));
|
||||
|
||||
return {
|
||||
android: forceAll || under(['app/', 'relay-core/', 'relay-ui/', 'ui-preview/', 'quest/', 'gradle/']) || exact([
|
||||
android: forceAll || under(['app/', 'gradle/']) || exact([
|
||||
'build.gradle.kts', 'settings.gradle.kts', 'gradle.properties', 'gradlew', 'gradlew.bat',
|
||||
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
|
||||
'scripts/check-android-collection-apis.py', '.github/workflows/ci-android.yml',
|
||||
'scripts/check-android-capabilities.py', 'scripts/tests/check_android_capabilities_test.py',
|
||||
'scripts/check-android-collection-apis.py', 'scripts/check-android-native-compat.py',
|
||||
'scripts/check-android-release-notes.py',
|
||||
'scripts/android_release_artifacts.py',
|
||||
'scripts/android-lane.ps1', 'scripts/android-prepush.py', 'scripts/dev.bat', 'scripts/dev.sh',
|
||||
'scripts/tests/android_prepush_test.py',
|
||||
'scripts/tests/check_android_native_compat_test.py',
|
||||
'scripts/tests/check_android_release_notes_test.py',
|
||||
'scripts/tests/android_release_artifacts_test.py',
|
||||
'.github/workflows/android-on-demand.yml', '.github/workflows/ci-android.yml',
|
||||
'.github/workflows/play-preflight-android.yml',
|
||||
'.github/workflows/approve-release-android.yml',
|
||||
'.github/workflows/release-android.yml',
|
||||
]),
|
||||
desktop: forceAll || under(['desktop/']) || exact([
|
||||
'.github/workflows/ci-desktop.yml',
|
||||
'.github/workflows/approve-release-extensions.yml',
|
||||
'.github/workflows/release-cli.yml',
|
||||
]),
|
||||
plugin: forceAll || paths.some((path) => /^plugin\/[^/]+\.py$/.test(path)) ||
|
||||
under(['plugin/relay/', 'plugin/tools/', 'plugin/tests/', 'relay_server/', 'hermes_relay_bootstrap/']) || exact([
|
||||
'plugin/plugin.yaml', 'pyproject.toml', 'scripts/check-plugin-version-sync.py',
|
||||
'scripts/check-server-version-sync.py', 'scripts/bump-plugin-version.sh',
|
||||
'scripts/bump-server-version.sh', '.github/workflows/ci-plugin.yml',
|
||||
'.github/workflows/approve-release-extensions.yml',
|
||||
'.github/workflows/release-plugin.yml',
|
||||
]),
|
||||
dashboard: forceAll || under(['plugin/dashboard/']) || exact([
|
||||
'.github/workflows/ci-dashboard.yml',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { join } = require('node:path');
|
||||
const { classifyCiPaths } = require('./classify-ci-paths.cjs');
|
||||
|
||||
const none = {
|
||||
@@ -14,7 +16,25 @@ const none = {
|
||||
|
||||
assert.deepEqual(classifyCiPaths(['README.md']), none);
|
||||
assert.deepEqual(classifyCiPaths(['desktop/src/cli.ts']), { ...none, desktop: true });
|
||||
assert.deepEqual(classifyCiPaths(['relay-core/src/main/kotlin/Wire.kt']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['experiments/quest/src/main/kotlin/Quest.kt']), none);
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-release-notes.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-native-compat.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android_release_artifacts.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/android_release_artifacts_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_native_compat_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android-lane.ps1']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android-prepush.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/dev.bat']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/dev.sh']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/android_prepush_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/android-on-demand.yml']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/approve-release-extensions.yml']), {
|
||||
...none,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-cli.yml']), { ...none, desktop: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-plugin.yml']), { ...none, plugin: true });
|
||||
assert.deepEqual(classifyCiPaths(['plugin/relay/server.py']), { ...none, plugin: true });
|
||||
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
|
||||
assert.deepEqual(classifyCiPaths(['user-docs/index.md']), { ...none, docs: true });
|
||||
@@ -30,5 +50,84 @@ assert.deepEqual(classifyCiPaths(['.github/workflows/ci-required.yml']), {
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-backmerge.yml']), {
|
||||
android: true,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
dashboard: true,
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/approve-release-train.yml']), {
|
||||
android: true,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
dashboard: true,
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
|
||||
const repoRoot = join(__dirname, '..', '..');
|
||||
const approvalWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-extensions.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const cliReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-cli.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const pluginReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-plugin.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const desktopCiWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'ci-desktop.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidPreflightWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'play-preflight-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidApprovalWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const requiredChecksWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'ci-required.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const releaseTrainWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-train.yml'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
assert.match(approvalWorkflow, /permissions:\r?\n contents: read/);
|
||||
assert.match(
|
||||
approvalWorkflow,
|
||||
/approve:[\s\S]*?permissions:\r?\n actions: write\r?\n contents: write/,
|
||||
);
|
||||
assert.match(
|
||||
approvalWorkflow,
|
||||
/ref: \$\{\{ contains\(inputs\.version, '-'\) && 'dev' \|\| 'main' \}\}/,
|
||||
);
|
||||
assert.match(cliReleaseWorkflow, /workflow_dispatch:[\s\S]*?Approved CLI\+UI version/);
|
||||
assert.match(cliReleaseWorkflow, /name: Restore exact-source tray build cache[\s\S]*?actions\/cache@v6/);
|
||||
assert.match(desktopCiWorkflow, /name: Restore exact-source tray build cache[\s\S]*?actions\/cache@v6/);
|
||||
assert.match(pluginReleaseWorkflow, /workflow_dispatch:[\s\S]*?Approved Plugin version/);
|
||||
assert.match(androidPreflightWorkflow, /Package immutable preflight artifacts/);
|
||||
assert.match(androidApprovalWorkflow, /Android public approval accepts stable SemVer only/);
|
||||
assert.match(androidReleaseWorkflow, /Download exact stable preflight artifacts/);
|
||||
assert.match(androidReleaseWorkflow, /artifact-ids: \$\{\{ needs\.validate\.outputs\.preflight_artifact_id \}\}/);
|
||||
assert.match(requiredChecksWorkflow, /name: Reuse exact-tree required checks/);
|
||||
assert.match(requiredChecksWorkflow, /name: required-checks-\$\{\{ needs\.changes\.outputs\.tree \}\}/);
|
||||
assert.match(releaseTrainWorkflow, /name: Hermes-Relay Coordinated Release Approval/);
|
||||
assert.match(releaseTrainWorkflow, /Coordinated Android approval is stable-only/);
|
||||
|
||||
console.log('CI path classification tests passed.');
|
||||
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-capabilities.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_capabilities_test.py']), { ...none, android: true });
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
name: Android On-Demand
|
||||
|
||||
run-name: Android ${{ inputs.preset }} · ${{ inputs.head_sha }}
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
head_sha:
|
||||
required: true
|
||||
type: string
|
||||
preset:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: android-on-demand-${{ inputs.head_sha }}-${{ inputs.preset }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate exact SHA
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Validate input shape
|
||||
shell: bash
|
||||
env:
|
||||
REQUESTED_SHA: ${{ inputs.head_sha }}
|
||||
REQUESTED_PRESET: ${{ inputs.preset }}
|
||||
run: |
|
||||
if [[ ! "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "head_sha must be a full lowercase 40-character commit SHA" >&2
|
||||
exit 2
|
||||
fi
|
||||
case "$REQUESTED_PRESET" in
|
||||
focused|lint|assemble-debug|release-smoke|all-final) ;;
|
||||
*)
|
||||
echo "unsupported Android preset: $REQUESTED_PRESET" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Checkout exact commit
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ inputs.head_sha }}
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Confirm checkout identity
|
||||
shell: bash
|
||||
env:
|
||||
REQUESTED_SHA: ${{ inputs.head_sha }}
|
||||
run: test "$(git rev-parse HEAD)" = "$REQUESTED_SHA"
|
||||
|
||||
focused:
|
||||
name: Focused Android checks
|
||||
needs: validate
|
||||
if: ${{ inputs.preset == 'focused' || inputs.preset == 'all-final' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: true
|
||||
|
||||
- name: Run repository checks and focused sideload tests
|
||||
run: python3 scripts/android-prepush.py --skip-lint
|
||||
|
||||
- name: Run the same focused tests for Google Play
|
||||
shell: bash
|
||||
run: |
|
||||
mapfile -t focused_tests < <(python3 -c \
|
||||
"import runpy; print(*runpy.run_path('scripts/android-prepush.py')['FOCUSED_TESTS'], sep='\n')")
|
||||
test_args=()
|
||||
for test_name in "${focused_tests[@]}"; do
|
||||
test_args+=(--tests "$test_name")
|
||||
done
|
||||
./gradlew :app:testGooglePlayDebugUnitTest "${test_args[@]}" --console=plain
|
||||
|
||||
- name: Upload failed test reports
|
||||
uses: actions/upload-artifact@v7
|
||||
if: failure()
|
||||
with:
|
||||
name: focused-test-reports-${{ inputs.head_sha }}
|
||||
path: app/build/reports/tests/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
lint:
|
||||
name: Android lint
|
||||
needs: validate
|
||||
if: ${{ inputs.preset == 'lint' || inputs.preset == 'all-final' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: true
|
||||
|
||||
- name: Validate Android repository inputs
|
||||
run: |
|
||||
python3 scripts/check-android-locales.py
|
||||
python3 scripts/check-user-docs-locales.py
|
||||
python3 scripts/check-android-collection-apis.py
|
||||
python3 scripts/check-android-release-notes.py
|
||||
python3 scripts/check-version-tracks.py
|
||||
if [[ -f scripts/tests/android_prepush_test.py ]]; then
|
||||
python3 -m unittest scripts.tests.android_prepush_test
|
||||
fi
|
||||
python3 -m unittest scripts.tests.check_android_release_notes_test
|
||||
python3 -m unittest scripts.tests.check_android_native_compat_test
|
||||
|
||||
- name: Run Android lint
|
||||
run: ./gradlew lint --console=plain
|
||||
|
||||
- name: Upload lint reports
|
||||
uses: actions/upload-artifact@v7
|
||||
if: always()
|
||||
with:
|
||||
name: lint-reports-${{ inputs.head_sha }}
|
||||
path: app/build/reports/lint-results*
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
assemble-debug:
|
||||
name: Assemble both debug flavors
|
||||
needs: validate
|
||||
if: ${{ inputs.preset == 'assemble-debug' || inputs.preset == 'all-final' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: true
|
||||
|
||||
- name: Build debug APKs
|
||||
run: ./gradlew assembleDebug --console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayDebug
|
||||
|
||||
- name: Verify packaged native compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/debug/*.apk \
|
||||
app/build/outputs/apk/sideload/debug/*.apk
|
||||
|
||||
- name: Upload debug APKs
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: debug-apks-${{ inputs.head_sha }}
|
||||
path: app/build/outputs/apk/*/debug/*.apk
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
release-smoke:
|
||||
name: Release build smoke
|
||||
needs: validate
|
||||
if: ${{ inputs.preset == 'release-smoke' || inputs.preset == 'all-final' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 35
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: true
|
||||
|
||||
- name: Build release bundles and APKs
|
||||
run: ./gradlew bundleRelease assembleRelease --console=plain
|
||||
|
||||
- name: Verify Play release capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayRelease
|
||||
|
||||
- name: Scan release DEX for unsupported collection APIs
|
||||
run: |
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Verify packaged native compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Upload release smoke artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-smoke-${{ inputs.head_sha }}
|
||||
path: |
|
||||
app/build/outputs/apk/*/release/*.apk
|
||||
app/build/outputs/bundle/**/*.aab
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
@@ -40,6 +40,10 @@ jobs:
|
||||
echo "::error::Hermes-Relay Android Release Approval must run from main, not $GITHUB_REF"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! "$REQUESTED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::Android public approval accepts stable SemVer only: $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
TOML_VERSION=$(grep -oP 'appVersionName\s*=\s*"\K[^"]+' gradle/libs.versions.toml)
|
||||
if [ "$REQUESTED_VERSION" != "$TOML_VERSION" ]; then
|
||||
echo "::error::Requested version $REQUESTED_VERSION does not match appVersionName $TOML_VERSION"
|
||||
@@ -56,13 +60,21 @@ jobs:
|
||||
RELEASE_TREE: ${{ steps.metadata.outputs.tree }}
|
||||
run: |
|
||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
||||
if [ "$COUNT" -lt 1 ]; then
|
||||
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
RUN_ID=$(jq -r '.workflow_run.id // empty' <<<"$ARTIFACT")
|
||||
if [ -z "$RUN_ID" ]; then
|
||||
echo "::error::No successful Play preflight found for version $VERSION with tree $RELEASE_TREE"
|
||||
exit 1
|
||||
fi
|
||||
echo "Verified Play preflight proof: $ARTIFACT_NAME"
|
||||
RUN=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}")
|
||||
CONCLUSION=$(jq -r '.conclusion' <<<"$RUN")
|
||||
WORKFLOW_PATH=$(jq -r '.path' <<<"$RUN")
|
||||
if [ "$WORKFLOW_PATH" != ".github/workflows/play-preflight-android.yml" ] || [ "$CONCLUSION" != "success" ]; then
|
||||
echo "::error::Preflight artifact came from ${WORKFLOW_PATH} with conclusion ${CONCLUSION}"
|
||||
exit 1
|
||||
fi
|
||||
echo "Verified immutable Play preflight artifacts: $ARTIFACT_NAME (run $RUN_ID)"
|
||||
|
||||
- name: Ensure release tag does not already exist
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
name: Hermes-Relay Plugin and CLI+UI Release Approval
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
surface:
|
||||
description: "Release surface"
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- plugin
|
||||
- desktop
|
||||
version:
|
||||
description: "Approved version (for example 1.11.2 or 0.4.0-beta.7)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: approve-${{ inputs.surface }}-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate release source and metadata
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
source_branch: ${{ steps.metadata.outputs.source_branch }}
|
||||
source_sha: ${{ steps.metadata.outputs.source_sha }}
|
||||
tag: ${{ steps.metadata.outputs.tag }}
|
||||
workflow: ${{ steps.metadata.outputs.workflow }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ contains(inputs.version, '-') && 'dev' || 'main' }}
|
||||
|
||||
- name: Validate approval request
|
||||
id: metadata
|
||||
env:
|
||||
REQUESTED_SURFACE: ${{ inputs.surface }}
|
||||
REQUESTED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$REQUESTED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "::error::Version must be SemVer with an optional prerelease suffix: $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$REQUESTED_VERSION" == *-* ]]; then
|
||||
source_branch="dev"
|
||||
else
|
||||
source_branch="main"
|
||||
fi
|
||||
if [ "$GITHUB_REF" != "refs/heads/main" ]; then
|
||||
echo "::error::Release approval must run from the trusted main workflow definition, not $GITHUB_REF"
|
||||
exit 1
|
||||
fi
|
||||
git fetch origin "$source_branch" --no-tags
|
||||
source_sha="$(git rev-parse HEAD)"
|
||||
expected_sha="$(git rev-parse FETCH_HEAD)"
|
||||
if [ "$source_sha" != "$expected_sha" ]; then
|
||||
echo "::error::Checked out $source_sha, but origin/$source_branch is $expected_sha"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$REQUESTED_SURFACE" in
|
||||
plugin)
|
||||
tag="server-v${REQUESTED_VERSION}"
|
||||
workflow="release-plugin.yml"
|
||||
python3 scripts/check-plugin-version-sync.py --expect "$REQUESTED_VERSION"
|
||||
if ! grep -Eq "^## \[Plugin ${REQUESTED_VERSION}\]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no Plugin release heading for $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
desktop)
|
||||
tag="desktop-v${REQUESTED_VERSION}"
|
||||
workflow="release-cli.yml"
|
||||
node desktop/scripts/cli-version-sync.mjs --expect "$REQUESTED_VERSION"
|
||||
if ! grep -Fq "## [$REQUESTED_VERSION]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no CLI+UI release heading for $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
echo "::error::Unsupported release surface: $REQUESTED_SURFACE"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
echo "workflow=$workflow" >> "$GITHUB_OUTPUT"
|
||||
echo "source_branch=$source_branch" >> "$GITHUB_OUTPUT"
|
||||
echo "source_sha=$source_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
approve:
|
||||
name: Create release tag and start publication
|
||||
needs: validate
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Verify release source has not moved
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SOURCE_BRANCH: ${{ needs.validate.outputs.source_branch }}
|
||||
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
|
||||
run: |
|
||||
current_sha=$(gh api "/repos/${GITHUB_REPOSITORY}/git/ref/heads/${SOURCE_BRANCH}" --jq .object.sha)
|
||||
if [ "$current_sha" != "$SOURCE_SHA" ]; then
|
||||
echo "::error::$SOURCE_BRANCH moved from $SOURCE_SHA to $current_sha; run approval again"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Ensure release tag does not already exist
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ needs.validate.outputs.tag }}
|
||||
run: |
|
||||
if gh api "/repos/${GITHUB_REPOSITORY}/git/ref/tags/${RELEASE_TAG}" >/dev/null 2>&1; then
|
||||
echo "::error::Tag $RELEASE_TAG already exists"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create approved release tag
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ needs.validate.outputs.tag }}
|
||||
RELEASE_SHA: ${{ needs.validate.outputs.source_sha }}
|
||||
run: |
|
||||
gh api --method POST "/repos/${GITHUB_REPOSITORY}/git/refs" \
|
||||
-f ref="refs/tags/${RELEASE_TAG}" \
|
||||
-f sha="$RELEASE_SHA"
|
||||
|
||||
- name: Start the immutable tag release workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_WORKFLOW: ${{ needs.validate.outputs.workflow }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
# A tag created by GITHUB_TOKEN does not recursively start workflows.
|
||||
# Dispatch the trusted definition from main; release jobs check out
|
||||
# and validate the immutable tag created above.
|
||||
gh workflow run "$RELEASE_WORKFLOW" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f version="$RELEASE_VERSION"
|
||||
|
||||
- name: Approval summary
|
||||
run: |
|
||||
echo "## Release approved" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Created \`${{ needs.validate.outputs.tag }}\` from \`${{ needs.validate.outputs.source_branch }}\` at \`${{ needs.validate.outputs.source_sha }}\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Dispatched \`${{ needs.validate.outputs.workflow }}\` to validate and publish that immutable tag." >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -0,0 +1,120 @@
|
||||
name: Hermes-Relay Coordinated Release Approval
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
android:
|
||||
description: "Approve Hermes-Relay Android"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
android_version:
|
||||
description: "Android version when selected"
|
||||
required: false
|
||||
type: string
|
||||
plugin:
|
||||
description: "Approve Hermes-Relay Plugin"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
plugin_version:
|
||||
description: "Plugin version when selected"
|
||||
required: false
|
||||
type: string
|
||||
desktop:
|
||||
description: "Approve Hermes-Relay CLI+UI"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
desktop_version:
|
||||
description: "CLI+UI version when selected"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: approve-coordinated-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate selected release surfaces
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Require versions for every selected surface
|
||||
env:
|
||||
ANDROID: ${{ inputs.android }}
|
||||
ANDROID_VERSION: ${{ inputs.android_version }}
|
||||
PLUGIN: ${{ inputs.plugin }}
|
||||
PLUGIN_VERSION: ${{ inputs.plugin_version }}
|
||||
DESKTOP: ${{ inputs.desktop }}
|
||||
DESKTOP_VERSION: ${{ inputs.desktop_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$ANDROID" != "true" ] && [ "$PLUGIN" != "true" ] && [ "$DESKTOP" != "true" ]; then
|
||||
echo "::error::Select at least one release surface"
|
||||
exit 1
|
||||
fi
|
||||
for pair in \
|
||||
"$ANDROID:$ANDROID_VERSION:Android" \
|
||||
"$PLUGIN:$PLUGIN_VERSION:Plugin" \
|
||||
"$DESKTOP:$DESKTOP_VERSION:CLI+UI"; do
|
||||
IFS=: read -r selected version label <<<"$pair"
|
||||
if [ "$selected" = "true" ] && [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "::error::$label requires a valid SemVer version"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ "$ANDROID" = "true" ] && [[ "$ANDROID_VERSION" == *-* ]]; then
|
||||
echo "::error::Coordinated Android approval is stable-only; use a dev candidate tag for prereleases"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
android:
|
||||
name: Approve Hermes-Relay Android
|
||||
needs: validate
|
||||
if: inputs.android
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch Android approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.android_version }}
|
||||
run: gh workflow run approve-release-android.yml --repo "$GITHUB_REPOSITORY" --ref main -f version="$VERSION"
|
||||
|
||||
plugin:
|
||||
name: Approve Hermes-Relay Plugin
|
||||
needs: validate
|
||||
if: inputs.plugin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch Plugin approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.plugin_version }}
|
||||
run: |
|
||||
gh workflow run approve-release-extensions.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f surface=plugin \
|
||||
-f version="$VERSION"
|
||||
|
||||
desktop:
|
||||
name: Approve Hermes-Relay CLI+UI
|
||||
needs: validate
|
||||
if: inputs.desktop
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch CLI+UI approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.desktop_version }}
|
||||
run: |
|
||||
gh workflow run approve-release-extensions.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f surface=desktop \
|
||||
-f version="$VERSION"
|
||||
@@ -20,20 +20,28 @@ on:
|
||||
branches: [main, dev]
|
||||
paths:
|
||||
- "app/**"
|
||||
- "relay-core/**"
|
||||
- "relay-ui/**"
|
||||
- "ui-preview/**"
|
||||
- "quest/**"
|
||||
- "gradle/**"
|
||||
- "build.gradle.kts"
|
||||
- "settings.gradle.kts"
|
||||
- "gradle.properties"
|
||||
- "gradlew"
|
||||
- "gradlew.bat"
|
||||
- "scripts/android-lane.ps1"
|
||||
- "scripts/android-prepush.py"
|
||||
- "scripts/dev.bat"
|
||||
- "scripts/dev.sh"
|
||||
- "scripts/tests/android_prepush_test.py"
|
||||
- "scripts/check-android-locales.py"
|
||||
- "scripts/android-locale-harness.py"
|
||||
- "scripts/check-android-collection-apis.py"
|
||||
- "scripts/check-android-capabilities.py"
|
||||
- "scripts/tests/check_android_capabilities_test.py"
|
||||
- "scripts/check-android-native-compat.py"
|
||||
- "scripts/check-android-release-notes.py"
|
||||
- "scripts/tests/check_android_native_compat_test.py"
|
||||
- "scripts/tests/check_android_release_notes_test.py"
|
||||
- ".github/workflows/ci-android.yml"
|
||||
- ".github/workflows/android-on-demand.yml"
|
||||
- ".github/workflows/play-preflight-android.yml"
|
||||
- ".github/workflows/approve-release-android.yml"
|
||||
- ".github/workflows/release-android.yml"
|
||||
@@ -57,7 +65,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -67,12 +75,26 @@ jobs:
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
- name: Validate Play capability boundary
|
||||
run: |
|
||||
python3 scripts/check-android-capabilities.py
|
||||
python3 -m unittest scripts.tests.check_android_capabilities_test
|
||||
|
||||
- name: Validate translation catalogs
|
||||
run: python3 scripts/check-android-locales.py
|
||||
|
||||
- name: Reject unsafe Android collection APIs
|
||||
run: python3 scripts/check-android-collection-apis.py
|
||||
|
||||
- name: Validate Android release notes
|
||||
run: |
|
||||
python3 scripts/check-android-release-notes.py
|
||||
python3 -m unittest scripts.tests.android_prepush_test
|
||||
python3 -m unittest scripts.tests.check_android_release_notes_test
|
||||
|
||||
- name: Test Android native compatibility checker
|
||||
run: python3 -m unittest scripts.tests.check_android_native_compat_test
|
||||
|
||||
- name: Run Android lint
|
||||
run: ./gradlew lint --console=plain
|
||||
|
||||
@@ -89,7 +111,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -102,6 +124,15 @@ jobs:
|
||||
- name: Build debug APK
|
||||
run: ./gradlew assembleDebug --console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayDebug
|
||||
|
||||
- name: Verify packaged ONNX Runtime compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/debug/*.apk \
|
||||
app/build/outputs/apk/sideload/debug/*.apk
|
||||
|
||||
- name: Upload debug APK
|
||||
uses: actions/upload-artifact@v7
|
||||
if: ${{ github.ref == 'refs/heads/main' }}
|
||||
@@ -133,7 +164,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -152,11 +183,21 @@ jobs:
|
||||
./gradlew :app:testSideloadDebugUnitTest \
|
||||
--tests com.hermesandroid.relay.network.ArchitectureBoundaryTest \
|
||||
--tests com.hermesandroid.relay.network.relay.RelayUrlDeriverTest \
|
||||
--tests com.hermesandroid.relay.network.shared.PluginProxyTransportTest \
|
||||
--tests '*GatewayChatClientTest*retarget*' \
|
||||
--tests '*RelayVoiceClientRoutingTest.proxyProviderOwnsBothVoiceSessionAndWebSocketRequests' \
|
||||
--tests com.hermesandroid.relay.network.relay.RelayHttpClientDiagnosticsTest \
|
||||
--tests com.hermesandroid.relay.ui.components.GatewayRoutesAccessPresentationTest \
|
||||
--tests com.hermesandroid.relay.ui.components.EndpointsCardCompactLayoutTest \
|
||||
--tests com.hermesandroid.relay.ui.screens.ConnectionDetailPresentationTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ConnectionSwitchTest \
|
||||
--tests com.hermesandroid.relay.util.ServerAddressTest \
|
||||
--tests com.hermesandroid.relay.util.IssueReportAndDiagnosticsTest \
|
||||
--tests com.hermesandroid.relay.data.AppLanguageTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatStreamRecoveryTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatViewModelGatewayInboundTurnTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.VoiceInboundCompletionTest \
|
||||
--tests com.hermesandroid.relay.voice.VoiceViewModelBargeInTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatViewModelRealtimeTurnTest \
|
||||
--tests com.hermesandroid.relay.network.relay.RealtimeVoiceEventParsingTest \
|
||||
--tests com.hermesandroid.relay.voice.VoiceCommandInterpreterTest \
|
||||
@@ -197,7 +238,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -218,3 +259,9 @@ jobs:
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Verify packaged ONNX Runtime compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
|
||||
name: CI — Upstream Contract
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
push:
|
||||
@@ -40,45 +43,64 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout hermes-relay
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve upstream ref
|
||||
id: ref
|
||||
env:
|
||||
REQUESTED_REF: ${{ github.event.inputs.upstream_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# PR/push runs use a known-good NousResearch/hermes-agent commit so
|
||||
# normal CI is stable. The weekly schedule below intentionally tracks
|
||||
# main as the upstream-drift siren.
|
||||
DEFAULT_REF="ef4b897a1843cd32c4f141f55db60f0f0602cc98"
|
||||
if [ "${{ github.event_name }}" = "schedule" ]; then
|
||||
REF="main" # weekly drift siren
|
||||
elif [ -n "${{ github.event.inputs.upstream_ref }}" ]; then
|
||||
REF="${{ github.event.inputs.upstream_ref }}" # manual override
|
||||
elif [ -n "$REQUESTED_REF" ]; then
|
||||
REF="$REQUESTED_REF" # manual override
|
||||
else
|
||||
REF="$DEFAULT_REF"
|
||||
fi
|
||||
|
||||
# The ref is passed to git below, so reject option-like or malformed
|
||||
# values before it reaches that boundary. Full commit IDs and normal
|
||||
# branch/tag names remain supported for manual contract checks.
|
||||
if [[ "$REF" == -* ]] ||
|
||||
! git check-ref-format --allow-onelevel "$REF" >/dev/null; then
|
||||
echo "FAIL: invalid upstream branch or tag name." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "ref=$REF" >> "$GITHUB_OUTPUT"
|
||||
echo "Checking standard-path route contract against upstream ref: $REF"
|
||||
|
||||
- name: Checkout vanilla upstream (no plugin, no bootstrap)
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: NousResearch/hermes-agent
|
||||
ref: ${{ steps.ref.outputs.ref }}
|
||||
path: _upstream
|
||||
fetch-depth: 1
|
||||
- name: Extract trusted upstream contract sources
|
||||
env:
|
||||
UPSTREAM_REF: ${{ steps.ref.outputs.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
UPSTREAM_GIT="$RUNNER_TEMP/hermes-agent-contract.git"
|
||||
git init --bare "$UPSTREAM_GIT"
|
||||
git -C "$UPSTREAM_GIT" remote add origin \
|
||||
"https://github.com/NousResearch/hermes-agent.git"
|
||||
git -C "$UPSTREAM_GIT" fetch --no-tags --depth=1 origin -- "$UPSTREAM_REF"
|
||||
UPSTREAM_COMMIT="$(git -C "$UPSTREAM_GIT" rev-parse 'FETCH_HEAD^{commit}')"
|
||||
|
||||
mkdir -p _upstream/gateway/platforms _upstream/hermes_cli
|
||||
git -C "$UPSTREAM_GIT" show \
|
||||
"$UPSTREAM_COMMIT:gateway/platforms/api_server.py" \
|
||||
> _upstream/gateway/platforms/api_server.py
|
||||
git -C "$UPSTREAM_GIT" show \
|
||||
"$UPSTREAM_COMMIT:hermes_cli/web_server.py" \
|
||||
> _upstream/hermes_cli/web_server.py
|
||||
echo "Extracted contract sources from upstream commit: $UPSTREAM_COMMIT"
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
- name: Assert upstream checkout is vanilla (no relay bootstrap/plugin)
|
||||
run: |
|
||||
if [ -e "_upstream/hermes_relay_bootstrap" ] || \
|
||||
[ -e "_upstream/plugin/hermes_relay_bootstrap" ] || \
|
||||
find _upstream -name "hermes_relay_bootstrap.pth" 2>/dev/null | grep -q .; then
|
||||
echo "FAIL: upstream checkout contains a relay bootstrap — not vanilla."; exit 1
|
||||
fi
|
||||
echo "OK: upstream checkout carries no relay plugin/bootstrap."
|
||||
|
||||
- name: Run route-surface contract
|
||||
run: python scripts/check-upstream-route-contract.py "_upstream"
|
||||
|
||||
@@ -38,6 +38,10 @@ jobs:
|
||||
working-directory: plugin/dashboard
|
||||
run: npm run build
|
||||
|
||||
- name: Test dashboard source
|
||||
working-directory: plugin/dashboard
|
||||
run: npm test
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
@@ -54,7 +58,11 @@ jobs:
|
||||
run: pip install -r relay_server/requirements.txt fastapi httpx requests
|
||||
|
||||
- name: Run dashboard API tests
|
||||
run: python -m unittest plugin.dashboard.test_plugin_api
|
||||
run: >-
|
||||
python -m unittest
|
||||
plugin.dashboard.test_plugin_api
|
||||
plugin.dashboard.test_git_api
|
||||
plugin.dashboard.test_mobile_plugin_api
|
||||
|
||||
- name: Verify dashboard bundle outputs
|
||||
run: |
|
||||
|
||||
@@ -107,6 +107,18 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Restore exact-source tray build cache
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
desktop/tray/target
|
||||
key: ${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-${{ hashFiles('desktop/tray/Cargo.toml', 'desktop/tray/build.rs', 'desktop/tray/src/**/*.rs') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
|
||||
@@ -101,9 +101,22 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_secure_proxy.py \
|
||||
plugin/tests/test_secure_proxy_contract.py \
|
||||
plugin/tests/test_secure_link_setup.py \
|
||||
plugin/tests/test_secure_proxy_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
plugin/tests/test_native_layout_imports.py \
|
||||
plugin/tests/test_profile_discovery.py \
|
||||
plugin/tests/test_profiles_updated_broadcast.py
|
||||
plugin/tests/test_profiles_updated_broadcast.py \
|
||||
plugin/tests/test_git_state.py \
|
||||
plugin/tests/test_git_state_write.py \
|
||||
plugin/tests/test_git_state_extras.py \
|
||||
plugin/tests/test_mobile_plugin_store.py \
|
||||
plugin/tests/test_android_tool.py \
|
||||
plugin/tests/test_android_navigate.py \
|
||||
plugin/tests/test_phone_platform.py \
|
||||
plugin/tests/test_desktop_tool_availability.py
|
||||
|
||||
@@ -10,13 +10,36 @@ on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
base_sha:
|
||||
description: "Exact base commit for a trusted release-backmerge candidate"
|
||||
required: true
|
||||
type: string
|
||||
head_sha:
|
||||
description: "Exact candidate commit to check"
|
||||
required: true
|
||||
type: string
|
||||
android_preset:
|
||||
description: "Optional Android-only compute lane"
|
||||
required: false
|
||||
default: auto
|
||||
type: choice
|
||||
options:
|
||||
- auto
|
||||
- focused
|
||||
- lint
|
||||
- assemble-debug
|
||||
- release-smoke
|
||||
- all-final
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: ci-required-${{ github.ref }}
|
||||
group: ci-required-${{ github.event_name == 'workflow_dispatch' && format('{0}-{1}', inputs.head_sha, inputs.android_preset) || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
@@ -30,23 +53,86 @@ jobs:
|
||||
dashboard: ${{ steps.filter.outputs.dashboard }}
|
||||
contract: ${{ steps.filter.outputs.contract }}
|
||||
docs: ${{ steps.filter.outputs.docs }}
|
||||
release_pr: ${{ steps.release.outputs.release_pr }}
|
||||
tree: ${{ steps.tree.outputs.tree }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
- name: Checkout pull request merge
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Checkout exact dispatched candidate
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- name: Test path classifier
|
||||
run: node .github/scripts/classify-ci-paths.test.cjs
|
||||
|
||||
- name: Record checked tree
|
||||
id: tree
|
||||
run: echo "tree=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Detect canonical release promotion
|
||||
id: release
|
||||
env:
|
||||
BASE_REF: ${{ github.base_ref }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
run: |
|
||||
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] && \
|
||||
[ "$BASE_REF" = "main" ] && \
|
||||
[ "$HEAD_REF" = "dev" ] && \
|
||||
[ "$HEAD_REPOSITORY" = "$GITHUB_REPOSITORY" ]; then
|
||||
echo "release_pr=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_pr=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Classify changed files
|
||||
id: filter
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DISPATCH_BASE_SHA: ${{ inputs.base_sha }}
|
||||
DISPATCH_HEAD_SHA: ${{ inputs.head_sha }}
|
||||
with:
|
||||
script: |
|
||||
let diffArgs;
|
||||
if (context.eventName === 'workflow_dispatch') {
|
||||
const base = process.env.DISPATCH_BASE_SHA || '';
|
||||
const head = process.env.DISPATCH_HEAD_SHA || '';
|
||||
const shaPattern = /^[0-9a-f]{40}$/;
|
||||
if (!shaPattern.test(base) || !shaPattern.test(head)) {
|
||||
core.setFailed('Exact-tree dispatch requires full 40-character base/head SHAs.');
|
||||
return;
|
||||
}
|
||||
const { stdout: checkedOut } = await exec.getExecOutput(
|
||||
'git',
|
||||
['rev-parse', 'HEAD'],
|
||||
);
|
||||
if (checkedOut.trim() !== head) {
|
||||
core.setFailed(`Checked out ${checkedOut.trim()}, expected ${head}.`);
|
||||
return;
|
||||
}
|
||||
const ancestry = await exec.exec(
|
||||
'git',
|
||||
['merge-base', '--is-ancestor', base, head],
|
||||
{ ignoreReturnCode: true },
|
||||
);
|
||||
if (ancestry !== 0) {
|
||||
core.setFailed(`Candidate ${head} does not descend from base ${base}.`);
|
||||
return;
|
||||
}
|
||||
diffArgs = ['diff', '--name-only', base, head];
|
||||
} else {
|
||||
diffArgs = ['diff', '--name-only', 'HEAD^1', 'HEAD^2'];
|
||||
}
|
||||
const { stdout } = await exec.getExecOutput(
|
||||
'git',
|
||||
['diff', '--name-only', 'HEAD^1', 'HEAD^2'],
|
||||
diffArgs,
|
||||
);
|
||||
const paths = stdout.split(/\r?\n/).filter(Boolean);
|
||||
const { classifyCiPaths } = require(
|
||||
@@ -60,35 +146,117 @@ jobs:
|
||||
core.notice(`Changed paths: ${paths.join(', ')}`);
|
||||
core.notice(`Selected checks: ${Object.entries(outputs).filter(([, value]) => value).map(([key]) => key).join(', ') || 'none'}`);
|
||||
|
||||
android:
|
||||
release-proof:
|
||||
name: Reuse exact-tree required checks
|
||||
needs: changes
|
||||
if: needs.changes.outputs.android == 'true'
|
||||
if: needs.changes.outputs.release_pr == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
reuse: ${{ steps.proof.outputs.reuse }}
|
||||
artifact_id: ${{ steps.proof.outputs.artifact_id }}
|
||||
run_id: ${{ steps.proof.outputs.run_id }}
|
||||
tree: ${{ steps.proof.outputs.tree }}
|
||||
steps:
|
||||
- name: Checkout simulated release merge
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Locate exact-tree proof
|
||||
id: proof
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
DEV_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
merge_tree=$(git rev-parse 'HEAD^{tree}')
|
||||
dev_tree=$(git rev-parse "${DEV_SHA}^{tree}")
|
||||
echo "reuse=false" >> "$GITHUB_OUTPUT"
|
||||
echo "tree=$dev_tree" >> "$GITHUB_OUTPUT"
|
||||
if [ "$merge_tree" != "$dev_tree" ]; then
|
||||
echo "Release merge changes the dev tree ($dev_tree -> $merge_tree); running full CI."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
artifact_name="required-checks-${dev_tree}"
|
||||
artifact=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${artifact_name}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
artifact_id=$(jq -r '.id // empty' <<<"$artifact")
|
||||
run_id=$(jq -r '.workflow_run.id // empty' <<<"$artifact")
|
||||
if [ -z "$artifact_id" ] || [ -z "$run_id" ]; then
|
||||
echo "No reusable proof exists for tree $dev_tree; running full CI."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")
|
||||
conclusion=$(jq -r '.conclusion' <<<"$run")
|
||||
workflow_path=$(jq -r '.path' <<<"$run")
|
||||
if [ "$workflow_path" != ".github/workflows/ci-required.yml" ] || [ "$conclusion" != "success" ]; then
|
||||
echo "::error::Required-check proof came from ${workflow_path} with conclusion ${conclusion}"
|
||||
exit 1
|
||||
fi
|
||||
echo "artifact_id=$artifact_id" >> "$GITHUB_OUTPUT"
|
||||
echo "run_id=$run_id" >> "$GITHUB_OUTPUT"
|
||||
echo "reuse=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Download exact-tree proof
|
||||
if: steps.proof.outputs.reuse == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
artifact-ids: ${{ steps.proof.outputs.artifact_id }}
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ steps.proof.outputs.run_id }}
|
||||
path: required-check-proof
|
||||
|
||||
- name: Verify exact-tree proof
|
||||
if: steps.proof.outputs.reuse == 'true'
|
||||
env:
|
||||
EXPECTED_TREE: ${{ steps.proof.outputs.tree }}
|
||||
run: |
|
||||
jq -e \
|
||||
--arg repository "$GITHUB_REPOSITORY" \
|
||||
--arg tree "$EXPECTED_TREE" \
|
||||
'.schemaVersion == 1 and .repository == $repository and .tree == $tree' \
|
||||
required-check-proof/required-checks.json
|
||||
|
||||
android:
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.android == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-android.yml
|
||||
|
||||
android_on_demand:
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.release-proof.outputs.reuse != 'true' && github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto' }}
|
||||
uses: ./.github/workflows/android-on-demand.yml
|
||||
with:
|
||||
head_sha: ${{ inputs.head_sha }}
|
||||
preset: ${{ inputs.android_preset }}
|
||||
|
||||
desktop:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.desktop == 'true'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.desktop == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-desktop.yml
|
||||
|
||||
plugin:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugin == 'true'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.plugin == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-plugin.yml
|
||||
|
||||
dashboard:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.dashboard == 'true'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.dashboard == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-dashboard.yml
|
||||
|
||||
contract:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.contract == 'true'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.contract == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-contract.yml
|
||||
|
||||
docs:
|
||||
name: Build public docs
|
||||
needs: changes
|
||||
if: needs.changes.outputs.docs == 'true'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.docs == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -110,11 +278,14 @@ jobs:
|
||||
guard:
|
||||
name: Required checks
|
||||
if: always()
|
||||
needs: [changes, android, desktop, plugin, dashboard, contract, docs]
|
||||
needs: [changes, release-proof, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
RELEASE_PROOF_RESULT: ${{ needs.release-proof.result }}
|
||||
REUSED_REQUIRED_CHECKS: ${{ needs.release-proof.outputs.reuse }}
|
||||
ANDROID_RESULT: ${{ needs.android.result }}
|
||||
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
|
||||
DESKTOP_RESULT: ${{ needs.desktop.result }}
|
||||
PLUGIN_RESULT: ${{ needs.plugin.result }}
|
||||
DASHBOARD_RESULT: ${{ needs.dashboard.result }}
|
||||
@@ -125,7 +296,7 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
failed=0
|
||||
for check in CHANGES ANDROID DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
for check in CHANGES RELEASE_PROOF ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
result_var="${check}_RESULT"
|
||||
result="${!result_var}"
|
||||
echo "$check: $result"
|
||||
@@ -135,3 +306,26 @@ jobs:
|
||||
esac
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Write exact-tree proof
|
||||
if: ${{ needs.release-proof.outputs.reuse != 'true' }}
|
||||
env:
|
||||
CHECKED_TREE: ${{ needs.changes.outputs.tree }}
|
||||
run: |
|
||||
mkdir -p required-check-proof
|
||||
jq -n \
|
||||
--arg repository "$GITHUB_REPOSITORY" \
|
||||
--arg tree "$CHECKED_TREE" \
|
||||
--arg commit "$GITHUB_SHA" \
|
||||
--arg run_id "$GITHUB_RUN_ID" \
|
||||
'{schemaVersion: 1, repository: $repository, tree: $tree, commit: $commit, runId: $run_id}' \
|
||||
> required-check-proof/required-checks.json
|
||||
|
||||
- name: Upload exact-tree proof
|
||||
if: ${{ needs.release-proof.outputs.reuse != 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: required-checks-${{ needs.changes.outputs.tree }}
|
||||
path: required-check-proof/required-checks.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
@@ -8,6 +8,15 @@ on:
|
||||
- "assets/screenshots/03_voice.png"
|
||||
- "assets/screenshots/06_manage.png"
|
||||
- "docs/media/screenshots.json"
|
||||
- "docs/media/desktop-ui-screenshots.json"
|
||||
- "assets/screenshots/desktop-ui/**"
|
||||
- "desktop/tray/ui/**"
|
||||
- "desktop/tray/scripts/*.mjs"
|
||||
- "desktop/tray/package-lock.json"
|
||||
- "desktop/tray/index.html"
|
||||
- "desktop/tray/icons/icon-256.png"
|
||||
- "desktop/src/endpoint.ts"
|
||||
- "desktop/src/transportSecurity.ts"
|
||||
- ".github/workflows/ci-website.yml"
|
||||
push:
|
||||
branches: [main, dev]
|
||||
@@ -17,6 +26,15 @@ on:
|
||||
- "assets/screenshots/03_voice.png"
|
||||
- "assets/screenshots/06_manage.png"
|
||||
- "docs/media/screenshots.json"
|
||||
- "docs/media/desktop-ui-screenshots.json"
|
||||
- "assets/screenshots/desktop-ui/**"
|
||||
- "desktop/tray/ui/**"
|
||||
- "desktop/tray/scripts/*.mjs"
|
||||
- "desktop/tray/package-lock.json"
|
||||
- "desktop/tray/index.html"
|
||||
- "desktop/tray/icons/icon-256.png"
|
||||
- "desktop/src/endpoint.ts"
|
||||
- "desktop/src/transportSecurity.ts"
|
||||
- ".github/workflows/ci-website.yml"
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
#
|
||||
# Run manually from the final dev or untagged main tree before creating
|
||||
# android-v*. The job
|
||||
# builds the same signed release artifacts, scans final DEX, and uploads the
|
||||
# Google Play bundle as a production DRAFT. A successful upload is the automated
|
||||
# Play gate while no public GitHub Release or sideload APK exists. Console-only
|
||||
# pre-review and pre-launch reports are informational and do not block release.
|
||||
# builds the signed release artifacts once, scans the final packages, and uploads
|
||||
# the Google Play bundle as a production DRAFT. The exact signed APK/AAB,
|
||||
# mappings, manifest, and checksums remain private Actions artifacts until
|
||||
# approval publishes those same bytes. Console-only pre-review and pre-launch
|
||||
# reports are informational and do not block release.
|
||||
|
||||
name: Hermes-Relay Android Play Preflight
|
||||
|
||||
@@ -68,7 +69,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -81,10 +82,10 @@ jobs:
|
||||
- name: Validate release metadata and source compatibility
|
||||
run: |
|
||||
python3 scripts/check-version-tracks.py
|
||||
python3 scripts/check-android-release-notes.py
|
||||
python3 scripts/check-privacy-policy.py --live
|
||||
python3 scripts/check-android-locales.py
|
||||
python3 scripts/check-android-collection-apis.py
|
||||
python3 -m json.tool app/src/main/assets/changelog.json >/dev/null
|
||||
|
||||
- name: Decode release keystore
|
||||
env:
|
||||
@@ -98,7 +99,15 @@ jobs:
|
||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
||||
run: ./gradlew bundleRelease assembleRelease --console=plain
|
||||
run: |
|
||||
./gradlew \
|
||||
:app:bundleGooglePlayRelease \
|
||||
:app:assembleGooglePlayRelease \
|
||||
:app:assembleSideloadRelease \
|
||||
--console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayRelease
|
||||
|
||||
- name: Scan final release DEX
|
||||
run: |
|
||||
@@ -106,6 +115,12 @@ jobs:
|
||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Verify packaged native compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Upload private production draft to Play
|
||||
env:
|
||||
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||
@@ -121,27 +136,27 @@ jobs:
|
||||
--resolution-strategy=ignore \
|
||||
--release-name="Hermes-Relay Android v${{ steps.metadata.outputs.version }}"
|
||||
|
||||
- name: Record successful preflight for the exact commit
|
||||
- name: Package immutable preflight artifacts
|
||||
run: |
|
||||
mkdir -p app/build/reports
|
||||
cat > app/build/reports/play-preflight.json <<EOF
|
||||
{
|
||||
"version": "${{ steps.metadata.outputs.version }}",
|
||||
"versionCode": "${{ steps.metadata.outputs.version_code }}",
|
||||
"commit": "$GITHUB_SHA",
|
||||
"tree": "${{ steps.metadata.outputs.tree }}",
|
||||
"track": "production",
|
||||
"status": "draft"
|
||||
}
|
||||
EOF
|
||||
python3 scripts/android_release_artifacts.py package \
|
||||
--version "${{ steps.metadata.outputs.version }}" \
|
||||
--version-code "${{ steps.metadata.outputs.version_code }}" \
|
||||
--commit "$GITHUB_SHA" \
|
||||
--tree "${{ steps.metadata.outputs.tree }}" \
|
||||
--sideload-apk app/build/outputs/apk/sideload/release/*.apk \
|
||||
--google-play-aab app/build/outputs/bundle/googlePlayRelease/*.aab \
|
||||
--sideload-mapping app/build/outputs/mapping/sideloadRelease/mapping.txt \
|
||||
--google-play-mapping app/build/outputs/mapping/googlePlayRelease/mapping.txt \
|
||||
--output app/build/preflight-artifacts
|
||||
|
||||
- name: Upload preflight proof
|
||||
- name: Upload immutable preflight artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: play-preflight-${{ steps.metadata.outputs.version }}-${{ steps.metadata.outputs.tree }}
|
||||
path: app/build/reports/play-preflight.json
|
||||
path: app/build/preflight-artifacts/*
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
compression-level: 0
|
||||
|
||||
- name: Preflight summary
|
||||
run: |
|
||||
@@ -152,4 +167,4 @@ jobs:
|
||||
echo "- Release tree: \`${{ steps.metadata.outputs.tree }}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Play track/status: **Production draft**" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The signed build, DEX scan, and Play draft upload passed. Ensure this exact release tree is on main, then run **Hermes-Relay Android Release Approval** from main. Console-only reports are informational and non-blocking." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The signed build, package scans, and Play draft upload passed. Approval will publish these exact private artifacts if the unchanged tree reaches main. Console-only reports are informational and non-blocking." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
@@ -36,6 +36,9 @@ jobs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
version_code: ${{ steps.version.outputs.version_code }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
release_tree: ${{ steps.version.outputs.release_tree }}
|
||||
preflight_artifact_id: ${{ steps.preflight.outputs.artifact_id }}
|
||||
preflight_run_id: ${{ steps.preflight.outputs.run_id }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
@@ -66,6 +69,7 @@ jobs:
|
||||
echo "version=$REF_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
||||
echo "release_tree=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify version sync
|
||||
run: |
|
||||
@@ -110,25 +114,38 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Require successful Play preflight for this exact release tree
|
||||
id: preflight
|
||||
if: ${{ !contains(steps.version.outputs.version, '-') }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
RELEASE_TREE=$(git rev-parse 'HEAD^{tree}')
|
||||
RELEASE_TREE="${{ steps.version.outputs.release_tree }}"
|
||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
||||
if [ "$COUNT" -lt 1 ]; then
|
||||
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
ARTIFACT_ID=$(jq -r '.id // empty' <<<"$ARTIFACT")
|
||||
RUN_ID=$(jq -r '.workflow_run.id // empty' <<<"$ARTIFACT")
|
||||
if [ -z "$ARTIFACT_ID" ] || [ -z "$RUN_ID" ]; then
|
||||
echo "::error::No successful Play preflight found for version $VERSION with tree $RELEASE_TREE"
|
||||
echo "Run Hermes-Relay Android Play Preflight from the final dev tree, merge that unchanged tree to main, then approve the release."
|
||||
exit 1
|
||||
fi
|
||||
echo "Play preflight proof found: $ARTIFACT_NAME"
|
||||
RUN=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}")
|
||||
CONCLUSION=$(jq -r '.conclusion' <<<"$RUN")
|
||||
WORKFLOW_PATH=$(jq -r '.path' <<<"$RUN")
|
||||
if [ "$WORKFLOW_PATH" != ".github/workflows/play-preflight-android.yml" ] || [ "$CONCLUSION" != "success" ]; then
|
||||
echo "::error::Preflight artifact came from ${WORKFLOW_PATH} with conclusion ${CONCLUSION}"
|
||||
exit 1
|
||||
fi
|
||||
echo "artifact_id=$ARTIFACT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "run_id=$RUN_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "Play preflight artifacts verified: $ARTIFACT_NAME (run $RUN_ID, artifact $ARTIFACT_ID)"
|
||||
|
||||
ci:
|
||||
name: CI Checks
|
||||
name: CI Checks (prerelease only)
|
||||
needs: validate
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
@@ -137,7 +154,7 @@ jobs:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -150,6 +167,7 @@ jobs:
|
||||
- name: Validate release metadata and Android API compatibility
|
||||
run: |
|
||||
python3 scripts/check-version-tracks.py
|
||||
python3 scripts/check-android-release-notes.py
|
||||
python3 scripts/check-privacy-policy.py
|
||||
python3 scripts/check-android-locales.py
|
||||
python3 scripts/check-android-collection-apis.py
|
||||
@@ -167,6 +185,7 @@ jobs:
|
||||
release:
|
||||
name: Build & Publish Release
|
||||
needs: [validate, ci]
|
||||
if: ${{ always() && needs.validate.result == 'success' && (needs.ci.result == 'success' || needs.ci.result == 'skipped') }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
@@ -175,7 +194,7 @@ jobs:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('android-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
@@ -185,31 +204,33 @@ jobs:
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
- name: Decode release keystore
|
||||
- name: Download exact stable preflight artifacts
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
artifact-ids: ${{ needs.validate.outputs.preflight_artifact_id }}
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ needs.validate.outputs.preflight_run_id }}
|
||||
path: app/build/preflight-artifacts
|
||||
|
||||
- name: Verify exact stable preflight artifacts
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
run: |
|
||||
python3 scripts/android_release_artifacts.py verify \
|
||||
--version "${{ needs.validate.outputs.version }}" \
|
||||
--version-code "${{ needs.validate.outputs.version_code }}" \
|
||||
--tree "${{ needs.validate.outputs.release_tree }}" \
|
||||
--directory app/build/preflight-artifacts
|
||||
|
||||
- name: Decode release keystore for candidate build
|
||||
env:
|
||||
HERMES_KEYSTORE_BASE64: ${{ secrets.HERMES_KEYSTORE_BASE64 }}
|
||||
if: env.HERMES_KEYSTORE_BASE64 != ''
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' && env.HERMES_KEYSTORE_BASE64 != '' }}
|
||||
run: |
|
||||
echo "$HERMES_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
|
||||
echo "HERMES_KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV"
|
||||
|
||||
- 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 }}
|
||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
||||
# `assembleRelease` and `bundleRelease` are flavor-wide task aliases
|
||||
# (added by `flavorDimensions += "track"` in app/build.gradle.kts), so
|
||||
# this one line builds ALL four artifacts at once. Filenames come from
|
||||
# `archivesName` (set in app/build.gradle.kts) which injects the app
|
||||
# version, so `<version>` below is `libs.versions.appVersionName`:
|
||||
# app/build/outputs/apk/googlePlay/release/hermes-relay-<version>-googlePlay-release.apk
|
||||
# app/build/outputs/apk/sideload/release/hermes-relay-<version>-sideload-release.apk
|
||||
# app/build/outputs/bundle/googlePlayRelease/hermes-relay-<version>-googlePlay-release.aab
|
||||
# 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:
|
||||
@@ -233,10 +254,10 @@ jobs:
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ github.sha }}
|
||||
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ needs.validate.outputs.release_tree }}
|
||||
path: |
|
||||
app/build/outputs/mapping/googlePlayRelease/mapping.txt
|
||||
app/build/outputs/mapping/sideloadRelease/mapping.txt
|
||||
app/build/preflight-artifacts/mapping-googlePlayRelease.txt
|
||||
app/build/preflight-artifacts/mapping-sideloadRelease.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
@@ -253,8 +274,7 @@ jobs:
|
||||
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
|
||||
--apk app/build/preflight-artifacts/*-sideload-release.apk
|
||||
|
||||
- name: Scan candidate DEX for unsupported collection APIs
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -262,25 +282,24 @@ jobs:
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
--apk app/build/outputs/apk/sideload/candidate/*.apk
|
||||
|
||||
- name: Verify stable packaged ONNX Runtime compatibility
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/preflight-artifacts/*-sideload-release.apk
|
||||
|
||||
- name: Verify candidate packaged ONNX Runtime compatibility
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/sideload/candidate/*.apk
|
||||
|
||||
- name: List produced artifacts (debug aid)
|
||||
run: |
|
||||
echo "=== APK outputs ==="
|
||||
echo "=== Reused stable artifacts ==="
|
||||
find app/build/preflight-artifacts -maxdepth 1 -type f -print 2>/dev/null || true
|
||||
echo "=== Candidate APK outputs ==="
|
||||
find app/build/outputs/apk -name '*.apk' -print 2>/dev/null || true
|
||||
echo "=== AAB outputs ==="
|
||||
find app/build/outputs/bundle -name '*.aab' -print 2>/dev/null || true
|
||||
|
||||
- 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
|
||||
# different between APK and AAB). Checksums cover EXACTLY the files
|
||||
# attached to the GitHub Release (see the 2-asset policy on the
|
||||
# release step below) so SHA256SUMS.txt matches the assets 1:1.
|
||||
run: |
|
||||
cd app/build/outputs
|
||||
sha256sum apk/sideload/release/*.apk bundle/googlePlayRelease/*.aab > SHA256SUMS.txt
|
||||
cat SHA256SUMS.txt
|
||||
|
||||
- name: Generate candidate checksums
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -326,9 +345,9 @@ jobs:
|
||||
# Deliberate 2-asset policy (#144): attach ONLY the installable
|
||||
# sideload APK and Play AAB, plus checksums covering those files.
|
||||
files: |
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
app/build/outputs/bundle/googlePlayRelease/*.aab
|
||||
app/build/outputs/SHA256SUMS.txt
|
||||
app/build/preflight-artifacts/*-sideload-release.apk
|
||||
app/build/preflight-artifacts/*-googlePlay-release.aab
|
||||
app/build/preflight-artifacts/SHA256SUMS.txt
|
||||
|
||||
- name: Create candidate GitHub prerelease
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -350,18 +369,36 @@ jobs:
|
||||
run: |
|
||||
echo "## Hermes-Relay Android v${{ needs.validate.outputs.version }}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$PRERELEASE" = "true" ] && [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Release-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ "$PRERELEASE" = "true" ]; then
|
||||
echo "⚠️ **Debug-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$PRERELEASE" != "true" ]; then
|
||||
echo "✅ **Published the exact signed Play-preflight artifacts**" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Signed with release keystore** — suitable for Play Store upload" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "✅ **Release-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$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"
|
||||
echo "⚠️ **Debug-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "### Artifacts" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||
find app/build/preflight-artifacts -maxdepth 1 -type f -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
find app/build/outputs/apk -name '*.apk' -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
find app/build/outputs/bundle -name '*.aab' -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate, release]
|
||||
if: needs.validate.outputs.prerelease != 'true'
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: android-v${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
# Reconcile a completed stable hotfix into dev without adding a ceremonial PR
|
||||
# merge commit. Normal dev -> main releases are detected and intentionally no-op.
|
||||
# A conflicted merge, failed exact-tree CI, stale dev ref, or denied branch update
|
||||
# stops without mutating dev and falls back to the normal reconciliation PR path.
|
||||
|
||||
name: Release Backmerge
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Published stable tag to reconcile (android-v*, server-v*, or desktop-v*)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-backmerge-dev
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: Prepare exact backmerge candidate
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
outcome: ${{ steps.prepare.outputs.outcome }}
|
||||
base_dev_sha: ${{ steps.prepare.outputs.base_dev_sha }}
|
||||
candidate_branch: ${{ steps.prepare.outputs.candidate_branch }}
|
||||
candidate_sha: ${{ steps.prepare.outputs.candidate_sha }}
|
||||
release_commit: ${{ steps.prepare.outputs.release_commit }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: main
|
||||
|
||||
- name: Validate release and prepare merge commit
|
||||
id: prepare
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ ! "$RELEASE_TAG" =~ ^(android|server|desktop)-v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::Release Backmerge accepts stable SemVer production tags only; got $RELEASE_TAG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git fetch origin \
|
||||
"+refs/heads/main:refs/remotes/origin/main" \
|
||||
"+refs/heads/dev:refs/remotes/origin/dev" \
|
||||
"+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}"
|
||||
release_commit="$(git rev-parse "${RELEASE_TAG}^{commit}")"
|
||||
base_dev_sha="$(git rev-parse origin/dev)"
|
||||
echo "release_commit=$release_commit" >> "$GITHUB_OUTPUT"
|
||||
echo "base_dev_sha=$base_dev_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if ! git merge-base --is-ancestor "$release_commit" origin/main; then
|
||||
echo "::error::$RELEASE_TAG ($release_commit) is not contained in origin/main"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
read -r is_draft is_prerelease < <(
|
||||
gh release view "$RELEASE_TAG" --json isDraft,isPrerelease \
|
||||
--jq '[.isDraft, .isPrerelease] | @tsv'
|
||||
)
|
||||
if [ "$is_draft" != "false" ] || [ "$is_prerelease" != "false" ]; then
|
||||
echo "::error::$RELEASE_TAG is not a published stable GitHub release"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
plan="$(
|
||||
python3 scripts/plan_release_backmerge.py \
|
||||
--release-commit "$release_commit" \
|
||||
--dev-commit "$base_dev_sha"
|
||||
)"
|
||||
case "$plan" in
|
||||
already-contained)
|
||||
echo "outcome=noop" >> "$GITHUB_OUTPUT"
|
||||
echo "## Release backmerge not needed" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`$RELEASE_TAG\` is already contained in \`dev\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
;;
|
||||
normal-release)
|
||||
echo "outcome=noop" >> "$GITHUB_OUTPUT"
|
||||
echo "## Normal release: no backmerge" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The released merge's integration parent is already contained in \`dev\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
;;
|
||||
hotfix) ;;
|
||||
*)
|
||||
echo "::error::Unknown release-backmerge plan: $plan"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
candidate_branch="chore/release-backmerge/${RELEASE_TAG}-${GITHUB_RUN_ID}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git switch --detach "$base_dev_sha"
|
||||
|
||||
set +e
|
||||
git merge --no-ff -m "chore: back-merge ${RELEASE_TAG}" "$release_commit"
|
||||
merge_status=$?
|
||||
set -e
|
||||
if [ "$merge_status" -ne 0 ]; then
|
||||
conflicts="$(git diff --name-only --diff-filter=U | paste -sd ', ' -)"
|
||||
echo "outcome=conflict" >> "$GITHUB_OUTPUT"
|
||||
echo "::error::Automatic backmerge conflicts: ${conflicts:-unknown}. Open a reconciliation PR."
|
||||
echo "## Manual reconciliation PR required" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`$RELEASE_TAG\` conflicts with current \`dev\`: ${conflicts:-unknown}." >> "$GITHUB_STEP_SUMMARY"
|
||||
git merge --abort || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
candidate_sha="$(git rev-parse HEAD)"
|
||||
first_parent="$(git rev-parse HEAD^1)"
|
||||
second_parent="$(git rev-parse HEAD^2)"
|
||||
if [ "$first_parent" != "$base_dev_sha" ] || [ "$second_parent" != "$release_commit" ]; then
|
||||
echo "::error::Candidate parents do not match dev + release commit"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git push origin "$candidate_sha:refs/heads/$candidate_branch"
|
||||
echo "outcome=candidate" >> "$GITHUB_OUTPUT"
|
||||
echo "candidate_branch=$candidate_branch" >> "$GITHUB_OUTPUT"
|
||||
echo "candidate_sha=$candidate_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "## Backmerge candidate prepared" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Release: \`$RELEASE_TAG\` (\`$release_commit\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Dev base: \`$base_dev_sha\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate: \`$candidate_sha\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Temporary ref: \`$candidate_branch\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
gate:
|
||||
name: Run exact-tree required checks
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.outcome == 'candidate'
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
check_run_id: ${{ steps.gate.outputs.check_run_id }}
|
||||
steps:
|
||||
- name: Dispatch and await Required checks
|
||||
id: gate
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
BASE_DEV_SHA: ${{ needs.prepare.outputs.base_dev_sha }}
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh workflow run ci-required.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref "$CANDIDATE_BRANCH" \
|
||||
-f base_sha="$BASE_DEV_SHA" \
|
||||
-f head_sha="$CANDIDATE_SHA"
|
||||
|
||||
check_run_id=""
|
||||
for _ in {1..20}; do
|
||||
check_run_id="$(
|
||||
gh run list \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--workflow ci-required.yml \
|
||||
--branch "$CANDIDATE_BRANCH" \
|
||||
--event workflow_dispatch \
|
||||
--limit 20 \
|
||||
--json databaseId,headSha \
|
||||
--jq ".[] | select(.headSha == \"$CANDIDATE_SHA\") | .databaseId" \
|
||||
| head -n 1
|
||||
)"
|
||||
if [ -n "$check_run_id" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
if [ -z "$check_run_id" ]; then
|
||||
echo "::error::Required checks dispatch was not observed for $CANDIDATE_SHA"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "check_run_id=$check_run_id" >> "$GITHUB_OUTPUT"
|
||||
gh run watch "$check_run_id" --repo "$GITHUB_REPOSITORY" --exit-status
|
||||
|
||||
promote:
|
||||
name: Compare-and-swap dev
|
||||
needs: [prepare, gate]
|
||||
if: needs.prepare.outputs.outcome == 'candidate' && needs.gate.result == 'success'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: main
|
||||
|
||||
- name: Fast-forward dev to the tested candidate
|
||||
env:
|
||||
BASE_DEV_SHA: ${{ needs.prepare.outputs.base_dev_sha }}
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
RELEASE_COMMIT: ${{ needs.prepare.outputs.release_commit }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin --no-tags \
|
||||
"+refs/heads/dev:refs/remotes/origin/dev" \
|
||||
"+refs/heads/$CANDIDATE_BRANCH:refs/remotes/origin/$CANDIDATE_BRANCH"
|
||||
current_dev="$(git rev-parse origin/dev)"
|
||||
remote_candidate="$(git rev-parse "origin/$CANDIDATE_BRANCH")"
|
||||
|
||||
if [ "$current_dev" != "$BASE_DEV_SHA" ]; then
|
||||
echo "::error::dev moved from $BASE_DEV_SHA to $current_dev; rerun or open a reconciliation PR"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$remote_candidate" != "$CANDIDATE_SHA" ]; then
|
||||
echo "::error::Candidate ref moved from $CANDIDATE_SHA to $remote_candidate"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$(git rev-parse "$CANDIDATE_SHA^1")" != "$BASE_DEV_SHA" ] || \
|
||||
[ "$(git rev-parse "$CANDIDATE_SHA^2")" != "$RELEASE_COMMIT" ]; then
|
||||
echo "::error::Candidate ancestry changed after verification"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The explicit lease is the atomic stale-base guard. The update is a
|
||||
# fast-forward from BASE_DEV_SHA; no unrelated history can be replaced.
|
||||
git push \
|
||||
--force-with-lease="refs/heads/dev:$BASE_DEV_SHA" \
|
||||
origin "$CANDIDATE_SHA:refs/heads/dev"
|
||||
|
||||
git push origin --delete "$CANDIDATE_BRANCH" || \
|
||||
echo "::warning::Could not remove temporary branch $CANDIDATE_BRANCH"
|
||||
|
||||
echo "## Release backmerge complete" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Fast-forwarded \`dev\` from \`$BASE_DEV_SHA\` to tested merge \`$CANDIDATE_SHA\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
fallback:
|
||||
name: Report PR fallback
|
||||
needs: [prepare, gate, promote]
|
||||
if: always() && needs.prepare.outputs.outcome == 'candidate' && needs.promote.result != 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Preserve safe fallback instructions
|
||||
env:
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
CHECK_RUN_ID: ${{ needs.gate.outputs.check_run_id }}
|
||||
run: |
|
||||
echo "## Automatic backmerge stopped" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`dev\` was not updated. Open or refresh a reconciliation PR after addressing the failed/stale gate." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate ref: \`${CANDIDATE_BRANCH:-not-created}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate SHA: \`${CANDIDATE_SHA:-n/a}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Required-check run: \`${CHECK_RUN_ID:-n/a}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -3,6 +3,12 @@ name: Hermes-Relay CLI+UI Release
|
||||
on:
|
||||
push:
|
||||
tags: ['desktop-v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Approved CLI+UI version"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -20,6 +26,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
@@ -34,10 +41,16 @@ jobs:
|
||||
- name: Extract and validate tag version
|
||||
id: version
|
||||
shell: bash
|
||||
env:
|
||||
DISPATCHED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
if [[ -z "$version" || "$version" == "$GITHUB_REF_NAME" ]]; then
|
||||
if [ -n "$DISPATCHED_VERSION" ]; then
|
||||
version="$DISPATCHED_VERSION"
|
||||
else
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
fi
|
||||
if [ -z "$version" ] || { [ -z "$DISPATCHED_VERSION" ] && [ "$version" = "$GITHUB_REF_NAME" ]; }; then
|
||||
echo "Expected a desktop-v* tag, got $GITHUB_REF_NAME" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -51,11 +64,12 @@ jobs:
|
||||
- name: Verify tag belongs to the correct integration branch
|
||||
shell: bash
|
||||
working-directory: .
|
||||
env:
|
||||
TAG_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
tag_commit="$(git rev-parse "${GITHUB_REF_NAME}^{commit}")"
|
||||
if [[ "$version" == *-* ]]; then
|
||||
tag_commit="$(git rev-parse HEAD)"
|
||||
if [[ "$TAG_VERSION" == *-* ]]; then
|
||||
git fetch origin dev --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
||||
echo "CLI+UI prereleases must be tagged from dev; $tag_commit is not in origin/dev" >&2
|
||||
@@ -78,6 +92,8 @@ jobs:
|
||||
working-directory: desktop
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js (for npm ci + tsc)
|
||||
uses: actions/setup-node@v7
|
||||
@@ -117,6 +133,9 @@ jobs:
|
||||
- name: Build Linux x64
|
||||
run: npm run build:bin:linux
|
||||
|
||||
- name: Build Linux arm64
|
||||
run: npm run build:bin:linux-arm
|
||||
|
||||
- name: Build macOS x64
|
||||
run: npm run build:bin:mac-x64
|
||||
|
||||
@@ -138,19 +157,27 @@ jobs:
|
||||
|
||||
- name: Smoke-test Linux binary
|
||||
run: |
|
||||
set -e
|
||||
set -euo pipefail
|
||||
chmod +x dist/bin/hermes-relay-linux-x64
|
||||
for cmd in --version --help doctor; do
|
||||
out=$(./dist/bin/hermes-relay-linux-x64 "$cmd" 2>&1 || true)
|
||||
set +e
|
||||
out=$(./dist/bin/hermes-relay-linux-x64 "$cmd" 2>&1)
|
||||
exit_code=$?
|
||||
if [ -z "$out" ] || [ ${#out} -lt 10 ]; then
|
||||
echo "SMOKE FAIL: './hermes-relay-linux-x64 $cmd' produced no output (exit=$exit_code)"
|
||||
set -e
|
||||
if [ "$exit_code" -ne 0 ] || [ -z "$out" ] || [ ${#out} -lt 10 ]; then
|
||||
echo "SMOKE FAIL: './hermes-relay-linux-x64 $cmd' failed or produced no output (exit=$exit_code)"
|
||||
echo "Raw output was: [$out]"
|
||||
exit 1
|
||||
fi
|
||||
echo " smoke OK: $cmd -> $(echo "$out" | head -1)"
|
||||
done
|
||||
|
||||
- name: Verify Linux arm64 artifact architecture
|
||||
run: |
|
||||
set -euo pipefail
|
||||
file dist/bin/hermes-relay-linux-arm64 | tee /tmp/hermes-relay-linux-arm64.file
|
||||
grep -Eq 'ELF 64-bit.*(ARM aarch64|ARM64)' /tmp/hermes-relay-linux-arm64.file
|
||||
|
||||
- name: Upload CLI release assets
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -158,6 +185,7 @@ jobs:
|
||||
path: |
|
||||
desktop/dist/bin/hermes-relay-win-x64.exe
|
||||
desktop/dist/bin/hermes-relay-linux-x64
|
||||
desktop/dist/bin/hermes-relay-linux-arm64
|
||||
desktop/dist/bin/hermes-relay-darwin-x64
|
||||
desktop/dist/bin/hermes-relay-darwin-arm64
|
||||
retention-days: 7
|
||||
@@ -196,6 +224,60 @@ jobs:
|
||||
throw "Windows CLI smoke left $(@($leftovers).Count) process(es) behind"
|
||||
}
|
||||
|
||||
smoke-macos-cli-release-asset:
|
||||
name: Smoke exact macOS CLI release asset
|
||||
runs-on: macos-latest
|
||||
needs:
|
||||
- validate-release
|
||||
- build-cli-binaries
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: cli-binaries
|
||||
path: release-assets
|
||||
|
||||
- name: Launch native release asset and inspect both architectures
|
||||
env:
|
||||
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
case "$(uname -m)" in
|
||||
x86_64) native_asset=hermes-relay-darwin-x64 ;;
|
||||
arm64) native_asset=hermes-relay-darwin-arm64 ;;
|
||||
*) echo "Unsupported macOS runner architecture: $(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
chmod +x "release-assets/$native_asset"
|
||||
version_output=$("release-assets/$native_asset" --version)
|
||||
test "$version_output" = "hermes-relay $EXPECTED_DESKTOP_VERSION"
|
||||
"release-assets/$native_asset" --help | grep -Fq 'Usage:'
|
||||
file release-assets/hermes-relay-darwin-x64 | grep -Fq 'x86_64'
|
||||
file release-assets/hermes-relay-darwin-arm64 | grep -Eq '(arm64|arm64e)'
|
||||
|
||||
smoke-linux-arm64-cli-release-asset:
|
||||
name: Smoke exact Linux arm64 CLI release asset
|
||||
runs-on: ubuntu-24.04-arm
|
||||
needs:
|
||||
- validate-release
|
||||
- build-cli-binaries
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: cli-binaries
|
||||
path: release-assets
|
||||
|
||||
- name: Launch native arm64 release asset
|
||||
env:
|
||||
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
asset=release-assets/hermes-relay-linux-arm64
|
||||
test "$(uname -m)" = "aarch64"
|
||||
chmod +x "$asset"
|
||||
version_output=$("$asset" --version)
|
||||
test "$version_output" = "hermes-relay $EXPECTED_DESKTOP_VERSION"
|
||||
"$asset" --help | grep -Fq 'Usage:'
|
||||
file "$asset" | grep -Eq 'ELF 64-bit.*(ARM aarch64|ARM64)'
|
||||
|
||||
build-windows-tray-installer:
|
||||
name: Build Windows tray installer
|
||||
runs-on: windows-latest
|
||||
@@ -205,6 +287,8 @@ jobs:
|
||||
working-directory: desktop
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
@@ -223,6 +307,18 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Restore exact-source tray build cache
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
desktop/tray/target
|
||||
key: ${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-${{ hashFiles('desktop/tray/Cargo.toml', 'desktop/tray/build.rs', 'desktop/tray/src/**/*.rs') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
@@ -345,6 +441,11 @@ jobs:
|
||||
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
||||
throw "installed CLI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$versionOutput'"
|
||||
}
|
||||
$tray = Join-Path $installDir 'hermes-relay-tray.exe'
|
||||
$trayVersion = (Get-Item -LiteralPath $tray).VersionInfo.ProductVersion
|
||||
if ($trayVersion -ne $env:EXPECTED_DESKTOP_VERSION) {
|
||||
throw "installed UI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$trayVersion'"
|
||||
}
|
||||
$helpOutput = (& $cli --help | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
|
||||
throw 'installed CLI --help smoke failed'
|
||||
@@ -385,7 +486,7 @@ jobs:
|
||||
throw "installer lifecycle changed the pre-existing tray startup preference"
|
||||
}
|
||||
|
||||
Write-Host "packaged installer lifecycle smoke OK version=$versionOutput install=$installDir"
|
||||
Write-Host "packaged installer lifecycle smoke OK cli=$versionOutput ui=$trayVersion install=$installDir"
|
||||
} finally {
|
||||
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
|
||||
Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
@@ -417,17 +518,18 @@ jobs:
|
||||
name: Publish GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- validate-release
|
||||
- build-cli-binaries
|
||||
- smoke-windows-cli-release-asset
|
||||
- smoke-macos-cli-release-asset
|
||||
- smoke-linux-arm64-cli-release-asset
|
||||
- build-windows-tray-installer
|
||||
steps:
|
||||
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
|
||||
# (the other publish-release steps only consume downloaded build artifacts).
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Extract CLI+UI version
|
||||
id: version
|
||||
run: echo "version=${GITHUB_REF_NAME#desktop-v}" >> "$GITHUB_OUTPUT"
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -447,8 +549,8 @@ jobs:
|
||||
# (desktop-v0.3.0) so install/pin commands stay accurate without manual edits.
|
||||
- name: Render release notes
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
TAG: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
sed -e "s/__VERSION__/${VERSION}/g" -e "s/__TAG__/${TAG}/g" \
|
||||
CLI_RELEASE_NOTES.md > cli_release_notes_rendered.md
|
||||
@@ -457,16 +559,36 @@ jobs:
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Hermes-Relay CLI+UI v${{ steps.version.outputs.version }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: Hermes-Relay CLI+UI v${{ needs.validate-release.outputs.version }}
|
||||
tag_name: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
draft: false
|
||||
prerelease: ${{ contains(steps.version.outputs.version, 'alpha') || contains(steps.version.outputs.version, 'beta') || contains(steps.version.outputs.version, 'rc') }}
|
||||
prerelease: ${{ contains(needs.validate-release.outputs.version, '-') }}
|
||||
fail_on_unmatched_files: true
|
||||
body_path: cli_release_notes_rendered.md
|
||||
files: |
|
||||
release-assets/cli-binaries/hermes-relay-win-x64.exe
|
||||
release-assets/cli-binaries/hermes-relay-linux-x64
|
||||
release-assets/cli-binaries/hermes-relay-linux-arm64
|
||||
release-assets/cli-binaries/hermes-relay-darwin-x64
|
||||
release-assets/cli-binaries/hermes-relay-darwin-arm64
|
||||
release-assets/cli-windows-installer/hermes-relay-windows-x64-setup.exe
|
||||
release-assets/SHA256SUMS.txt
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate-release, publish-release]
|
||||
if: ${{ !contains(needs.validate-release.outputs.version, '-') }}
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -4,6 +4,12 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "server-v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Approved Plugin version"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -19,10 +25,19 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
run: echo "version=${GITHUB_REF#refs/tags/server-v}" >> "$GITHUB_OUTPUT"
|
||||
env:
|
||||
DISPATCHED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ -n "$DISPATCHED_VERSION" ]; then
|
||||
version="$DISPATCHED_VERSION"
|
||||
else
|
||||
version="${GITHUB_REF#refs/tags/server-v}"
|
||||
fi
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify Plugin version sync and changelog
|
||||
run: |
|
||||
@@ -61,6 +76,8 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
@@ -85,11 +102,16 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
plugin/tests/test_proactive_channel.py \
|
||||
plugin/tests/test_android_phone_status.py
|
||||
plugin/tests/test_android_phone_status.py \
|
||||
plugin/tests/test_android_tool.py \
|
||||
plugin/tests/test_android_navigate.py \
|
||||
plugin/tests/test_phone_platform.py \
|
||||
plugin/tests/test_desktop_tool_availability.py
|
||||
|
||||
package:
|
||||
name: Build and publish Plugin package
|
||||
@@ -98,6 +120,8 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
@@ -138,3 +162,22 @@ jobs:
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
dist/SHA256SUMS.txt
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate, package]
|
||||
if: ${{ !contains(needs.validate.outputs.version, '-') }}
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: server-v${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -83,7 +83,7 @@ jobs:
|
||||
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
@@ -24,10 +24,7 @@ Thumbs.db
|
||||
local.properties
|
||||
/build/
|
||||
/app/build/
|
||||
/relay-core/build/
|
||||
/relay-ui/build/
|
||||
/ui-preview/build/
|
||||
/quest/build/
|
||||
/experiments/quest/**/build/
|
||||
/app/release/
|
||||
*.apk
|
||||
*.aab
|
||||
@@ -95,3 +92,4 @@ keystore.properties
|
||||
desktop/tray/ui/vendor/
|
||||
# Generated from assets/screenshots/02_chat.png before docs dev/build.
|
||||
/user-docs/public/chat-demo.png
|
||||
/user-docs/public/product/desktop-ui/
|
||||
|
||||
@@ -7,14 +7,17 @@ coding agent (Claude Code, Codex, Cursor, etc.).
|
||||
|
||||
This file is the provider-neutral canonical agent context. Read it before
|
||||
touching code, then `docs/spec.md` and `docs/decisions.md`. Provider adapters
|
||||
such as **[CLAUDE.md](CLAUDE.md)** may add tool-specific guidance, but they do
|
||||
not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
|
||||
such as **[CLAUDE.md](CLAUDE.md)** import this file instead of duplicating
|
||||
policy. They do not redefine the branch, release, hotfix, or verification
|
||||
contract here and in `RELEASE.md`.
|
||||
|
||||
- Release process → **[RELEASE.md](RELEASE.md)**
|
||||
- Contributor setup → **[CONTRIBUTING.md](CONTRIBUTING.md)**
|
||||
- Gateway/session/reconnect testing → **[docs/gateway-contract-testing.md](docs/gateway-contract-testing.md)**
|
||||
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
|
||||
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
|
||||
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
|
||||
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
- Follow-ups / deferred work / known gaps → **[docs/project/TODO.md](docs/project/TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
|
||||
## Branch contract
|
||||
|
||||
@@ -28,7 +31,7 @@ not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
|
||||
| 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 |
|
||||
| Back-merge target | `dev`; merge `main` back immediately after every hotfix |
|
||||
| Back-merge target | `dev`; stable hotfixes reconcile automatically when the exact tested merge is conflict-free, otherwise through a PR |
|
||||
|
||||
Feature completion means merged and verified on `dev`; it does not mean
|
||||
released. A release train is separate work owned by a Forge release
|
||||
@@ -37,6 +40,14 @@ open the `dev` → `main` release PR, tag the resulting `main` tip, publish the
|
||||
surface artifacts, deploy or roll out, and verify the live result. Never create
|
||||
a staging branch.
|
||||
|
||||
A normal `dev` → `main` release needs no back-merge: the released integration
|
||||
parent is already in `dev`. A production-tag hotfix is different. After its
|
||||
stable release succeeds, `Release Backmerge` prepares a `dev`-first merge
|
||||
commit, runs the same path-aware required checks on that exact SHA, verifies
|
||||
that `dev` has not moved, and fast-forwards `dev`. Conflicts, failed checks,
|
||||
stale refs, or denied branch updates fail closed and require a reconciliation
|
||||
PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
### Local integration discipline
|
||||
|
||||
- Fetch `origin/dev` before creating a task branch or worktree; do not base new
|
||||
@@ -54,8 +65,10 @@ a staging branch.
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
||||
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||
compatibility surface; Relay adds optional extensions. A Gateway-owned
|
||||
conversation never changes transport because Gateway auth or reachability
|
||||
changes. This
|
||||
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
@@ -75,11 +88,21 @@ a staging branch.
|
||||
Version bumps happen only on a release-prep branch targeting `dev`, and
|
||||
production tags are cut only from `main`.
|
||||
- **Android:** Jetpack Compose only (no XML), kotlinx.serialization (no Gson),
|
||||
OkHttp (no Ktor), `wss://` only. Run `./gradlew lint` before pushing Kotlin.
|
||||
OkHttp (no Ktor), `wss://` only. While editing, use only the narrow local
|
||||
compile or focused test needed for feedback, through `scripts/android-lane.ps1`
|
||||
on Windows. Once an exact commit is already pushed, prefer the `Android
|
||||
On-Demand` workflow for lint, the focused shards, both-flavor assemblies, and
|
||||
release smoke; isolated cloud jobs may run concurrently. Do not push solely
|
||||
to obtain cloud compute without push authorization, and do not duplicate a
|
||||
preset already running for the same SHA. Full local verification remains
|
||||
available through `scripts/dev.bat prepush` (or `./scripts/dev.sh prepush`)
|
||||
when explicitly wanted or when cloud execution is unavailable.
|
||||
Physical-device checks and APK installation remain separately owned local
|
||||
evidence.
|
||||
- **Plugin (Python 3.11+):** aiohttp + asyncio (no threading), type hints
|
||||
everywhere, structured `logging` (no `print`). **Desktop CLI (Node ≥21):**
|
||||
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Full
|
||||
per-language style and the dev loop live in CLAUDE.md → "Code Style".
|
||||
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Contributor
|
||||
commands and the development loop live in `CONTRIBUTING.md`.
|
||||
|
||||
## Review guidelines
|
||||
|
||||
@@ -94,6 +117,40 @@ a staging branch.
|
||||
- Prioritize findings that warrant holding the merge. State the impacted path
|
||||
and the concrete failure mode.
|
||||
|
||||
## Automated public issue triage
|
||||
|
||||
New public issues may receive one clearly labeled **Hermes-Relay automated
|
||||
triage** reply. That first response may classify the report with existing
|
||||
type/area labels, point to related issues or current code/docs, ask for safe
|
||||
sanitized diagnostics, and flag the thread for maintainer review.
|
||||
|
||||
GitHub attributes that reply to the repository-scoped
|
||||
`hermes-relay-triage[bot]` App, never to a maintainer's personal account.
|
||||
|
||||
The automated lane may assign only the fixed maintainer account `Codename-11`
|
||||
as follow-up ownership; that assignment does not imply acceptance, priority,
|
||||
implementation, or a release commitment. It never closes, milestones,
|
||||
prioritizes, promises a fix/release/timeline, chooses another assignee, or
|
||||
continues replying after its first response. A related issue is not
|
||||
automatically a duplicate. Human maintainer comments and decisions remain
|
||||
authoritative; read the complete live thread before acting on an issue.
|
||||
|
||||
## Automated public PR intake
|
||||
|
||||
New external-contributor, non-draft pull requests may receive one clearly
|
||||
labeled **Hermes-Relay automated PR intake** reply from
|
||||
`hermes-relay-triage[bot]`. Owner-authored `Codename-11` PRs and bot PRs are
|
||||
dropped before model dispatch. For eligible PRs, the intake compares the live PR
|
||||
metadata/body and changed-path list with trusted `origin/dev` policy and
|
||||
`.github/pull_request_template.md` without checking out or executing contributor
|
||||
code. It may add genuine area labels plus `documentation`, `ci`, or
|
||||
`needs-maintainer-review` and point out missing intake evidence.
|
||||
|
||||
The automated lane never approves, requests changes, merges, closes, assigns,
|
||||
requests reviewers, milestones, prioritizes, pushes commits, edits PR text,
|
||||
reruns workflows, applies `review-candidate`, or claims code correctness. Human
|
||||
maintainer review and CI remain authoritative.
|
||||
|
||||
## Public-repo writing hygiene
|
||||
|
||||
Everything committed is public. In CHANGELOG, DEVLOG, README, docs, and release
|
||||
|
||||
@@ -8,16 +8,252 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
### Added
|
||||
|
||||
- Provider usage shows Grok subscription periods, product usage, and on-demand credit state for hosts signed in with `xai-oauth`. Android shows SuperGrok by default when no provider visibility choice is saved.
|
||||
- Guided Secure Link setup in Dashboard and the Desktop Relay pane, with shared read-only host CLI checks, restart instructions, and signed pairing handoff.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Desktop tray notices, screenshot evidence, and grant prompts stay reusable after dismissal; screenshot evidence keeps the most recently selected image. (#606)
|
||||
- Proactive phone Thread messages render relay-token and host-path media as attachments while preserving multiline text; notification previews omit media markers. (#485)
|
||||
- Desktop computer screenshots attach validated image bytes to the host tool result instead of returning base64 as plain text.
|
||||
- Relay-owned media uploads are removed on token expiry, eviction, and shutdown; media activity logs omit tokens, file paths, and screenshot bytes.
|
||||
- Plugin screenshot and navigation tools resolve Android's authenticated media token, attach the actual bounded image to host vision, and keep legacy inline screenshots readable. (#593)
|
||||
- Android Chat can open the model picker before the first turn, loads Gateway models when opened, and distinguishes loading, unavailable, and empty catalogs.
|
||||
- Secure Link configuration failures leave ordinary Relay available; route details and pairing previews resolve the advertised service namespaces.
|
||||
- Dashboard pairing QR codes support larger certificate-bearing Secure Link invites.
|
||||
- Secure Link preserves Gateway ticket authentication and Dashboard login paths, bounds rewritten responses, and serves compatible health information without additional loopback probes.
|
||||
- Android Secure Link enforces the paired certificate pin for HTTP, Gateway, and voice traffic, retains the correct TLS policy during Gateway route changes, and displays the active HTTPS Dashboard route.
|
||||
- Android cold start restores the saved Appearance palette and platform light/dark mode before the first app frame.
|
||||
- Android Gateway onboarding verifies Dashboard access without overstating Chat or voice readiness, explains common authentication setup failures, and requires exact-address consent before using HTTP. Custom Dashboard ports are accepted and shown throughout setup and route editing. (#604)
|
||||
- Android safely settles Gateway foreground-service starts before stopping local retention, preventing the startup/shutdown race reported in #603. Turning off always-on connectivity preserves active turns.
|
||||
- Android Standard Voice speaks live background completions in its active conversation after the original reply finishes. Stop and conversation changes discard pending speech. (#545)
|
||||
|
||||
## [Android 1.17.0] - 2026-09-13
|
||||
|
||||
### Added
|
||||
|
||||
- Optional voice controls over other apps in Google Play, with contextual permission setup, a persistent Stop voice notification, and session shutdown on screen lock or permission loss. Phone control remains sideload-only.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Android shows standalone response cards without an outer bubble, uses subtler assistant surfaces, and places delivery status beside message timestamps.
|
||||
- Android answers upstream Clarify batches one question at a time, with independent choices, custom answers, and confirmed progress preserved across reconnects. (#474)
|
||||
- Android context previews mark phone status and turn context as unavailable in Gateway chats instead of claiming they are sent. Settings clarify that automatic phone-status sharing applies to API-only chats. (#556)
|
||||
- Android shows Hermes profile display names and groups the resolved server default under its agent identity, while preserving explicit profile selection and saved conversations.
|
||||
|
||||
## [Plugin 1.11.3] - 2026-09-13
|
||||
|
||||
### Fixed
|
||||
|
||||
- Relay Dashboard WebSockets work with current Hermes authentication helpers while preserving older-host compatibility, single-use tickets, Host/Origin/IP checks, and Relay session authentication.
|
||||
|
||||
## [Android 1.16.1] - 2026-09-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- Android Dashboard-only connections start the profile-scoped session directory before Gateway readiness, so a cold launch no longer leaves both the directory and passive Gateway socket waiting on each other. (#495, #528)
|
||||
|
||||
## [Android 1.16.0] - 2026-09-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- Android no longer crashes when a route probe finishes while a network change invalidates the endpoint cache.
|
||||
- Android opens an authenticated Gateway chat on the first foreground launch instead of waiting for a background-and-resume cycle to leave the waking state. (#495, #528)
|
||||
- Android Dashboard sign-in removes pasted line breaks from username and password fields, matching the browser login while preserving every other credential character. (#541)
|
||||
- Android keeps saved Dashboard sign-ins bound to their connection when switching gateways, rather than letting a stale resolver route invalidate another connection's session.
|
||||
- Bot Mode no longer crashes when different connections have bots with the same profile name. Both the conversation list and Active Now strip preserve each bot's connection, and opening progress appears only on the selected bot.
|
||||
- Android feedback uses themed banners and action cards instead of platform toasts and default snackbars. Dashboard errors no longer misidentify missing resources as an outdated Relay. Developer settings includes local-only message previews.
|
||||
- Missing chat attachments show their error and retry in the attachment card without repeated global popups. Global action messages occupy the top message area instead of covering the composer.
|
||||
- Chat distinguishes session preparation from response streaming and retains initialization errors that arrive before the session acknowledgement. Long-press the agent header to open a live session-diagnostics drawer.
|
||||
- Delegated-agent activity survives parent replies and leaves compact history entries for later read-only review. The activity strip appears only while work runs; historical process views cannot stop or dismiss live work. (#447)
|
||||
|
||||
## [Plugin 1.11.2] - 2026-09-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay tool availability avoids repeated Windows loopback delays and preserves multi-PC capabilities.** Host-local Android, Desktop, and Phone paths use explicit IPv4 loopback, while Desktop checks share a bounded health snapshot that preserves per-client advertisements and fails closed when Hermes-Relay is unavailable. (#562, #563)
|
||||
- **`android_*` tools resolve bridge credentials written after host startup.** Requests retry profile-scoped env and active bridge-session credentials after a stale token is rejected, and vision navigation now shares the same current Relay transport instead of the retired standalone default.
|
||||
- **`android_setup` accepts both its canonical and legacy schema keys.** `bridge_session_token` and `pairing_code` are accepted, while a missing token returns a structured error.
|
||||
- **Android tool setup tests use a temporary Hermes home.** Test runs no longer write bridge settings into a developer environment.
|
||||
|
||||
## [Android 1.15.1] - 2026-09-02
|
||||
|
||||
### Changed
|
||||
|
||||
- Chat and Bot Chat offer a compact Correct now / Queue next tray behind the composer. Chat settings sets the default; each message can override it. Stop pauses pending work until Resume, and editing or removing queued messages preserves the remaining order.
|
||||
- Wider Chat and Voice layouts keep text and controls centered and readable, including landscape Voice Focus.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Delivery and correction labels remain readable inside user-message bubbles.
|
||||
- Voice errors use a scrollable dialog with separate Retry and Dismiss actions.
|
||||
- Attachment previews stay open through rotation, and videos retain their original proportions. (#483)
|
||||
- Release builds preserve the native configuration names required for wake-word startup. (#444)
|
||||
- Standard Hermes attachments stream to disk while enforcing download size limits. (#531)
|
||||
- Session refresh no longer sustains a request loop. History loads, chat rendering, image previews, and media exports keep memory use bounded.
|
||||
- Image-generation progress remains visible between interim replies and media delivery.
|
||||
- New Gateway chats wait for session readiness before the first prompt; ownership refusals preserve the retryable prompt and server error.
|
||||
|
||||
## [0.4.0-beta.7] - 2026-09-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- Windows updates detect a colocated management UI, report both installed versions, and update the CLI and UI together through the verified bundle installer. CLI-only installations keep their standalone updater.
|
||||
|
||||
## [Android 1.15.0] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android prefers current upstream Hermes for standard media, Git, usage, and notices.** Authenticated Dashboard file delivery, current-session `/api/git/*`, Gateway `usage.bars`, and keyed agent notices work without the optional Hermes-Relay Plugin; Relay remains additive for older-host media compatibility, sensitivity metadata, repository discovery and guarded mutations, multi-provider usage, and true Relay tools.
|
||||
- **Android Settings separates standard Hermes from Relay tools.** Media now sits with Chat and Voice under Hermes, while proactive Threads, Terminal, Notification Companion, Relay sessions, and Device Control remain clearly grouped behind the optional plugin.
|
||||
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
|
||||
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Standard Hermes attachments no longer demand Relay pairing.** Host-local images, audio, video, and files download through the authenticated Dashboard, stay loaded across history reconciliation, and fall back to one neutral compatibility card on older hosts instead of flashing `Relay URL not configured` or retrying indefinitely.
|
||||
- **Removing optional Relay does not strand Standard voice or leak preferences across connections.** Runtime fallback keeps Dashboard voice usable, preserves configured choices through temporary outages, and normalizes only connection-scoped named-profile settings after explicit Relay removal.
|
||||
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
|
||||
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
|
||||
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
|
||||
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
|
||||
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
|
||||
- **Android Chat settles an owned Gateway turn when its terminal frame is lost.** An exact idle `session.active_list` snapshot now completes the matching local stream, reconciles durable history, and drains its queued follow-up without interrupting or claiming Desktop/TUI work.
|
||||
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
|
||||
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
|
||||
|
||||
## [Plugin 1.11.1] - 2026-08-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
|
||||
- **Relay prompt context advertises only real callable phone tools.** Phone-control and cross-platform delivery guidance now follows the exact selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` capabilities.
|
||||
|
||||
## [Android 1.14.0] - 2026-08-30
|
||||
|
||||
### Added
|
||||
|
||||
- **Android can preview delegated agent work without leaving the parent chat.** The current-chat activity sheet shows bounded lifecycle, progress, and tool previews for concurrent children, opens vanilla Hermes child history read-only when the Gateway exposes it, and stays explicit when reconnect gaps or older routes leave details unavailable. (#447)
|
||||
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden. An updated optional Hermes-Relay Plugin is required for Git operations.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Connections now explain and recover each Dashboard, Relay, and optional API route independently.** LAN, Tailscale, and public HTTPS can fail over without allowing an unauthenticated or different-origin Relay route to borrow Dashboard credentials. Protected same-origin Relay health challenges are recognized as authentication boundaries instead of outages. An updated optional Hermes-Relay Plugin is required for same-origin Relay ingress. (Related: #399)
|
||||
- **Android What's New leads with one curated release highlight without interrupting startup.** A timed post-update toast can be swiped or closed, previews additional feature/fix counts when a release has meaningful secondary items, expands into the centered highlight view on request, and keeps the full technical history available. Each release can present one plain-language summary, up to three primary benefits, and up to two quieter improvements, while release checks keep the structured entry, fallback, Play copy, and public release records aligned.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android wake-word detection now loads a compatible native ONNX Runtime.** Packaged sherpa and Java JNI consumers are checked against the shared runtime for every supported ABI before release. (#444)
|
||||
- **Android Continuous voice waits for barge-in microphone teardown before listening again.** Multi-turn hands-free conversations no longer lose the microphone after a response finishes with barge-in enabled. (#464)
|
||||
- **Opening Android no longer claims or interrupts a turn already running in Hermes Desktop/TUI.** Passive foreground and session browsing now use read-only Gateway status plus profile-scoped history; live-session resume remains reserved for explicit Android actions and exact Android-owned recovery. (Related: #365)
|
||||
- **Android provisional Threads can be removed without touching server history.** The drawer now offers a local-only removal action, reconciles promoted phone sessions without duplicate rows, and keeps Thread routing isolated to the active saved connection. (#461)
|
||||
- **Android Clarify cards make custom answers explicit and keyboard-friendly.** Choice prompts label their Other answer field, submit trimmed text from the keyboard, and do not restore an authoritatively expired prompt after session navigation. (#446)
|
||||
- **The visible Android Sphere keeps its smooth procedural motion across startup and chat.** Backgrounded and motion-disabled surfaces remain still without reducing foreground animation to a stepped ambient pulse.
|
||||
- **Android Voice Focus keeps Stop and immediate spoken steering available across every interaction mode.** Hold-to-talk now interrupts Thinking and Transcribing turns before capturing the replacement direction, remains operable through TalkBack, Switch Access, and keyboard controls, preserves pointer press-and-release behavior across floating controls, and Google Play no longer offers the sideload-only system overlay action.
|
||||
- **Android Assistant sessions explain when no speech was captured instead of appearing stuck at Ready.** Retry feedback survives the separate system overlay process, recreated session UI requests the current turn state, and locked sessions keep transcript, response, and technical error text private. (Related: #424)
|
||||
- **Android New Chat keeps the current profile and stays fresh across profile switches.** Starting from All Profiles no longer forces the literal default profile, choosing another profile from an empty draft no longer reopens that profile's previous session after route settlement or restart, and leaving a provisional phone Thread cannot route the next turn to its old chat under the new profile. (#436)
|
||||
- **Android Dashboard connections and profile drawers no longer wait on unavailable optional routes.** Dashboard, API fallback, and Relay probes run independently; API/Relay never gate a normal Dashboard connection, Gateway auth/ticket failures are not blindly retried, and authenticated session history remains available without a live Gateway socket. Concurrent route probes are shared and generation-safe, healthy same-priority routes win immediately, superseded session reads cancel their HTTP calls, and optional PR decoration stays outside the session-list critical path.
|
||||
|
||||
### Removed
|
||||
|
||||
- **Android Chat no longer includes the hidden clean-focus presentation.** The long-press gesture, overlapping instructional pill, reduced composer, and alternate fading transcript were removed so Chat keeps one complete interaction model. Voice Focus remains available.
|
||||
|
||||
## [Plugin 1.11.0] - 2026-08-30
|
||||
|
||||
### Added
|
||||
|
||||
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
|
||||
- **Relay extensions can use the authenticated Dashboard origin as one network ingress.** Fixed allowlisted HTTP and WebSocket paths proxy to the local Relay while Dashboard admission and Relay session authentication remain separate. (Related: #399)
|
||||
|
||||
### Changed
|
||||
|
||||
- **Hermes-Relay Dashboard management is organized around operator tasks.** Overview, Devices, Activity, Remote Access, Git, and Settings now have separate native Dashboard surfaces; pairing is QR-first, paired clients use responsive cards, and token-backed media is labeled as a bounded diagnostic instead of a health counter. (#486)
|
||||
- **Dashboard, CLI, and TUI pairing advertise the same explicit route set.** Recommended Tailscale uses dedicated HTTPS `:10443` for local Dashboard `:9119`, public HTTPS and LAN stay visible fallbacks, and old `:443`/`:9119` plus direct `:8767` remain migration compatibility.
|
||||
- **Pairing receipts explain transport protection before exposing an invite.** Per-surface probes distinguish application TLS, tailnet encryption, optional API fallback, and authenticated Relay ingress.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Public and roaming pairing no longer invent closed direct Relay or Dashboard ports.** Exact Dashboard origins own their same-origin Relay paths, ambiguous or plaintext public candidates fail closed, and inactive optional API routes are omitted.
|
||||
- **Dense pairing QRs scan reliably.** Dashboard, CLI, and TUI render integer-sized modules with a full quiet zone.
|
||||
- **Remote-access migration keeps existing listeners safe.** Recommended setup avoids taking over `:443`, explicit legacy cleanup remains available, and default disable actions remove only the listeners they own.
|
||||
|
||||
## [0.4.0-beta.6] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
- **Hermes-Relay CLI+UI preserves the complete multi-route pairing topology.** Dashboard, Relay, optional API, priorities, and transport protection remain attached to one saved host across LAN, Tailscale, and public routes. (Related: #399)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Desktop rejects Dashboard-ingress Relay dials until it can mint Dashboard WebSocket tickets.** The daemon and host selector choose a compatible direct Relay fallback instead of attempting an unauthenticated same-origin ingress.
|
||||
- **API-less pairing remains valid.** Dashboard and direct Relay routes can pair without inventing an optional API server, while secure-first ranking keeps plain LAN as the final fallback.
|
||||
|
||||
## [Android 1.13.2] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Android Supervised Mode presents a parent-controlled, profile-pinned chat surface.** Parents can limit attachments, Standard voice, generated media, conversation history, actions, and technical metadata while device authentication protects full settings. Hermes-Relay can identify and revoke a paired supervised client without becoming the policy enforcement boundary.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android session rows stay neutral when optional live activity is unavailable or still loading.** Directory refreshes no longer restore a persistent Checking state, and full-row activity borders are reserved for actual Starting or Working turns.
|
||||
- **Returning from parent settings keeps Supervised Chat rendered.** Parent access now relocks without rebuilding the active navigation graph, and full Settings keeps a prominent shortcut back to Supervised Mode controls.
|
||||
|
||||
## [Android 1.13.1] - 2026-08-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android session activity now follows live Hermes runtime truth.** Working, Starting, Needs input, Idle, Checking, Unavailable, and Background work no longer come from the Dashboard's five-minute recency hint, and only complete, unambiguously resolved live snapshots clear stale state.
|
||||
|
||||
## [Android 1.13.0] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Provider usage and limits are available from top-level Settings.** Codex credential pools, Nous balances, and OpenCode Go account windows share one provider-neutral screen with Summary, Expanded, and Hidden presentation modes. Provider credentials remain on the Hermes host.
|
||||
- **Android Bot Mode provides one messenger-style workspace across saved Hermes gateways.** Bots and read-only group rooms aggregate without changing the foreground connection, Bot Chats retain exact gateway/profile ownership, and unavailable gateways keep clearly marked last-known roster entries.
|
||||
- **Android Assistant screen context.** Compatible unlocked assistant-button invocations can open Hermes, begin listening, and include bounded visible text plus an available screenshot in the first Standard voice turn. Ordinary wake and keyguard invocations remain screen-context free.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Release and candidate names use one public product hierarchy.** Future releases use `Hermes-Relay Android`, `Hermes-Relay Plugin`, or `Hermes-Relay CLI+UI` display names, while isolated Android review and release-candidate installs use `HR Candidate`, without changing immutable tags, package identities, updater contracts, or artifact filenames.
|
||||
- **Review candidates are an explicit PR opt-in with one trusted handoff comment.** Maintainers can apply `review-candidate` for exact-head Android and Relay bundles; a separate reporter updates the PR with the artifact, expiry, source SHA, and bounded review instructions without executing fork code with write permission.
|
||||
- **Unlabeled PR updates no longer receive false candidate-failure comments.** The trusted reporter ignores skipped review-bundle workflow shells before reading artifacts or writing to a PR.
|
||||
- **Android releases and review candidates use clear public product names.** Stable builds use `Hermes-Relay Android`, while isolated review installs use `HR Candidate` without changing package identities or update contracts.
|
||||
- **Review candidates are explicit and source-pinned.** Maintainers can opt a PR into a matched Android and Relay bundle with checksums, expiry, source SHA, and bounded review instructions.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Unlabeled PR updates no longer receive false candidate-failure comments.** The trusted reporter ignores skipped review-bundle workflow shells before reading artifacts or writing to a PR.
|
||||
- **Android chats no longer retain a stale busy composer.** A completed Gateway bubble settles automatically when its exact session has no live or detached turn, new-chat navigation clears stale visible ownership, and Stop remains an immediate escape hatch. (#416, #418)
|
||||
- **README and Google Play onboarding now match the Dashboard-first product path.** Public setup copy names the two separate Dashboard QR actions, treats the API server as an advanced fallback, explains the encouraged Hermes-Relay extension without implying Play includes Device Control, and ships one current deterministic Android screenshot set.
|
||||
- **The Android Sphere remains gently animated while visibly idle.** New chats and the ambient Sphere behind messages now use a low-cost layer breath, while hidden/backgrounded and motion-disabled surfaces stay still and active agent/voice states retain their full procedural animation.
|
||||
- **Android retries Windows-hosted `MEDIA:` attachments through Relay's by-path route.** A document deferred on cellular no longer treats `C:\...` as an opaque media token and reports it as expired.
|
||||
|
||||
## [Plugin 1.10.0] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Relay provides normalized provider usage without exposing credentials.** The authenticated Dashboard route resolves the active Codex pool entry, structured Nous balances, and OpenCode Go windows on the Hermes host; explicitly enabled paired clients receive the same provider-neutral schema.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Plugin releases use the `Hermes-Relay Plugin` public name.** The display name is aligned with Android and CLI+UI while the `server-v*` compatibility tag remains unchanged.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay profile discovery follows `HERMES_HOME` by default.** Custom Hermes installations surface their real default profile and persist Relay sessions beside the active config while retaining the explicit `RELAY_HERMES_CONFIG` override.
|
||||
|
||||
## [0.4.0-beta.5] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Desktop releases now include a Linux ARM64 CLI artifact.** The one-line installer, updater, checksums, release publication, architecture validation, and platform documentation all recognize the same `linux-arm64` binary.
|
||||
- **The public site now shows the real Windows CLI UI and guides each surface through first use.** Deterministic public-safe screenshots cover connection, host access, activity, computer control, and updates.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Desktop releases use the `Hermes-Relay CLI+UI` public name.** The beta keeps its existing `desktop-v*` tag and updater contract.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Desktop install and update discovery remains reliable in a multi-surface release repository.** Every resolver paginates GitHub releases before choosing the SemVer maximum, Windows cooperative updates clean their released backup, unsigned preview installers retain the normal SmartScreen warning, and release smoke tests preserve real exit codes.
|
||||
- **Desktop daemon connections recover instead of exiting after an interrupted Relay socket.** Healthy daemons retry through Relay restarts and repeated failed reconnect attempts, oversized desktop-tool results fail within a bounded response instead of closing the shared WebSocket, and terminal failures leave an accurate stopped status for the tray.
|
||||
- **Desktop computer control follows Hermes' current CUA Driver contract.** CUA Driver 0.20 and newer are accepted when their manifest, daemon/MCP arguments, required tools, and canonical path remain compatible, and Windows sessions use the manifest-declared direct standard-mode runtime instead of a potentially stale machine-wide daemon. Current 0.21 installations no longer fall back solely because of an obsolete upper version pin or daemon contract.
|
||||
|
||||
@@ -73,7 +309,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
- **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
|
||||
@@ -1130,7 +1365,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
- **Voice-exit chime firing on every Add-connection tap.** `ConnectionSwitchCoordinator.switchConnection` fires the `voiceStopCallback` unconditionally at step 3 (correct for connection-to-connection switches while voice is active), but `beginAddConnection` also routes through `switchConnection` to bind the placeholder Connection's auth store before the pair wizard runs — and `VoiceViewModel.exitVoiceMode()` was playing `sfxPlayer.playExit()` regardless of whether voice mode was actually on. Logcat confirmed the chime on every Add-connection FAB tap. Fix adds an idempotence guard at the top of `exitVoiceMode()`: early-return when `_uiState.value.voiceMode` is already false. Teardown is still safe to skip because every inner statement is null-guarded + try/catch-wrapped and would be a no-op on an already-stopped voice session; the only meaningful line is the `playExit()` SFX, which is what we're silencing.
|
||||
- **500 ms freeze on every Add-connection tap.** `ConnectionSwitchCoordinator.switchConnection` runs a `withTimeoutOrNull(AUTH_HYDRATE_TIMEOUT_MS = 500L)` block at step 10 to wait for the freshly-bound `AuthManager` to flip `AuthState` from `Loading` to `Paired`. The comment acknowledged Add-connection is the common path and the 500 ms was meant to be "imperceptible," but on-device it wasn't — the user perceived the delay (and the voice chime masking it) on every tap. The placeholder Connection created by `beginAddConnection` has `pairedAt == null` and an empty EncryptedSharedPreferences store, so `AuthState` will NEVER reach `Paired` — the 500 ms is pure stall. Fix short-circuits the hydrate wait when `target.pairedAt == null`: skip `withTimeoutOrNull` entirely for placeholders and log at DEBUG instead of the misleading "auth hydrate timeout" INFO. Real paired-to-paired switches still run the full hydrate wait because both sides have `pairedAt != null`.
|
||||
- **KDoc nested-comment trap in `ConnectionViewModel.relayReady` doc block.** A literal `/voice/*` path pattern inside the `relayReady` KDoc opened a nested block comment (Kotlin supports nested `/* */`, Java does not) whose `*/` then closed only the nested level — leaving the outer `/**` open for the remaining ~2200 lines of the file. Symptom: `MainActivity.kt:67` "Unresolved reference 'isReady'" plus ~50 cascading "Cannot infer type" errors across `PairedDevicesScreen`, `SettingsScreen`, `TerminalScreen`. Real errors (`Missing '}`, `Unclosed comment`) were the last two lines of `./gradlew compileGooglePlayDebugKotlin` output, easy to miss. Fix was a two-character rewrite: path patterns now wrapped in backticks AND `/*` → `/...` so the glob-looking character isn't in a block-comment position. Lesson logged in `DEVLOG.md` 2026-04-21; worth a sweep of other KDoc blocks for shell/regex-looking patterns before the next large diff.
|
||||
- **KDoc nested-comment trap in `ConnectionViewModel.relayReady` doc block.** A literal `/voice/*` path pattern inside the `relayReady` KDoc opened a nested block comment (Kotlin supports nested `/* */`, Java does not) whose `*/` then closed only the nested level — leaving the outer `/**` open for the remaining ~2200 lines of the file. Symptom: `MainActivity.kt:67` "Unresolved reference 'isReady'" plus ~50 cascading "Cannot infer type" errors across `PairedDevicesScreen`, `SettingsScreen`, `TerminalScreen`. Real errors (`Missing '}`, `Unclosed comment`) were the last two lines of `./gradlew compileGooglePlayDebugKotlin` output, easy to miss. Fix was a two-character rewrite: path patterns now wrapped in backticks AND `/*` → `/...` so the glob-looking character isn't in a block-comment position. Lesson logged in `docs/project/DEVLOG.md` 2026-04-21; worth a sweep of other KDoc blocks for shell/regex-looking patterns before the next large diff.
|
||||
|
||||
- **Orphan placeholder connections from abandoned Add-connection flows.** The `beginAddConnection` path pre-creates a placeholder Connection and switches to it before the pair wizard runs — so `applyPairingPayload` lands the token in the right auth store. Previously, cleanup of the placeholder was wired only to the explicit Cancel button and TopAppBar back arrow. System back (gesture back / predictive back) bypassed that branch, leaving the placeholder in the connection list forever. Two-part fix: (a) `PairScreen` now installs a `BackHandler` that routes system back through the same `onCancel` → `discardPlaceholderConnection` branch the explicit back arrow uses; (b) `ConnectionViewModel.init` sweeps for any existing orphans (tuple: `pairedAt == null && apiServerUrl.isBlank() && label == PLACEHOLDER_LABEL`) on cold start and removes them — the tuple cannot be produced by any real pairing, so the sweep is safe without a dry-run. If the active connection at startup points at an orphan, the sweep switches to the first surviving real connection before deleting. Fixes the "why does my chip say 'New connection…'" symptom on devices that were affected pre-fix.
|
||||
- **Pair flow now auto-starts the camera on Add connection.** `ConnectionWizard` gains an `autoStart: String?` param (currently only `"scan"` is honored). The Add-connection FAB on `ConnectionsSettingsScreen` passes it so the wizard fires the camera permission launcher on first composition instead of forcing users through the Method chooser — one obvious next step, one-tap flow. Re-pair surfaces intentionally leave `autoStart` null so the full Scan / Enter code / Show code chooser stays available there. The deep-link arg is plumbed through `Screen.Pair`'s route (`pair?connectionId=...&autoStart=...`) and `PairScreen`'s new `autoStart` param; unrecognized values fall through to the default Method step so future builds can add more targets without breaking old ones.
|
||||
@@ -1947,7 +2182,7 @@ picker.
|
||||
- **`CLAUDE.md`** — updated Git section with the new branching policy,
|
||||
added file-table entries for `hermes-relay-update`,
|
||||
`register_code_command`, and the expanded `install.sh`
|
||||
- **`TODO.md`** — captures open research questions around proper
|
||||
- **`docs/project/TODO.md`** — captures open research questions around proper
|
||||
Hermes plugin/skill/tool distribution
|
||||
- **`user-docs` vitepress site** — new "For AI Agents" copy-paste
|
||||
block on the home view, Feature Matrix component, two-track explainer,
|
||||
|
||||
@@ -1,525 +1 @@
|
||||
# Hermes-Relay — Claude Code Adapter
|
||||
|
||||
> Read [AGENTS.md](AGENTS.md) first. It is the provider-neutral canonical agent
|
||||
> context. Branch, release, staging, and hotfix rules live in `AGENTS.md` and
|
||||
> [RELEASE.md](RELEASE.md); this file only adds Claude-specific project and tool
|
||||
> guidance. Then read `docs/spec.md` and `docs/decisions.md`.
|
||||
|
||||
## What This Is
|
||||
|
||||
A native Android app (Kotlin + Jetpack Compose) paired with an optional Python relay plugin/server (aiohttp) for the Hermes agent platform. Vanilla Hermes chat, Manage, and dashboard voice work against unmodified upstream Hermes. The Relay plugin adds phone control, terminal, remote desktop tooling, extra voice engines, and dashboard Relay management via the official Hermes web dashboard.
|
||||
|
||||
**Current state:** Reference latest released version for stable state and current dev branch for working state. The default no-plugin path supports chat, Manage, and voice on vanilla upstream Hermes. Chat auto-prefers the dashboard `/api/ws` gateway transport when Manage auth is ready, then falls back to API-server SSE routes. Vanilla Hermes voice uses dashboard `/api/audio/*` with the Manage session. Relay remains an additive power path for terminal, bridge/device control, notification companion, extra/provider-native voice, remote access, and desktop tooling. Two Android product flavors ship: `googlePlay` (conservative, no unattended Device Control surface) and `sideload` (full-capability).
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Phone (WS) -> Hermes dashboard (:9119) [vanilla Hermes gateway chat, live thinking]
|
||||
Phone (HTTP/SSE) -> Hermes API Server (:8642) [vanilla Hermes chat fallback, sessions, runs]
|
||||
Phone (HTTP) -> Hermes dashboard (:9119) [vanilla Hermes Manage + voice]
|
||||
Phone (WSS/HTTP) -> Relay plugin/server (:8767) [optional bridge, terminal, relay voice, remote tools]
|
||||
```
|
||||
|
||||
The Vanilla Hermes path must stay upstream-only. API-server bearer auth and dashboard cookie auth are separate. Terminal and bridge require Relay pairing; Vanilla Hermes chat, Manage, and dashboard voice must not.
|
||||
|
||||
### Upstream Hermes API Reference
|
||||
|
||||
**IMPORTANT:** Always verify endpoints against the actual hermes-agent source (`gateway/platforms/api_server.py`). The upstream repo is the source of truth — not our docs, not our memory, not assumptions from other frontends.
|
||||
|
||||
**Vanilla Hermes endpoints (confirmed in hermes-agent source):**
|
||||
|
||||
|
||||
| Endpoint | Purpose | Tool Call Format |
|
||||
| --------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `POST /v1/chat/completions` | OpenAI-compatible chat (stream=true for SSE) | Inline markdown text (``💻 terminal``) — no separate tool events |
|
||||
| `POST /v1/runs` | Start an agent run | Returns `run_id` |
|
||||
| `GET /v1/runs/{run_id}/events` | SSE stream of run lifecycle events | **Structured events**: `tool.started`, `tool.completed`, `message.delta`, `reasoning.available`, `run.completed`, `run.failed` |
|
||||
| `POST /v1/responses` | OpenAI Responses API format | Structured `function_call` objects (non-streaming only) |
|
||||
| `GET /v1/capabilities` | Machine-readable feature + endpoint discovery | Use before assuming optional surfaces exist |
|
||||
| `GET /v1/models` | List available models | — |
|
||||
| `GET /v1/skills` | Read-only skill list for the API-server agent | `{"object":"list","data":[...]}` |
|
||||
| `GET /v1/toolsets` | Read-only API-server toolset inventory | `{"object":"list","platform":"api_server","data":[...]}` |
|
||||
| `GET/POST/PATCH/DELETE /api/sessions/*` | Native session CRUD, messages, fork, sync chat, SSE chat | Upstream merged via NousResearch/hermes-agent PR #33134 |
|
||||
| `GET /health` | Health check | — |
|
||||
| `GET/POST/PATCH/DELETE /api/jobs/*` | Cron job management (api_server surface) | — |
|
||||
|
||||
|
||||
**Compatibility endpoints (not all native upstream API-server routes):**
|
||||
|
||||
Upstream main now contains the focused session-control API (`#33134`) and read-only skills/toolsets (`#33016`). The original broad PR [#8556](https://github.com/NousResearch/hermes-agent/pull/8556) was closed as superseded. Keep these distinctions straight:
|
||||
|
||||
1. **Native upstream** — `/api/sessions`, `/api/sessions/{id}/messages`, `/api/sessions/{id}/chat`, `/api/sessions/{id}/chat/stream`, `/v1/capabilities`, `/v1/skills`, and `/v1/toolsets` exist in current `gateway/platforms/api_server.py`.
|
||||
2. **Bootstrap compatibility** (`plugin/hermes_relay_bootstrap/`) — monkey-patches aiohttp on startup via `.pth` file, injecting only compatibility-only surfaces (session search, memory, legacy skill detail/toggle, config, available-models, slash middleware). Sessions CRUD/messages/fork and the legacy skills list are **retired** — native upstream owns them (#33134/#33016) and the bootstrap carries no fallback for old builds. Native routes still win per method/path for the remaining set. The repo-root `hermes_relay_bootstrap/` package is a legacy import shim.
|
||||
3. **Legacy fork branches** — useful as lineage only. Do not cite `feat/session-api` / `#8556` as the current upstream contract.
|
||||
|
||||
|
||||
| Endpoint | Purpose | Provided by |
|
||||
| -------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `GET /api/sessions` (CRUD) | Session list/create/rename/delete/fork | Native upstream (#33134); bootstrap injection retired |
|
||||
| `GET /api/sessions/{id}/messages` | Conversation history | Native upstream (#33134); bootstrap injection retired |
|
||||
| `POST /api/sessions/{id}/chat` | Synchronous session chat | Native upstream (#33134) |
|
||||
| `POST /api/sessions/{id}/chat/stream` | Session-based SSE chat | Native upstream (#33134); bootstrap does NOT inject |
|
||||
| `GET /v1/skills`, `GET /v1/toolsets` | Read-only skill/toolset discovery | Native upstream (#33016) |
|
||||
| `GET /api/sessions/search` | Full-text message search | Bootstrap/fork legacy; not in current upstream main |
|
||||
| `GET /api/config`, `PATCH /api/config` | Personalities + model config | Bootstrap/fork legacy or dashboard web-server surface; not current API-server upstream |
|
||||
| `GET /api/skills/{name}` | Legacy skill detail | Bootstrap compat; list (`GET /api/skills`) retired — use native `/v1/skills` |
|
||||
| `PUT /api/skills/toggle` | Enable/disable installed skill | `hermes_cli/web_server.py` dashboard surface; bootstrap stub returns 501 |
|
||||
| `GET/POST/PATCH/DELETE /api/memory` | Memory CRUD | Bootstrap/fork legacy; not current API-server upstream |
|
||||
| `GET /api/available-models` | Provider model list | Bootstrap/fork legacy; not current API-server upstream |
|
||||
|
||||
|
||||
The Android client probes per-endpoint capability via `HermesApiClient.probeCapabilities()` (returns `ServerCapabilities`). When `streamingEndpoint = "auto"`, `ConnectionViewModel.resolveStreamingEndpoint()` picks `sessions`, `completions`, or `runs` based on the capability snapshot.
|
||||
|
||||
**Dashboard web server (separate surface — standard Manage / Desktop remote gateway):**
|
||||
|
||||
hermes-agent ships a second web server at `hermes_cli/web_server.py` that hosts the React admin dashboard at `hermes_cli/web_dist/`. It has its **own** `/api/*` routes that **do not live on `api_server.py`** — notably: `GET/PUT /api/config` (full tree), `GET /api/config/schema`, `GET /api/config/defaults`, `GET/PUT /api/config/raw` (YAML text), `GET/PUT/DELETE /api/env` + `POST /api/env/reveal`, `PUT /api/skills/toggle`, `/api/cron/jobs/*` (different shape from `/api/jobs/*`), `/api/providers/oauth/*`, `/api/dashboard/themes`, `/api/dashboard/plugins`, `/api/model/info` + `/api/model/options` + `POST /api/model/set`, `/api/profiles/*` (CRUD, `POST /api/profiles/active`, per-profile soul/description/model), `/api/mcp/*`, `/api/logs`, `/api/analytics/usage`, and `**POST /api/audio/transcribe` + `POST /api/audio/speak`** (base64 data-url contract, built for hermes-desktop voice). The API server has **no audio routes** — its `/v1/capabilities` advertises `audio_api: false`; PR #8199 (`/v1/audio/*`) is the canonical future surface but is unmerged. Android's **Vanilla Hermes (no-plugin) voice** therefore rides this dashboard surface via `StandardHermesVoiceClient` with the per-connection dashboard cookie session (Manage sign-in unlocks voice); `AutoVoiceAudioClient` prefers Relay when paired and falls back to standard.
|
||||
|
||||
Current upstream supports two auth modes on this surface. Loopback dashboards still use the injected `window.__HERMES_SESSION_TOKEN__` path. Remote/non-loopback dashboards use the Desktop-style dashboard auth gate: `/api/status` advertises `auth_required` and providers, `/auth/password-login` handles password providers, `/auth/login?provider=...` handles Nous/OIDC redirects, `/api/auth/me` returns the verified session, and `/api/auth/ws-ticket` mints a short-lived ticket for `/api/ws` / `/api/pty`. This dashboard session is **not** an `API_SERVER_KEY`. Android uses it for Manage, Vanilla Hermes voice, and the gateway chat transport. `/api/ws` is backed by `tui_gateway/server.py` (what hermes-desktop + the Ink TUI speak) and is the only upstream surface with **live** `reasoning.delta`/`thinking.delta` streaming; the api_server SSE paths remain the SSE fallback. Relay-only capabilities remain behind Relay pairing. **Do not proxy dashboard auth or dashboard admin APIs over the relay.**
|
||||
|
||||
**Tool call rendering paths:**
|
||||
|
||||
1. **Runs API** — Emits `tool.started`/`tool.completed` as real SSE events → `ToolProgressCard` in real-time.
|
||||
2. **Sessions API** — Native upstream emits structured SSE (`run.started`, `message.started`, `assistant.delta`, `tool.progress`, `tool.started/completed/failed`, `assistant.completed`, `run.completed`, `done`). `run.completed.messages` can reconcile authoritative per-turn transcript.
|
||||
3. **Annotation parser** — Fallback for servers emitting inline markdown annotations (``💻 terminal``).
|
||||
|
||||
## Key Instructions
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The default (no-plugin) connection path — gateway/API chat, Manage, and Vanilla Hermes voice via the dashboard surface — must work against **unmodified upstream hermes-agent**: no fork patches, no bespoke server config as a dependency. The app ships on Google Play to users whose servers we don't control. Features that need server-side changes go through upstream PRs (with graceful degradation until merged) or live behind the opt-in relay plugin.
|
||||
- **Always verify upstream before assuming an endpoint exists.** Check `gateway/platforms/api_server.py` in hermes-agent. If an endpoint isn't there, document whether bootstrap injects it or it requires the fork.
|
||||
- If we use a non-standard endpoint, ensure `probeCapabilities()` covers it and the auto-resolver degrades gracefully.
|
||||
- **Bootstrap maintenance:** Retire `plugin/hermes_relay_bootstrap/` per surface. Done: sessions CRUD/messages/fork and the legacy skills list are retired from the bootstrap (native upstream #33134/#33016, no old-build fallback kept). Remaining: config, memory, legacy skill detail/toggle, available-models, session search, and slash middleware still need explicit replacement decisions before full removal.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
```
|
||||
hermes-android/
|
||||
├── app/src/main/kotlin/com/hermesandroid/relay/
|
||||
│ ├── ui/ # Screens, components, theme
|
||||
│ ├── network/ # ConnectionManager, ChannelMultiplexer, handlers
|
||||
│ ├── auth/ # AuthManager (pairing + tokens)
|
||||
│ ├── viewmodel/ # ChatViewModel, ConnectionViewModel
|
||||
│ ├── data/ # ChatMessage, ToolCall models, FeatureFlags
|
||||
│ ├── audio/ # VoiceRecorder, VoicePlayer, VoiceSfxPlayer
|
||||
│ ├── voice/ # VoiceViewModel, VoiceBridgeIntentHandler
|
||||
│ ├── accessibility/ # HermesAccessibilityService, ScreenReader, ActionExecutor
|
||||
│ ├── bridge/ # BridgeSafetyManager, BridgeForegroundService, BridgeStatusOverlay
|
||||
│ └── notifications/ # HermesNotificationCompanion
|
||||
├── relay-core/ ← [EXPERIMENTAL] Quest/XR shared core lib (com.axiomlabs.hermesrelay.core) — pairing, transport, terminal, voice, wire
|
||||
├── relay-ui/ ← [EXPERIMENTAL] Quest/XR shared Compose UI lib — sphere, terminal WebView, QR scanner
|
||||
├── quest/ ← [EXPERIMENTAL] Meta Spatial SDK Quest/XR app (gradle includeBuild; in development, not shipped)
|
||||
├── ui-preview/ ← Desktop Compose Hot Reload harness for PC UI iteration (NOT shipped; shares MorphingSphereCore)
|
||||
├── desktop/ ← Node thin-client CLI (`@hermes-relay/cli`)
|
||||
│ ├── bin/hermes-relay.js # #!/usr/bin/env node shim → dist/cli.js
|
||||
│ ├── src/
|
||||
│ │ ├── cli.ts # argv parser + subcommand dispatcher (bare → shell)
|
||||
│ │ ├── commands/ # chat, shell, pair, status, tools, devices
|
||||
│ │ ├── banner.ts # contextual connect line (LAN / Tailscale / Plain / Secure)
|
||||
│ │ ├── renderer.ts # GatewayEvent → plain-line stdout formatter (chat only)
|
||||
│ │ ├── endpoint.ts # ADR 24 EndpointCandidate + role helpers
|
||||
│ │ ├── pairingQr.ts # v3 QR decode + priority-raced reachability probe
|
||||
│ │ ├── pairing.ts # readline 6-char prompt + payload validator
|
||||
│ │ ├── credentials.ts # token → pair-qr → code → stored → prompt precedence
|
||||
│ │ ├── certPin.ts # TOFU SPKI sha256 extract / pinKey / compare
|
||||
│ │ ├── tools/ # desktop.command router + fs/terminal/search handlers + consent
|
||||
│ │ ├── transport/ # RelayTransport (reconnect state machine + TLS probe TOFU)
|
||||
│ │ └── lib/ # gracefulExit, rpc, circularBuffer (vendored)
|
||||
│ └── scripts/ # install.sh + install.ps1 curl/iwr one-liners
|
||||
├── website/ ← Astro product/marketing site (static Coolify/Nixpacks deployment)
|
||||
├── plugin/ ← Hermes agent plugin
|
||||
│ ├── android_tool.py # 18 android_* tool handlers
|
||||
│ ├── pair.py # QR pairing implementation
|
||||
│ ├── relay/ # Canonical WSS relay (server.py, auth.py, channels/, media.py, voice.py)
|
||||
│ ├── tools/ # android_navigate.py, android_notifications.py
|
||||
│ └── dashboard/ # hermes-agent dashboard plugin — manifest, React UI, FastAPI proxy
|
||||
├── relay_server/ ← Thin compat shim → plugin.relay (legacy entrypoint)
|
||||
├── hermes_relay_bootstrap/ ← Legacy import shim for older startup hooks
|
||||
├── skills/devops/hermes-relay-pair/ ← /hermes-relay-pair slash command
|
||||
├── scripts/ ← dev.bat, bridge-smoke.sh, bump-version.sh
|
||||
└── docs/ ← spec, decisions, security, relay-server, mcp-tooling
|
||||
```
|
||||
|
||||
## Project Conventions
|
||||
|
||||
### File Structure
|
||||
|
||||
- **Root-level:** README.md, CLAUDE.md, AGENTS.md, DEVLOG.md, TODO.md, .gitignore
|
||||
- **docs/** — spec, decisions, security, and any other long-form documentation
|
||||
- **DEVLOG.md** — update at end of each work session with what was done + verification (the factual record of *what happened*). It churns; do NOT park forward work here.
|
||||
- **TODO.md** — the single home for follow-ups / deferred work / known gaps ("what's next"). Record them here — never buried in DEVLOG or scattered through code/doc comments where they get lost.
|
||||
- **CLAUDE.md hygiene:** Key Files entries must stay one line — implementation detail belongs in the file or `docs/`. Run `/revise-claude-md` after feature-heavy sessions to trim drift.
|
||||
|
||||
### Public-repo writing hygiene
|
||||
|
||||
This is a **public, distributed repo** — every committed file (CHANGELOG, DEVLOG, README, docs, release notes) is public-facing. Write accordingly:
|
||||
|
||||
- **No personal names** in prose — attribute impersonally ("a user reported", "observed"). Author identity lives in git history + the signing cert, not the changelog.
|
||||
- **No private infrastructure** — real server hostnames/IPs, internal deployment names, `~/SYSTEM.md` contents. (Generic example IPs like `192.168.1.100` in setup docs are fine.)
|
||||
- **No AI/assistant process self-narration** — no "I should have…", no course-correction confessionals. State the technical conclusion, not the path to it.
|
||||
- **No internal jargon / fork-branch plumbing** in user-facing notes — keep *what changed*, drop *where we staged it*.
|
||||
- **CHANGELOG** uses Keep-a-Changelog grouping (Added / Changed / Fixed). Detail may accumulate during iteration, but at **release-prep the version block is condensed to crisp public bullets** (1–2 lines each) — deep "how we debugged it" stays in commits/DEVLOG. See [RELEASE.md](RELEASE.md) §2 "Scrub for public distribution".
|
||||
- **DEVLOG.md** is a committed, factual engineering log — what changed, why, and verification — depersonalized and third-person, not a diary.
|
||||
|
||||
### Code Style — Android (Kotlin)
|
||||
|
||||
- **Jetpack Compose** — no XML layouts. Material 3 / Material You.
|
||||
- **kotlinx.serialization** — not Gson. Type-safe, faster.
|
||||
- **OkHttp** for WebSocket + SSE — `okhttp` for WSS relay, `okhttp-sse` for API streaming
|
||||
- **Single-activity** — Compose Navigation for all routing
|
||||
- **Namespace (Kotlin source tree):** `com.hermesandroid.relay` — stable, drives on-disk layout + class FQCNs
|
||||
- **applicationId:** `com.axiomlabs.hermesrelay` (googlePlay), `com.axiomlabs.hermesrelay.sideload` (sideload)
|
||||
- **Min SDK 26, Target SDK 35, Compile SDK 37** / **Kotlin 2.0+**, JVM toolchain 17
|
||||
|
||||
### Code Style — Desktop CLI (Node/TypeScript)
|
||||
|
||||
- **Node ≥21** — uses built-in global `WebSocket` (no `ws`/`undici` dep). Strict TS, ES modules, `NodeNext` resolution.
|
||||
- **Zero runtime deps** — `@types/node` + `tsx`/`rimraf`/`typescript` are devDeps only. Ship compiled `dist/`, not tsx.
|
||||
- **One binary, subcommands** — idiomatic for Node CLIs (codex, continue, vite pattern). Bare invocation is `chat`.
|
||||
- **Vendor-for-now** — transport/gateway/types are copied verbatim from `hermes-agent-tui-smoke/ui-tui/src/` with a header note. Extract to a shared package when the TUI and CLI stabilize.
|
||||
- **Dev loop:** `npx tsx src/cli.ts <args>` (no rebuild). `npm run build` + `npm link` before pushing to verify the bin shim. Never ship tsx in the published tarball — pre-build with `tsc` so Windows `npm install -g` can cmd-shim the JS directly.
|
||||
|
||||
### Code Style — Server (Python)
|
||||
|
||||
- **aiohttp** — async, matches existing Hermes relay patterns
|
||||
- **Type hints everywhere** — Python 3.11+ syntax
|
||||
- **asyncio** — no threading; **structured logging** — use `logging`, not print()
|
||||
|
||||
### Git
|
||||
|
||||
- **Conventional Commits:** `feat`, `fix`, `docs`, `refactor`, `test`, `chore`
|
||||
- **Branch/release policy:** follow the branch-contract table in `AGENTS.md` and
|
||||
the executable release and hotfix procedures in `RELEASE.md`. Do not maintain
|
||||
a Claude-specific parallel policy here.
|
||||
|
||||
### Testing
|
||||
|
||||
- **Android:** JUnit + Compose testing for UI, MockK for mocks
|
||||
- **Gateway/session/reconnect work:** follow the on-demand scenario,
|
||||
current-upstream conformance, Android instrumentation, and physical-proof
|
||||
routing in `docs/gateway-contract-testing.md`; do not infer device behavior
|
||||
from fixture or source checks.
|
||||
- **Python:** `python -m unittest plugin.tests.test_<name>` — avoid bare `pytest` (conftest imports `responses` which may not be installed in the venv)
|
||||
- **CI and release gates:** follow the repository-wide requirements in
|
||||
`AGENTS.md` and `RELEASE.md`; Claude-specific guidance does not redefine them.
|
||||
|
||||
## Key Files
|
||||
|
||||
|
||||
| File | Why |
|
||||
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `docs/spec.md` | Full specification — protocol, UI layouts, phases, dependencies |
|
||||
| `docs/decisions.md` | Architecture decisions — framework choice, channel design, auth model |
|
||||
| `docs/gateway-contract-testing.md` | On-demand reusable Gateway scenarios, upstream conformance, Android instrumentation, and ADB certification |
|
||||
| `AGENTS.md` | Universal agent entry point — points here + the non-negotiables (standard-path, commits, writing hygiene) |
|
||||
| `docs/mcp-tooling.md` | MCP server setup — android-tools-mcp + mobile-mcp; `android_*` tool usage patterns |
|
||||
| **App — Core** | |
|
||||
| `ui/RelayApp.kt` | Main scaffold (Scaffold + Compose nav); Chat is home — no mode strip, Manage/Bridge reached via Settings; `bottomBar` is a status pill, not a NavigationBar |
|
||||
| `viewmodel/ChatViewModel.kt` | Chat orchestration — send, stream, cancel, slash commands |
|
||||
| `viewmodel/ConnectionViewModel.kt` | Dual connection model (API + relay); `resolveStreamingEndpoint()`; derived `relayUiState` flow + `markPaired` hook stamp the active Connection |
|
||||
| `viewmodel/RelayUiState.kt` | Shared sealed state for the relay row — 5 cases + `asBadgeState()` / `statusText()` extensions; 5s grace window before Stale |
|
||||
| `network/HermesApiClient.kt` | Direct HTTP/SSE — `sendRunStream()`, `sendChatStream()`, `probeCapabilities()` |
|
||||
| `network/GatewayChatClient.kt` | Gateway chat transport — JSON-RPC over dashboard `/api/ws` (tui_gateway); live `reasoning.delta`; fresh ws-ticket per connect; per-turn SSE fallback via `onPreflightFailure`; `prewarm()` (connect+resume off the send path); `setKeepAliveInBackground()` suppresses the 120s idle-close |
|
||||
| `network/GatewayKeepAliveService.kt` | Opt-in `specialUse` foreground service (BOTH flavors; declared in main manifest; Play needs a Console FGS declaration) holding the process up so the gateway socket survives background/Doze; driven by ConnectionViewModel from the `KEY_GATEWAY_KEEP_ALIVE` toggle; stops on task-removal |
|
||||
| `data/GatewayKeepAlivePrefs.kt` | Shared `KEY_GATEWAY_KEEP_ALIVE` pref key + `Context.setGatewayKeepAlive()` — used by ConnectionViewModel (StateFlow/setter) and the FGS Stop action |
|
||||
| `network/GatewayEventMapper.kt` | Pure-JVM gateway event→callback mapping for one turn; unknown event types silently ignored; tui_gateway usage-key translation |
|
||||
| `network/GatewayModels.kt` | `GatewayAvailability`, `ActiveTurnHandle`, `GatewayTurnCallbacks` (all members REQUIRED — forces dispatchOn main-thread wrap), `GatewayAsk`, `GatewaySubagentEvent`, `resolveStreamingEndpointPreference()` |
|
||||
| `ui/components/ChatInputBar.kt` | Redesigned input bar — pill field, one trailing slot morphing Send/Voice/Stop/Steer/Queue, no slash button (long-press + opens palette) |
|
||||
| `ui/components/SubagentLane.kt` | Per-taskIndex subagent progress lane — guide rail, compact tool rows, auto-collapse |
|
||||
| `notifications/TurnCompleteNotifier.kt` | Turn-complete local notification when backgrounded — channel `chat_turn_complete`, cancel on resume, settings-gated |
|
||||
| `network/ConnectionManager.kt` | WSS to relay with auto-reconnect; rebuilds OkHttpClient with fresh CertPinner on connect |
|
||||
| `network/ChannelMultiplexer.kt` | Envelope routing by channel; `sendNotification()` for notification outbound |
|
||||
| `network/handlers/ChatHandler.kt` | Chat message state, streaming events, tool annotation parser |
|
||||
| `network/models/SessionModels.kt` | Session, message, SSE event data models |
|
||||
| `data/FeatureFlags.kt` | Feature gating — DEV_MODE + DataStore overrides; `BuildFlavor` (googlePlay/sideload Tier flags) |
|
||||
| **App — Auth** | |
|
||||
| `auth/AuthManager.kt` | Wires SessionTokenStore + CertPinStore; parses auth.ok; `applyServerIssuedCodeAndReset()` |
|
||||
| `auth/SessionTokenStore.kt` | Keystore (StrongBox) + EncryptedSharedPrefs fallback; lossless migration on upgrade |
|
||||
| `auth/CertPinStore.kt` | TOFU cert pinning — SHA-256 SPKI per host:port in DataStore |
|
||||
| `auth/PairedSession.kt` | PairedSession state + PairedDeviceInfo wire model |
|
||||
| `data/Endpoint.kt` | `EndpointCandidate` / `ApiEndpoint` / `RelayEndpoint` — multi-endpoint pairing (ADR 24); `displayLabel()` for LAN/Tailscale/Public/Custom chips |
|
||||
| `network/RelayHttpClient.kt` | OkHttp for /media, /sessions (list/revoke/extend), /health |
|
||||
| **App — Bridge** | |
|
||||
| `network/handlers/BridgeCommandHandler.kt` | Routes `bridge.command` → ActionExecutor; full path inventory + safety-rail integration |
|
||||
| `viewmodel/BridgeViewModel.kt` | BridgeScreen VM — masterToggle, bridgeStatus, permissionStatus, activityLog |
|
||||
| `bridge/BridgeSafetyManager.kt` | Connection-scoped capabilities + timed screen expiry + blocklist + destructive confirmation; unknown, denied, and expired commands fail closed |
|
||||
| `bridge/BridgeCapabilities.kt` / `data/BridgeCapabilityPolicyRepository.kt` | Closed method/path registry + no-backup-bound per-Connection Always/Never/Timed policy; global safety vocabulary and timer duration remain in `BridgeSafetyPreferences.kt` |
|
||||
| `ui/screens/BridgeScreen.kt` | Bridge cockpit — master → Agent access posture/setup → single Unattended Access control → capability-scoped Android readiness (expandable full matrix) → Advanced safety/full editor → activity log |
|
||||
| `ui/components/BridgeAccessCards.kt` | Native access cockpit + first-use preset and screen-lease sheets (renewable idle limits or warned Until-off dedicated-device mode); preserves full permission/safety drilldowns while keeping selected policy/readiness above the fold |
|
||||
| `ui/components/UnattendedAccessRow.kt` | Unattended toggle card (sideload); `enabled=masterEnabled`; inline `KeyguardDetectedAlert` |
|
||||
| `ui/components/UnattendedGlobalBanner.kt` | 28dp amber strip at scaffold top when master+unattended on (sideload); tap → Bridge tab |
|
||||
| `bridge/BridgeStatusOverlay.kt` | WindowManager overlay; `ConfirmationOverlayHost`; requires `SavedStateRegistryOwner` init order (CREATED→restore→RESUMED) |
|
||||
| `accessibility/HermesAccessibilityService.kt` | AccessibilityService subclass; `@Volatile instance` singleton for BridgeCommandHandler |
|
||||
| `accessibility/ScreenReader.kt` | UI tree → ScreenContent; `findNodeBoundsByText()`, `findFocusedInput()` |
|
||||
| `accessibility/ActionExecutor.kt` | Gesture/text dispatch via GestureDescription + ACTION_SET_TEXT; pressKey maps vocab only |
|
||||
| **App — Voice** | |
|
||||
| `voice/VoiceViewModel.kt` | Voice turn state machine; TTS queue; `ignoreAssistantId`; `errorEvents: SharedFlow` |
|
||||
| `audio/VoiceRecorder.kt` | MediaRecorder wrapper; perceptual amplitude curve; `.m4a` at 16kHz/64kbps |
|
||||
| `audio/VoicePlayer.kt` | Media3 ExoPlayer (gapless TTS queue) + Visualizer; amplitude StateFlow; `awaitCompletion()` via coroutine; `audioSessionId` is a thread-safe `@Volatile` cache |
|
||||
| `network/RelayVoiceClient.kt` | OkHttp for `/voice/transcribe`, `/synthesize`, `/config` |
|
||||
| `voice/VoiceBridgeIntentHandler.kt` | Interface routing voice utterances to bridge; impls per flavor via factory |
|
||||
| `voice/VoiceIntentClassifier.kt` | Regex phone-control classifier (sideload only); false-negatives preferred over false-positives |
|
||||
| `ui/components/VoiceModeOverlay.kt` | Full-screen voice UI — MorphingSphere + VoiceWaveform + mic button |
|
||||
| `ui/components/MorphingSphere.kt` | Compose renderer for the agent sphere — delegates math to `MorphingSphereCore` |
|
||||
| `ui/components/MorphingSphereCore.kt` | Platform-agnostic sphere algorithm (`kotlin.math` only) — single source of truth; mirrored byte-for-byte in `preview/web/sphere.js` |
|
||||
| `preview/web/` | Zero-dep browser harness — live `index.html` preview + `parity-check.mjs`; paired with `MorphingSphereCoreParityTest` (JVM) for struct/full checksum diffing |
|
||||
| `user-docs/.vitepress/theme/components/SphereMark.vue` | Docs-site sphere embed — imports `preview/web/sphere.js` directly; autonomous fbm drift + pointer-proximity gaze/state blend; `<ClientOnly>` + `IntersectionObserver` + `prefers-reduced-motion` aware |
|
||||
| **App — Media + Notifications** | |
|
||||
| `util/MediaCacheWriter.kt` | `cacheDir/hermes-media/` LRU writer; returns FileProvider URIs |
|
||||
| `util/MediaSaver.kt` | Save/share/open for chat media — MediaStore scoped-storage save (Pictures/Download `Hermes-Relay`, no perms on API 29+; pre-Q → share sheet); FileProvider share staging; remote-byte fetch; magic-byte image-MIME sniff for correct extensions |
|
||||
| `ui/components/ChatImageViewer.kt` | Full-screen image viewer — pinch-zoom/pan (`detectTransformGestures`), double-tap 1×/2.5×, Share/Save/Close; `ChatImageViewerSource` decouples Coil-model/bitmap display from a suspend `bytesProvider` so Save keeps original bytes |
|
||||
| `ui/components/InboundAttachmentCard.kt` | Discord-style attachment card for images/video/audio/pdf/text/generic; image tap → ChatImageViewer, file card long-press → Open/Share/Save menu |
|
||||
| `ui/components/ChatImageContent.kt` | Parses `` out of assistant content; remote http(s) → Coil (tap → ChatImageViewer), server-local/failed → inline "can't render" notice with the path |
|
||||
| `data/HermesCard.kt` | `CARD:{json}` envelope (ADR 26) — type/accent/fields/actions; kotlinx.serialization |
|
||||
| `ui/components/HermesCardBubble.kt` | Rich-card renderer — accent stripe + FlowRow actions + dispatch stamp collapse |
|
||||
| `viewmodel/CardDispatchSyncBuilder.kt` | Twin of VoiceIntentSyncBuilder — synthesizes card dispatches as `hermes_card_action` OpenAI pairs for session memory |
|
||||
| `notifications/HermesNotificationCompanion.kt` | NotificationListenerService; cold-start buffer (50); forwards via ChannelMultiplexer |
|
||||
| `util/RelayErrorClassifier.kt` | `classifyError(Throwable, context) → HumanError`; used by Voice/Chat/Connection |
|
||||
| `util/TurnLatencyTracer.kt` | One `TurnLatency` INFO line per chat turn — `warm/cold` + `connect/session/submit/ttfe/ttft/done@…ms`; gateway + 3 SSE paths use it for desktop-comparable latency diagnosis; durations only |
|
||||
| **Relay — Server** | |
|
||||
| `plugin/relay/server.py` | Canonical relay — WSS + HTTP routes; bridge, media, voice, session, pairing handlers. `handle_pairing_mint` mirrors `pair.py:762` — top-level = API server, `relay.{url,code}` nested |
|
||||
| `plugin/relay/auth.py` | PairingManager, SessionManager, RateLimiter; `math.inf` for never-expire |
|
||||
| `plugin/relay/channels/bridge.py` | Bridge handler — `handle_command()` mints request_id, awaits response, 30s timeout |
|
||||
| `plugin/relay/channels/notifications.py` | Bounded deque (100) of notification metadata; in-memory only |
|
||||
| `plugin/relay/media.py` | MediaRegistry — LRU token store; `strict_sandbox` off by default for `/media/by-path` |
|
||||
| `plugin/relay/voice.py` | Voice endpoints — transcribe, synthesize, voice_config; lazy tool imports |
|
||||
| `plugin/relay/qr_sign.py` | HMAC-SHA256 QR signing; secret at `~/.hermes/hermes-relay-qr-secret`; canonical form preserves `endpoints` array order + role strings verbatim (ADR 24) |
|
||||
| `plugin/relay/tailscale.py` | First-class Tailscale helper (ADR 25) — `status()` / `enable(port)` / `disable(port)` / `canonical_upstream_present()`; safe-absent via shell-out to `tailscale` CLI |
|
||||
| `plugin/relay/_env_bootstrap.py` | Loads `~/.hermes/.env` before relay imports; called from both entry points |
|
||||
| **Plugin — Tools + Installer** | |
|
||||
| `plugin/tools/android_tool.py` | 18 `android_*` tool handlers (14 baseline + send_sms, call, search_contacts, return_to_hermes); `android_screenshot` first consumer of `register_media()` |
|
||||
| `plugin/tools/android_navigate.py` | Vision-driven navigation loop; up to 20 iterations; `llm_gap` error until vision client wired |
|
||||
| `plugin/pair.py` | QR payload builder + CLI; `build_payload(sign=True)`; `--register-code` fallback |
|
||||
| `plugin/doctor.py` | `hermes relay doctor`; checks standard upstream API/dashboard reachability, Relay loopback state, plugin layout, and compat hook state |
|
||||
| `plugin/compat.py` | `hermes relay compat status/install/remove`; owns the optional `hermes_relay_bootstrap.pth` lifecycle |
|
||||
| `plugin/hermes_relay_bootstrap/` | Plugin-owned runtime compatibility patch — compat-only surfaces (session search, memory, skill detail/toggle, config, available-models, slash middleware); sessions + skills-list injection retired (#33134/#33016) |
|
||||
| `install.sh` | Canonical installer — 6 steps; idempotent; drops `hermes-relay-update` shim |
|
||||
| `uninstall.sh` | Canonical uninstaller; reverses install.sh; never touches `.env` or `state.db` |
|
||||
| `hermes_relay_bootstrap/` | Legacy import shim for old `.pth` files and editable installs |
|
||||
| **Plugin — Dashboard** | |
|
||||
| `plugin/dashboard/manifest.json` | Declares tab, entry bundle, and FastAPI module for hermes-agent discovery |
|
||||
| `plugin/dashboard/plugin_api.py` | FastAPI router proxying 5 routes to relay over loopback; `/pairing` body = API-server overrides (host/port/tls/api_key), relay URL auto-derived |
|
||||
| `plugin/dashboard/src/index.jsx` | React root registering `hermes-relay` plugin with 4-tab shell |
|
||||
| `plugin/dashboard/dist/index.js` | Committed IIFE bundle loaded verbatim by dashboard |
|
||||
| **Desktop CLI** | |
|
||||
| `desktop/package.json` | `@hermes-relay/cli` package manifest — Node ≥21, one `hermes-relay` bin, pre-built dist |
|
||||
| `desktop/bin/hermes-relay.js` | Tiny shim: `import('../dist/cli.js').then(m => m.main())` + error surfacing |
|
||||
| `desktop/src/chatAttach.ts` | captureClipboardImage / captureScreenshot / readImageFile; ships base64 to server via `image.attach.bytes` RPC before next prompt.submit |
|
||||
| `desktop/src/cli.ts` | argv parser + subcommand dispatcher — bare → `shell` (PTY), positional-only → `chat`; command-scoped `--help` falls through to each command |
|
||||
| `desktop/src/lib/theme.ts` | Shared ANSI palette + `colorEnabled()` + `Theme` (semantic helpers, `statusDot`) — single visual language; `--no-color`/`NO_COLOR`/TTY aware |
|
||||
| `desktop/src/lib/table.ts` | Zero-dep column-aligned table renderer (ANSI-width aware, last column flexes to terminal width) — used by devices/sessions/audit |
|
||||
| `desktop/src/lib/spinner.ts` | Stderr braille spinner for slow ops (pair probe, gateway connect); no-op when piped/quiet/json |
|
||||
| `desktop/src/lib/usage.ts` | `UsageSpec` + `renderUsage`/`printUsage`/`unknownSubcommand` — per-subcommand `--help` + self-documenting sub-verb fallback |
|
||||
| `desktop/src/lib/hints.ts` | `suggestedFix(err, ctx)` → next-step command (re-pair on auth fail, etc.); `formatError` renders error + hint |
|
||||
| `desktop/src/lib/logo.ts` | Slim box-drawing "Hermes Relay" wordmark; shown atop `--help`, first-run welcome, REPL header, and `hermes-relay logo`; theme/no-color aware |
|
||||
| `desktop/src/lib/auditLog.ts` | Local desktop-tool audit JSONL (`~/.hermes/desktop-audit.jsonl`); router appends per dispatch; backs `audit` command (relay's ring is loopback-only) |
|
||||
| `desktop/src/lib/daemonStatus.ts` | Daemon heartbeat file (`~/.hermes/daemon-status.json`) + `isPidAlive` liveness; backs `daemon --status` |
|
||||
| `desktop/src/commands/audit.ts` | `hermes-relay audit` — tails the local audit log into a table (WHEN/TOOL/STATUS/DETAIL); `--limit`, `--json` |
|
||||
| `desktop/src/commands/relay.ts` | `hermes-relay relay info/security/context/queue` — relay-server management surface; info/security/queue loopback-only, context works remote with bearer; `queue` lists/cancels the agent→phone outbound buffer (`--clear` / `--cancel <id>`) |
|
||||
| `desktop/src/commands/chat.ts` | REPL + one-shot + piped-stdin; `runOneTurn` returns `{promise, cancel}` for safe SIGINT; auto-wires `DesktopToolRouter` when consented |
|
||||
| `desktop/src/commands/shell.ts` | Pipes the `terminal` relay channel to raw-mode stdin/stdout; post-attach `exec hermes` 350ms after tmux settles; `Ctrl+A .` detach / `Ctrl+A k` kill / `Ctrl+A Ctrl+A` literal |
|
||||
| `desktop/src/commands/pair.ts` | Either 6-char code + `--remote`, or full v3 QR via `--pair-qr` — probes + picks endpoint, records role; `--grant-tools` (TTY prompt) / `--auto-grant-tools` (silent) stamp `toolsConsented` so `daemon` works without a `shell` round-trip |
|
||||
| `desktop/src/commands/tools.ts` | `tools.list` RPC → enabled/available toolsets; `--verbose` lists individual tools |
|
||||
| `desktop/src/commands/status.ts` | Local read of `~/.hermes/remote-sessions.json`; renders `grants:` + `expires:` + `route:`; `--json` redacts tokens, `--reveal-tokens` opts in |
|
||||
| `desktop/src/commands/devices.ts` | Server-side session management — `GET/DELETE/PATCH /sessions` via `fetch` over http(s)://host:port; `list` / `revoke <prefix>` / `extend <prefix> --ttl <s>` |
|
||||
| `desktop/src/banner.ts` | `buildConnectBanner({url, meta, endpointRole})` → "Connected via LAN (plain) — server 0.6.0"; `humanExpiry()` for TTL formatting |
|
||||
| `desktop/src/endpoint.ts` | `EndpointCandidate` / `EndpointRole` types + `displayLabel()` — mirrors Android `data/Endpoint.kt` |
|
||||
| `desktop/src/pairingQr.ts` | `decodePairingPayload` (JSON or base64), `payloadToCandidates` (v3 verbatim / v1–v2 synthesized), `probeCandidatesByPriority` (`Promise.any` within tier, `AbortSignal.any`, 4s timeout, 60s cache) |
|
||||
| `desktop/src/certPin.ts` | `extractSpkiSha256(der)` via `crypto.X509Certificate` + `publicKey.export({type:'spki'})`; `pinKey(url)`, `comparePins()`, `isSecureUrl()` |
|
||||
| `desktop/src/tools/router.ts` | `DesktopToolRouter.attach(relay)` — `onChannel('desktop')` dispatch under 30s `AbortController`; heartbeat enriched with host/platform/version/uptime_ms + sticky `last_error` for `desktop_health` |
|
||||
| `desktop/src/tools/handlerSet.ts` | Single source of truth for the desktop tool map — `DESKTOP_HANDLERS` + `DESKTOP_ADVERTISED_TOOLS`; consumed by `chat.ts` / `shell.ts` / `daemon.ts` so adding a tool is a one-file change |
|
||||
| `desktop/src/tools/consent.ts` | `ensureToolsConsent(url)` — stored per-URL in `toolsConsented`; TTY prompt; non-TTY fails closed |
|
||||
| `desktop/src/tools/handlers/fs.ts` | `readFileHandler` / `writeFileHandler` / `patchHandler` — strict unified-diff applier, no fuzz |
|
||||
| `desktop/src/tools/handlers/terminal.ts` | `bash -lc` / `cmd /c`, SIGKILL on timeout or abort, returns `{stdout, stderr, exit_code, duration_ms}` |
|
||||
| `desktop/src/tools/handlers/powershell.ts` | Spawns `pwsh`/`powershell` directly with `-Command -`, script piped via stdin — no cmd.exe quote-mangling; auto-picks pwsh > powershell |
|
||||
| `desktop/src/tools/handlers/process.ts` | `spawn_detached` (unref'd, returns pid+log_path), `list_processes` (tasklist /FO CSV — no /V to dodge window-title latency), `kill_process`, `find_pid_by_port` (netstat/lsof/ss) |
|
||||
| `desktop/src/tools/handlers/jobs.ts` | Job API — `~/.hermes/desktop-jobs/<id>/{stdout.log, stderr.log, meta.json}` is source of truth across daemon restarts; `taskkill /T` on Windows so build trees die fully |
|
||||
| `desktop/src/tools/handlers/transfer.ts` | `copy_directory` via `fs.cp`, `zip`/`unzip` via tar > zip > PowerShell probe, `checksum` streamed (sha256/sha1/md5) |
|
||||
| `desktop/src/tools/handlers/search.ts` | ripgrep with pure-Node fallback, skips `.git`/`node_modules`/`dist`/`.next`/`.cache` |
|
||||
| `desktop/src/renderer.ts` | Streams `message.delta` → stdout, tool events → decorated lines; NO_COLOR / --json / --quiet aware |
|
||||
| `desktop/src/pairing.ts` | readline-based 6-char prompt (`A-Z0-9`); headless mirror of TUI's Ink prompt; `validatePairingPayloadString` discriminated-union wrapper |
|
||||
| `desktop/src/credentials.ts` | Precedence: `--token` → `--pair-qr` (probe+pair) → `--code` → stored → prompt; returns `Credentials{sessionToken?, pairingCode?, resolvedEndpoint?}` |
|
||||
| `desktop/src/transport/RelayTransport.ts` | Fork of ui-tui's transport + reconnect state machine (`idle/connecting/connected/reconnecting`, exp backoff 1→30s, 5min on 429, gate re-check post-sleep) + pre-WS TLS probe for TOFU |
|
||||
| `desktop/src/remoteSessions.ts` | Same file path as TUI (`~/.hermes/remote-sessions.json`, 0600); schema widened with `grants`, `ttlExpiresAt`, `endpointRole`, `toolsConsented`; `saveSession` back-compat overload |
|
||||
| `desktop/src/commands/daemon.ts` | Headless WSS + tool router for always-on access; JSON-line logs; fails closed on missing consent unless `--allow-tools` with explicit `--token` |
|
||||
| `desktop/src/commands/doctor.ts` | Local-only diagnostic report — version / binary path / PATH / sessions / daemon detection; `--json` for support-paste; omits tokens entirely |
|
||||
| `desktop/src/relayUrlPrompt.ts` | First-run URL fallback — `resolveFirstRunUrl()` auto-picks single stored session, numbered picker for multiple, welcome banner for zero; throws on non-interactive + ambiguous |
|
||||
| `desktop/src/version.ts` | Build-time-generated constant (`npm run gen:version` before every build) — Bun compiled binaries can't read package.json via `__dirname` so version is embedded at build |
|
||||
| `desktop/scripts/install.sh` / `install.ps1` | curl/iwr one-liner installers — download prebuilt Bun binary (no Node required), SHA256-verified, API-resolver for `latest` that includes prereleases, version-aware pre/post-install readback |
|
||||
| `desktop/scripts/uninstall.sh` / `uninstall.ps1` | 3-tier removal — default (binary + PATH), `--purge` (also wipes `~/.hermes/remote-sessions.json`), `--service` (stub for future service installers); Windows iex-safe env-var fallback |
|
||||
| `desktop/README.md` | User-facing install + usage reference |
|
||||
| **Desktop CLI — dev iteration** | |
|
||||
| `npm run smoke` (in `desktop/`) | Builds Windows binary + runs `--version` / `--help` / `doctor`, fails loud on zero-output. Local pre-flight before cutting any tag. |
|
||||
| `npm run gen:version` | Regenerates `src/version.ts` from `package.json`. Runs automatically before every `build` / `build:bin:*`. |
|
||||
| `release-cli.yml → Smoke-test Linux binary` step | CI-side equivalent: runs compiled Linux binary through the same 3-command check before uploading assets. Catches silent-exit-0 + segfault classes. |
|
||||
| **Server — Desktop tool routing (Phase B)** | |
|
||||
| `plugin/relay/channels/desktop.py` | Mirrors `bridge.py` — `desktop.command`/`desktop.response`/`desktop.status`, UUID-correlated futures, 30s timeout, single-client MVP, per-session advertised-tools set |
|
||||
| `plugin/tools/desktop_tool.py` | 24 `desktop_*` tools (fs/shell/powershell/process/jobs/transfer/health) — registers with `tools.registry` under `desktop` toolset; per-tool `check_fn` pings `/desktop/_ping?tool=<name>`; `desktop_health` is `_RELAY_ONLY` and pings `/desktop/health` so it works even when the client is wedged |
|
||||
| **Gradle modules — experimental Quest/XR (in development)** | |
|
||||
| `relay-core/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.core`) — shared pairing/transport/terminal/voice/wire for the Quest port; not yet wired into the shipped `:app` |
|
||||
| `relay-ui/` | [EXPERIMENTAL] Android library (`com.axiomlabs.hermesrelay.ui`) — shared Compose UI (sphere, terminal WebView, QR scanner) for the Quest port; carries its own sphere copy |
|
||||
| `quest/` | [EXPERIMENTAL] Meta Spatial SDK Quest/XR app — gradle `includeBuild("quest")`; needs further development, not shipped |
|
||||
| **Tooling — dev iteration (not shipped)** | |
|
||||
| `ui-preview/` | Desktop Compose Hot Reload harness — JVM Compose for Desktop; source-shares `MorphingSphereCore` from `:relay-ui`; `Main.kt` gallery; see `ui-preview/README.md` |
|
||||
| `app/src/test/.../screenshots/StoreScreenshotTest.kt` | Roborazzi host-side store/docs screenshot renderer — deterministic, no device, exact 1080×2160; reuses real components+chrome with mock data; `capture(name, themeId){…}` renders any view; see `docs/screenshot-automation.md` §Deterministic rendering (JDK-21 + no-plugin gotchas) |
|
||||
|
||||
|
||||
## What NOT to Do
|
||||
|
||||
- **Don't use XML layouts** — Compose only
|
||||
- **Don't use Gson** — kotlinx.serialization
|
||||
- **Don't use Ktor for networking** — OkHttp for WebSocket
|
||||
- **Don't use plaintext WebSocket** — `wss://` only, even in development
|
||||
- **Don't put documentation in root** — long-form docs go in `docs/`
|
||||
- **Don't forget DEVLOG.md** — update it (record *what happened*)
|
||||
- **Don't bury follow-ups** — deferred work / known gaps go in `TODO.md`, never in DEVLOG or one-off code/doc comments
|
||||
- **Don't touch production / remote hosts** — automation and orchestrated agents must NEVER SSH into, deploy to, pull/restart/reconfigure, or push code to a live/remote Hermes host. Building, on-device testing, and server deployment are owner-driven (see Server Deployment). Stop at committing on your branch; surface "this needs a deploy/on-device check" rather than doing it.
|
||||
|
||||
## MCP Tooling
|
||||
|
||||
Two MCP servers are configured for AI-assisted development. See `docs/mcp-tooling.md` for full reference.
|
||||
|
||||
|
||||
| Server | Layer | Requires |
|
||||
| ------------------- | --------------------------------------------------------------- | ---------------------------------------- |
|
||||
| `android-tools-mcp` | IDE/Build — Compose previews, Gradle, code search, Android docs | Android Studio running with project open |
|
||||
| `mobile-mcp` | Device/Runtime — tap, swipe, screenshot, app management | ADB + connected device/emulator |
|
||||
|
||||
|
||||
## Dev Workflow
|
||||
|
||||
```bash
|
||||
scripts/dev.bat build # Build debug APK (DEV_MODE=true)
|
||||
scripts/dev.bat release # Build signed release APK (DEV_MODE=false)
|
||||
scripts/dev.bat bundle # Build release AAB for Google Play upload
|
||||
scripts/dev.bat run # Build + install + launch + logcat
|
||||
scripts/dev.bat test # Run unit tests
|
||||
scripts/dev.bat version # Show current version from libs.versions.toml
|
||||
scripts/dev.bat relay # Start relay server (dev mode, no SSL)
|
||||
```
|
||||
|
||||
### Bridge smoke test (run on hermes-host, not local PC)
|
||||
|
||||
```bash
|
||||
scripts/bridge-smoke.sh # full suite, destructive ON
|
||||
scripts/bridge-smoke.sh --no-destructive # read-only paths only
|
||||
scripts/bridge-smoke.sh --filter open_app # re-run a single test
|
||||
scripts/bridge-smoke.sh --pair ABCDEF # register pairing code first
|
||||
```
|
||||
|
||||
Curls every bridge HTTP route via `localhost:8767`. Catches the silent-drop regression class (Python relay registers a route but Kotlin dispatcher's `when (path)` has no matching branch). Run after every relay restart.
|
||||
|
||||
### Typical Dev Loop
|
||||
|
||||
1. **Edit locally** — Windows checkout. Both plugin (`plugin/`) and app (`app/`) live here.
|
||||
2. **Python syntax check** — `python -m py_compile plugin/<file>.py`. Full tests run on the server.
|
||||
3. **Kotlin changes** — do NOT run `gradle build`. Bailey builds via Android Studio's ▶ button. Never `adb install` from Claude.
|
||||
4. **Before pushing Kotlin changes** — run `./gradlew lint` locally. It's the exact task CI runs and catches errors Android Studio's live inspections miss — e.g. `UnsafeOptInUsageError` with `kotlin.OptIn` vs `androidx.annotation.OptIn`, `FlowOperatorInvokedInComposition` (mapped flows inside Composables), Media3 `@UnstableApi` propagation. Android CI runs lint alongside build/test for faster feedback, but a local lint run still surfaces issues before the workflow spends runner time compiling and packaging.
|
||||
5. **Commit + push** — follow `AGENTS.md` and `RELEASE.md`; normal work PRs to `dev`.
|
||||
6. **Pull + restart on server** — see Server Deployment below.
|
||||
7. **Test on phone** — Bailey builds from Studio, installs to Samsung device, pairs via `/hermes-relay-pair`.
|
||||
|
||||
### Server Deployment
|
||||
|
||||
Server is a Linux box running hermes-agent with hermes-relay editable-installed (`pip install -e`). Sensitive details (IP, user, secrets) in `~/SYSTEM.md` on the server — not in this repo.
|
||||
|
||||
|
||||
| What | Where |
|
||||
| ------------------ | ------------------------------------------------------------------ |
|
||||
| hermes-agent repo | `~/.hermes/hermes-agent/` |
|
||||
| hermes-relay clone | `~/.hermes/hermes-relay/` |
|
||||
| Plugin symlink | `~/.hermes/plugins/hermes-relay` → `~/.hermes/hermes-relay/plugin` |
|
||||
| Config | `~/.hermes/config.yaml` + `~/.hermes/.env` |
|
||||
| Relay log | `journalctl --user -u hermes-relay -f` |
|
||||
|
||||
|
||||
**Update:** `hermes-relay-update` (idempotent, re-fetches install.sh). Or manually: `git pull --ff-only && systemctl --user restart hermes-relay`.
|
||||
|
||||
**Compat hook:** `hermes relay compat status/install/remove` manages only the
|
||||
|
||||
optional `hermes_relay_bootstrap.pth` startup hook. New installs load the
|
||||
|
||||
plugin-owned bootstrap from `plugin/hermes_relay_bootstrap/`; the repo-root
|
||||
|
||||
package is only a legacy import shim. Vanilla Hermes chat, Manage, and dashboard voice
|
||||
|
||||
must not depend on this hook.
|
||||
|
||||
**Key conventions:**
|
||||
|
||||
- Phone pairing **survives** relay restart — `SessionManager` persists sessions to `~/.hermes/hermes-relay-sessions.json` (`server.py:88-90`, `persistence_path` from `RelayConfig.from_env`); a trusted-device refresh token recovers a lost/revoked/reset session without a new QR scan. (Only the in-memory *live-connection presence* clears on restart; the phone reconnects automatically.)
|
||||
- Use `python -m unittest` not `pytest` — conftest imports `responses` which may not be installed
|
||||
- `_env_bootstrap.py` loads `~/.hermes/.env` on every relay start — no stale API keys
|
||||
|
||||
### Where Python vs. Kotlin changes land
|
||||
|
||||
|
||||
| Change type | Who restarts? | Command |
|
||||
| ------------------------------------ | ------------------------ | -------------------------------------------------- |
|
||||
| Plugin tool (`android_tool.py` etc.) | `hermes-gateway.service` | `systemctl --user restart hermes-gateway` |
|
||||
| Relay code (`plugin/relay/*.py`) | `hermes-relay.service` | `systemctl --user restart hermes-relay` |
|
||||
| Pair CLI / skill files | — | No restart — fresh process / scanned on invocation |
|
||||
| Android app | Bailey (Studio) | Studio run button |
|
||||
|
||||
|
||||
### Release Process
|
||||
|
||||
See [AGENTS.md](AGENTS.md) for the canonical branch contract and
|
||||
[RELEASE.md](RELEASE.md) for version sources, release trains, surface tags,
|
||||
hotfixes, secrets, publishing, and verification. Claude-specific automation
|
||||
must not infer release authority from feature completion.
|
||||
|
||||
## Integration Points
|
||||
|
||||
|
||||
| Surface | Endpoint | Notes |
|
||||
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Chat (gateway) | Dashboard `POST /api/auth/ws-ticket` -> WS `/api/ws` | Vanilla Hermes dashboard/tui_gateway path; live thinking/reasoning; requires dashboard auth |
|
||||
| Chat streaming | `POST /v1/runs` → `GET /v1/runs/{id}/events` | Structured tool events; async run-control path |
|
||||
| Chat (sessions) | `POST /api/sessions/{id}/chat/stream` | Native upstream session-persisted SSE; preferred when capability probe finds it |
|
||||
| Chat (compat) | `POST /v1/chat/completions` (stream=true) | Inline tool annotations only |
|
||||
| Session CRUD | `GET/POST/PATCH/DELETE /api/sessions` | Native upstream (#33134); bootstrap fallback retired |
|
||||
| Manage | Dashboard `/api/status`, `/api/auth/me`, `/api/config`, `/api/profiles/*`, `/api/env`, `/api/model/*`, `/api/mcp/*` | Vanilla Hermes dashboard surface; do not proxy through Relay |
|
||||
| Vanilla Hermes voice | Dashboard `POST /api/audio/transcribe`, `POST /api/audio/speak` | Vanilla Hermes no-plugin voice; uses dashboard session from Manage |
|
||||
| Pairing (QR) | `POST /pairing/register` (loopback only) | Via `/hermes-relay-pair` or `hermes-pair` shim; accepts optional `endpoints` for multi-endpoint QRs |
|
||||
| Pairing (multi-endpoint) | QR `endpoints` array (ADR 24) | `hermes: 3` schema; ordered `lan`/`tailscale`/`public`/... candidates; phone re-probes on network change |
|
||||
| Pairing auth | WSS `auth.ok` payload | Includes `expires_at`, `grants`, `transport_hint` |
|
||||
| Tailscale Serve (ADR 25) | `hermes-relay-tailscale enable|disable|status` CLI | Fronts loopback `:8767` with `tailscale serve --bg --https=<port>`; auto-retires on upstream PR #9295 |
|
||||
| Inbound media (token) | `GET /media/{token}` | Bearer auth; 24h TTL |
|
||||
| Inbound media (path) | `GET /media/by-path?path=<abs>` | Permissive by default; `RELAY_MEDIA_STRICT_SANDBOX=1` to restrict |
|
||||
| Session management | `GET /sessions`, `DELETE /sessions/{prefix}`, `PATCH /sessions/{prefix}` | List/revoke/extend; RelayHttpClient |
|
||||
| Voice transcribe | `POST /voice/transcribe` | multipart/form-data; bearer auth |
|
||||
| Voice synthesize | `POST /voice/synthesize` | JSON → audio/mpeg; max 5000 chars |
|
||||
| Voice config | `GET /voice/config` | Returns current tts/stt provider info |
|
||||
| Plugin diagnostics | `hermes relay doctor --json` | Reports upstream route reachability, Relay loopback state, plugin layout, and legacy bootstrap state |
|
||||
| Compat hook lifecycle | `hermes relay compat status/install/remove` | Optional legacy API compatibility hook; not required for the standard path |
|
||||
| Notifications | `GET /notifications/recent?limit=N` | Loopback callers skip bearer |
|
||||
| Relay health | `GET /health` on `:8767` | Used by `RelayHttpClient.probeHealth()` |
|
||||
| Capabilities | `GET /v1/capabilities` plus targeted `HEAD` probes | Prefer capabilities when present; HEAD probes keep mixed-version fallback working |
|
||||
| Desktop CLI (tui channel) | WSS `tui.attach` / `tui.rpc.request` / `tui.rpc.event` | Same channel + envelopes as the Ink TUI — the CLI just renders events as plain lines. Zero server changes. |
|
||||
| Desktop CLI (terminal channel) | WSS `terminal.attach` / `terminal.input` / `terminal.output` / `terminal.resize` / `terminal.detached` | Existing channel (shared with Android). CLI `shell` subcommand attaches, injects `clear; exec hermes\n` 350ms after ack, pipes raw bytes. `Ctrl+A .` detaches (tmux preserved), `Ctrl+A k` kills. |
|
||||
| Desktop CLI tool visibility | `tools.list` RPC on the shared tui channel | Returns `{toolsets: [{name, description, tool_count, enabled, tools:[]}]}`; surfaced by `hermes-relay tools` |
|
||||
| Desktop CLI devices | HTTP `GET/DELETE/PATCH /sessions` on the relay's same port | Wrapped by `hermes-relay devices list |
|
||||
| Desktop tool routing (Phase B) | WSS `desktop.command` (s→c) + `desktop.response` (c→s) + `desktop.status` (c→s heartbeat) | New channel. Hermes calls `desktop_read_file(path)` → Python handler POSTs to `/desktop/desktop_read_file` → relay forwards over `desktop.command` → Node client's `DesktopToolRouter` runs the handler locally → response bubbles back. Mirror of Android's `bridge.command` pattern. |
|
||||
| Desktop tool check_fn | HTTP `GET /desktop/_ping?tool=<name>` | Returns 200 if a client is connected AND advertises this tool; 503 otherwise. Hermes uses this to fail the tool quickly when no desktop client is live, instead of waiting 30s for the dispatch timeout. |
|
||||
| Desktop health | HTTP `GET /desktop/health` | Returns full status snapshot — connected/host/platform/version/pid/uptime/advertised_tools/last_error/recent_commands. Loopback-only. Backs the `desktop_health` agent tool, which intentionally does NOT round-trip through the client so it remains callable when other tools are wedged. |
|
||||
|
||||
|
||||
## Upstream References
|
||||
|
||||
|
||||
| Topic | Upstream File |
|
||||
| -------------------------- | ----------------------------------------------------------------------------- |
|
||||
| API endpoints | `gateway/platforms/api_server.py` — all registered HTTP routes |
|
||||
| Platform adapter interface | `gateway/platforms/base.py` — `BasePlatformAdapter` abstract class |
|
||||
| Adding a platform | `gateway/platforms/ADDING_A_PLATFORM.md` — 16-step checklist |
|
||||
| Platform registration | `gateway/run.py` → `_create_adapter()`, `gateway/config.py` → `Platform` enum |
|
||||
| Channel directory | `gateway/channel_directory.py` — how platforms/channels are enumerated |
|
||||
| Send message routing | `tools/send_message_tool.py` → `platform_map` dict |
|
||||
| SSE streaming (runs) | `gateway/platforms/api_server.py` → runs endpoint, `_on_tool_progress` |
|
||||
|
||||
|
||||
## Related Projects
|
||||
|
||||
- [**hermes-agent**](https://github.com/NousResearch/hermes-agent) — the agent platform (gateway, WebAPI, plugin system)
|
||||
- [**android-tools-mcp**](https://github.com/Codename-11/android-tools-mcp) — our fork of Android Studio MCP bridge (Compose previews, Gradle, docs)
|
||||
- [**mobile-mcp**](https://github.com/mobile-next/mobile-mcp) — device control MCP server (ADB, tap/swipe, screenshots)
|
||||
|
||||
@AGENTS.md
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
# Hermes-Relay CLI+UI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-15
|
||||
**Release Date:** 2026-09-02
|
||||
|
||||
This patch keeps the Windows management UI usable when the Relay daemon is stopped or its status cannot be read.
|
||||
This beta fixes Windows updates so the installed CLI and management UI advance together. Explicit CLI-only installations keep their standalone update path.
|
||||
|
||||
**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.
|
||||
**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/arm64, and macOS x64/arm64; the management UI is Windows-only.
|
||||
|
||||
## What's changed
|
||||
|
||||
### Fixed
|
||||
|
||||
- **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.
|
||||
- `hermes-relay update` detects an installed management UI beside the CLI and reports both installed versions.
|
||||
- Bundle installations use the checksum-verified Windows installer to update and restart the affected CLI and UI together.
|
||||
- Explicit CLI-only installations continue to use the standalone binary updater.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -43,7 +44,3 @@ hermes-relay hosts list --json
|
||||
hermes-relay daemon start
|
||||
hermes-relay daemon status --json
|
||||
```
|
||||
|
||||
On Windows, click the Hermes-Relay CLI UI notification-area icon to open the management popup directly above it.
|
||||
|
||||
See the [CLI and tray guide](https://hermes-relay.dev/docs/desktop/) for installation, access modes, grants, and troubleshooting.
|
||||
|
||||
@@ -61,6 +61,15 @@ configuration between invocations and do not add `--no-daemon` to normal dev
|
||||
commands; a different heap or Java home starts a separate daemon and discards
|
||||
the warm-process benefit.
|
||||
|
||||
On Windows, all repository dev helpers serialize Android build and device work
|
||||
through one machine-wide lane shared by every Hermes-Relay worktree. Use
|
||||
`scripts/android-lane.ps1` for ad hoc Gradle, connected-test, and APK-install
|
||||
commands, and keep Android Studio idle while another owner holds the lane. For
|
||||
an exact commit that is already pushed, prefer the `Android On-Demand` workflow
|
||||
for heavy verification so concurrent worktrees use isolated GitHub-hosted
|
||||
runners. See [Android build execution](docs/android-build-lane.md) for cloud
|
||||
presets, the optional full local gate, status, and recovery modes.
|
||||
|
||||
Use the narrowest command that proves the change:
|
||||
|
||||
1. `scripts/dev.bat compile` for a Kotlin compile check.
|
||||
@@ -68,7 +77,15 @@ Use the narrowest command that proves the change:
|
||||
3. `scripts/dev.bat install-fast` when the result must run on the connected
|
||||
arm64 phone. This passes `-Phermes.devAbi=arm64-v8a`, avoiding the x86,
|
||||
x86_64, and armeabi-v7a native libraries in the local APK.
|
||||
4. `scripts/dev.bat prepush` before pushing Android work.
|
||||
4. `Android On-Demand` after an exact commit is pushed for lint, broad checks,
|
||||
assemblies, or release smoke.
|
||||
5. `scripts/dev.bat prepush` only when full local verification is explicitly
|
||||
wanted or cloud execution is unavailable.
|
||||
|
||||
Android release preparation uses `python scripts/android-prepush.py
|
||||
--release-prep` while version notes are changing. It keeps local feedback to
|
||||
metadata and release-presentation tests; the exact pushed commit still goes
|
||||
through required CI and Play preflight before publication.
|
||||
|
||||
`install-fast` is intentionally phone-specific. Use `install` for a universal
|
||||
sideload debug APK or when the target ABI is not arm64. Release builds remain
|
||||
@@ -104,6 +121,24 @@ The legacy `relay_server/` directory is a thin compatibility shim around `plugin
|
||||
| **CI/CD** | GitHub Actions (lint, build, test, signed APK artifacts) |
|
||||
| **Min SDK** | 26 (Android 8.0) / Target SDK 36 |
|
||||
|
||||
## Issues and automated triage
|
||||
|
||||
New issues may receive one first response headed **Hermes-Relay automated
|
||||
triage**. It reads the live report against current code, documentation, related
|
||||
issues, and public release state; it may add existing type/area labels and ask
|
||||
for a focused, safe diagnostic such as the app version, interaction mode, or a
|
||||
sanitized log excerpt.
|
||||
|
||||
GitHub displays the response as authored by `hermes-relay-triage[bot]`, a
|
||||
repository-scoped App rather than a maintainer's personal account.
|
||||
|
||||
That reply is an acknowledgement and initial analysis, not a maintainer
|
||||
decision. The automated path may assign `Codename-11` as the fixed owner for
|
||||
follow-up, but assignment does not mean acceptance, priority, implementation,
|
||||
or a release commitment. It does not close issues, choose another assignee, set
|
||||
milestones or priority, promise a fix or release, or continue the conversation.
|
||||
A maintainer will follow up on the thread.
|
||||
|
||||
## Running the Relay Locally
|
||||
|
||||
Only needed if you're working on the bridge, voice, notifications, or media features. Chat alone doesn't need the relay.
|
||||
@@ -145,6 +180,23 @@ documentation fixes.
|
||||
`main` is release history, not the normal contribution target; it receives
|
||||
approved release PRs from `dev` and focused hotfix PRs based on production tags.
|
||||
|
||||
Pull requests use [the repository template](.github/pull_request_template.md).
|
||||
Keep the body grounded: describe the outcome and focused changes, list exact
|
||||
verification, include visual evidence when applicable, state compatibility or
|
||||
risk, and preserve contributor lineage when replacing or salvaging prior work.
|
||||
Check an item when it is satisfied or when its N/A rationale is written in the
|
||||
body; do not use checked boxes as a substitute for evidence.
|
||||
|
||||
New external-contributor, non-draft pull requests may receive one
|
||||
**Hermes-Relay automated PR intake** reply from `hermes-relay-triage[bot]`.
|
||||
Owner-authored `Codename-11` PRs and bot PRs skip this lane. For eligible PRs,
|
||||
the bot checks the live body, base branch, changed-path areas, template
|
||||
completeness, stated verification, visual proof, and lineage without checking
|
||||
out or executing contributor code. It may add bounded area/intake labels and
|
||||
identify missing evidence, but it does not review code correctness, approve,
|
||||
request changes, merge, close, assign, request reviewers, push commits, edit the
|
||||
PR, rerun workflows, or select review bundles.
|
||||
|
||||
`origin/dev` is the canonical integration ref. Keep local `dev` as a clean,
|
||||
fast-forward-only mirror and create each task in its own branch/worktree from the
|
||||
current `origin/dev`. Do not accumulate unpublished commits on local `dev`. If a
|
||||
@@ -207,28 +259,36 @@ translations may ship as `ai-translated`; do not claim fluent review unless a
|
||||
review reference is recorded. Focused correction PRs from fluent contributors
|
||||
are the canonical way to improve wording and can advance a locale to
|
||||
`community-reviewed` or `verified` under `docs/translation-playbook.md`.
|
||||
Translated READMEs use separate `README.<locale>.md` files; `README.md` remains
|
||||
the canonical project description. User docs may be added incrementally under
|
||||
`user-docs/<locale>/`, with links back to canonical English reference material.
|
||||
Translated README entrypoints live under `docs/readme/` as
|
||||
`README.<locale>.md`; root `README.md` remains the canonical project
|
||||
description. Keep translated entrypoints concise: summarize onboarding and
|
||||
core capabilities, link to localized user docs where available, and link back
|
||||
to English for fast-moving architecture, security, and operator detail. User
|
||||
docs may be added incrementally under `user-docs/<locale>/`, with links back to
|
||||
canonical English reference material.
|
||||
|
||||
## Changelog & writing conventions
|
||||
|
||||
This is a **public repo** — `CHANGELOG.md`, `DEVLOG.md`, the README, and everything under `docs/` ship publicly. Keep them clean:
|
||||
This is a **public repo** — `CHANGELOG.md`, `docs/project/DEVLOG.md`, the README, and everything under `docs/` ship publicly. Keep them clean:
|
||||
|
||||
- **`CHANGELOG.md`** follows [Keep a Changelog](https://keepachangelog.com/) (Added / Changed / Fixed). Append your change to the `## [Unreleased]` block in the PR. Entries can carry detail while they accumulate, but at release-prep the version block is **condensed to crisp public bullets** (1–2 lines each) — the deep "how we debugged it" narrative belongs in commit messages and `DEVLOG.md`, not the public changelog.
|
||||
- **`DEVLOG.md`** is a factual engineering log — what changed, why, and how it was verified. Keep it depersonalized and third-person; it's a record, not a diary.
|
||||
- **`CHANGELOG.md`** follows [Keep a Changelog](https://keepachangelog.com/) (Added / Changed / Fixed). Append your change to the `## [Unreleased]` block in the PR. Entries can carry detail while they accumulate, but at release-prep the version block is **condensed to crisp public bullets** (1–2 lines each) — the deep "how we debugged it" narrative belongs in commit messages and `docs/project/DEVLOG.md`, not the public changelog.
|
||||
- **`docs/project/DEVLOG.md`** is a factual engineering log — what changed, why, and how it was verified. Keep it depersonalized and third-person; it's a record, not a diary.
|
||||
- **No non-public wording anywhere committed:** no personal names (attribute impersonally — identity lives in git history), no real server hostnames/IPs or internal deployment names, no AI/assistant process self-narration, no fork/branch plumbing in user-facing notes. Generic example IPs in setup docs are fine.
|
||||
|
||||
Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/play-store-listing.md`) are theme-framed and user-facing; see [RELEASE.md](RELEASE.md) §2 "Scrub for public distribution" for the full checklist.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Android pre-push gate:** `scripts\dev.bat prepush` on Windows or
|
||||
`./scripts/dev.sh prepush` on macOS/Linux. This runs the Android repository
|
||||
checks, Google Play debug lint, and the same focused unit-test shard used by
|
||||
CI in one cached Gradle invocation. Run it before pushing Android PR updates
|
||||
to catch common hosted failures without waiting for another full Actions
|
||||
cycle; hosted CI remains the exhaustive all-variant gate.
|
||||
- **Android cloud verification (preferred for pushed work):** dispatch the
|
||||
registered `Required checks` workflow with an exact base/head SHA pair and
|
||||
`android_preset` set to `focused`, `lint`, `assemble-debug`, `release-smoke`,
|
||||
or `all-final`. It calls the reusable Android workflow from `dev`. Check for
|
||||
an existing run before dispatching the same SHA/preset again. The four
|
||||
`all-final` compute jobs use isolated runners and may execute concurrently.
|
||||
- **Full local Android gate (optional):** `scripts\dev.bat prepush` on Windows
|
||||
or `./scripts/dev.sh prepush` on macOS/Linux. This retains the repository
|
||||
checks, full Android lint, and both focused flavor shards for an explicit local
|
||||
run or cloud outage. On Windows it acquires the machine-wide lane.
|
||||
- **Focused Android unit test:** `scripts/dev.bat test-one "<fully-qualified-class-or-pattern>"`
|
||||
- **Android unit tests:** `scripts/dev.bat test` (runs the sideload debug JUnit + MockK + Compose suite)
|
||||
- **Gateway contract lab:** [`docs/gateway-contract-testing.md`](docs/gateway-contract-testing.md)
|
||||
@@ -237,7 +297,7 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
|
||||
device lane is scheduled automatically.
|
||||
- **Python tests:** `python -m unittest plugin.tests.test_<name>` from the repo root with the hermes-agent venv active. `pytest` works too but the pre-existing `conftest.py` imports a module that isn't always installed — `unittest` avoids that entirely.
|
||||
|
||||
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched.
|
||||
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched. The registered `ci-required.yml` dispatcher calls `android-on-demand.yml` as the trusted manual compute lane for an exact pushed commit; it does not replace required PR checks.
|
||||
Superseded Android runs on `dev` and PR refs are canceled automatically; `main`
|
||||
runs are never canceled because each release-branch commit must complete its
|
||||
independent validation.
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
# Hermes-Relay Plugin v__VERSION__
|
||||
|
||||
**Release Date:** August 21, 2026
|
||||
**Release Date:** September 13, 2026
|
||||
|
||||
## 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.
|
||||
Dashboard WebSocket connections work again with current Hermes authentication helpers, while older Hermes hosts remain supported.
|
||||
|
||||
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
|
||||
## Fixed
|
||||
|
||||
## Added
|
||||
|
||||
- **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.
|
||||
|
||||
## 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.
|
||||
- Resolve WebSocket guards from their current upstream module and retain the older-host fallback. Single-use tickets, Host/Origin/IP checks, and independent Hermes-Relay session authentication remain enforced. Missing or incomplete helper contracts deny admission.
|
||||
|
||||
## Install / update
|
||||
|
||||
@@ -27,6 +20,8 @@ Standard chat, session history, and Vanilla Hermes voice remain upstream-owned a
|
||||
# or, if already installed:
|
||||
hermes-relay-update
|
||||
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest and prompt context are active.
|
||||
|
||||
## Verify
|
||||
|
||||
hermes relay doctor
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — your Hermes agent, in your pocket" width="800">
|
||||
<img src="assets/readme-hero-v2.jpg" alt="Hermes-Relay — Your Hermes agent. Wherever you are. Android, Voice, Desktop." width="1000">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -17,11 +17,17 @@
|
||||
<a href="https://developer.android.com/about/versions/oreo"><img src="https://img.shields.io/badge/Android-8.0%2B-3DDC84.svg?logo=android&logoColor=white" alt="Android 8.0+"></a>
|
||||
<a href="https://github.com/Codename-11/hermes-relay/actions/workflows/ci-android.yml"><img src="https://github.com/Codename-11/hermes-relay/actions/workflows/ci-android.yml/badge.svg" alt="Android CI"></a>
|
||||
<a href="https://github.com/Codename-11/hermes-relay/releases"><img src="https://img.shields.io/github/v/release/Codename-11/hermes-relay?filter=android-v*&label=release&color=8B5CF6" alt="Latest release"></a>
|
||||
<a href="https://github.com/Codename-11/hermes-relay/tree/main/desktop"><img src="https://img.shields.io/badge/CLI-alpha-orange.svg" alt="CLI (alpha)"></a>
|
||||
<a href="https://github.com/Codename-11/hermes-relay/tree/main/desktop"><img src="https://img.shields.io/badge/CLI-beta-756cff.svg" alt="CLI (beta)"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> · <a href="README.zh-CN.md">简体中文</a><br>
|
||||
<strong>English</strong> ·
|
||||
<a href="docs/readme/README.de.md">Deutsch</a> ·
|
||||
<a href="docs/readme/README.es.md">Español</a> ·
|
||||
<a href="docs/readme/README.ja.md">日本語</a> ·
|
||||
<a href="docs/readme/README.pt-BR.md">Português (Brasil)</a> ·
|
||||
<a href="docs/readme/README.ru.md">Русский</a> ·
|
||||
<a href="docs/readme/README.zh-CN.md">简体中文</a><br>
|
||||
<a href="https://hermes-relay.dev/docs/">Documentation</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/releases">Releases</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/discussions">Discussions</a> ·
|
||||
@@ -36,12 +42,12 @@
|
||||
Hermes-Relay puts your [Hermes agent](https://github.com/NousResearch/hermes-agent) on the devices you actually carry. The brain stays on your own machine — Hermes-Relay is how you reach it.
|
||||
|
||||
- **📱 Android app** — streaming chat, hands-free voice, native plugin pages, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. Add a floating Petdex companion or optionally make Hermes your Android assistant; sideload builds can also let the agent read and act on your screen.
|
||||
- **⌨️ Hermes-Relay CLI** *(alpha)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
|
||||
- **⌨️ Hermes-Relay CLI** *(beta)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
|
||||
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough — chat, management, voice, Petdex, and ordinary installed-plugin pages need **no Relay plugin**. Add the optional Relay only when you want terminal, phone control, agent-created page drafts, or the CLI's tools. **Pair once from either surface; both work.**
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, inbound files, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, desktop tools, enhanced voice, Relay sessions, page drafts, optional Device Control, and media compatibility or metadata. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/diagrams/architecture-homepage.png" alt="How Hermes-Relay connects — Vanilla Hermes (Chat, Manage, Voice) runs with no plugin; the optional Relay plugin adds Terminal, Bridge, relay voice and desktop tools to the app and CLI; Device Control needs the sideload build." width="900">
|
||||
<img src="assets/readme-connection-map-v2.png" alt="How Hermes-Relay connects — Dashboard and Gateway own the standard Android path for Chat, Manage, Voice, and inbound files; the optional Relay plugin separately adds Android enhancements plus CLI and UI tools; sideload adds Device Control." width="1000">
|
||||
</p>
|
||||
|
||||
## Quick Start (Android)
|
||||
@@ -50,7 +56,7 @@ Install → connect → talk, in about two minutes.
|
||||
|
||||
### 1 · Install the app
|
||||
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, Manage, terminal/TUI, media, notifications, and relay sessions.
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, Manage, and inbound files work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, notifications, Relay sessions, and media enhancements.
|
||||
- **APK** *(full phone-control feature set)* — download the file ending in **`-sideload-release.apk`** from the newest `android-v*` release on [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases) and open it (allow your browser to install unknown apps the first time). Integrity verification, signing fingerprint, and per-build details are in the [Sideload guide](https://hermes-relay.dev/docs/guide/getting-started.html#sideload-apk).
|
||||
|
||||
Sideload builds check GitHub for updates and show a one-tap banner when you're behind; Play builds update through the Store. See [Release tracks](https://hermes-relay.dev/docs/guide/release-tracks) for the capability matrix.
|
||||
@@ -58,7 +64,7 @@ Sideload builds check GitHub for updates and show a one-tap banner when you're b
|
||||
### 2 · Have the Hermes Dashboard running
|
||||
|
||||
The normal Android connection uses the upstream Hermes Dashboard/Gateway for
|
||||
chat, sign-in, sessions, Manage, and voice. Installing Hermes and choosing a
|
||||
chat, sign-in, sessions, Manage, voice, and inbound files. Installing Hermes and choosing a
|
||||
provider is vanilla Hermes setup:
|
||||
|
||||
```bash
|
||||
@@ -71,27 +77,20 @@ 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.
|
||||
Start on a trusted LAN. For away-from-home access, Tailscale is the recommended
|
||||
path. Secure Link, public TLS, and experimental routing options are covered in
|
||||
the [remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
||||
|
||||
### 3 · Connect and talk
|
||||
|
||||
Open the app, choose **Connect to Hermes**, and enter or discover the dashboard
|
||||
address (conventionally `http://<host>:9119`). Sign in through the dashboard's
|
||||
configured provider when prompted. The app probes the available upstream
|
||||
capabilities and finishes with a connection summary.
|
||||
Use **Find Hermes on LAN** or enter the Dashboard address manually
|
||||
(conventionally `http://<host>:9119`). Sign in through the
|
||||
Dashboard's configured provider when prompted. The app probes the available
|
||||
upstream capabilities and finishes with a connection summary.
|
||||
|
||||
If the Relay Dashboard page is already installed, **Connect mobile app** offers
|
||||
the same standard connection as a tokenless QR. It contains only the Dashboard
|
||||
address and does not install, enable, or pair Relay.
|
||||
|
||||
The separate API server can be discovered automatically or added later under
|
||||
**Advanced** as a chat fallback or for a headless compatibility setup. Its API
|
||||
@@ -105,50 +104,48 @@ The wizard probes everything and finishes with a capability card:
|
||||
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
||||
| **API fallback** | Optional API route available/unavailable |
|
||||
| **Relay** | Optional extensions — fine to leave unpaired |
|
||||
| **Direct API** | Optional API-only compatibility route available/unavailable |
|
||||
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
the whole Vanilla Hermes setup.
|
||||
|
||||
> **Going places?** Add the Dashboard's Tailscale address — for example `http://100.x.y.z:9119` or a separately published `https://host.ts.net` URL — under **Settings → Connections → Routes**. Android tests it as a Dashboard route; no API server or API key is required. The app uses LAN at home and switches routes automatically when you leave. See [Remote access](https://hermes-relay.dev/docs/guide/remote-access).
|
||||
> **Going places?** Add the Dashboard's Tailscale address — for example `http://100.x.y.z:9119` or a separately published `https://host.ts.net` URL — under **Settings → Gateways → Routes**. Android tests it as a Dashboard route; no API server or API key is required. The app uses LAN at home and switches routes automatically when you leave. See [Remote access](https://hermes-relay.dev/docs/guide/remote-access).
|
||||
|
||||
### 4 · Optional: install Relay for power tools
|
||||
### 4 · Recommended: pair Relay for the complete experience
|
||||
|
||||
Install the Relay plugin on the server only when you want Terminal, Bridge phone control, relay sessions, media routes, the realtime voice engine, or approval-gated agent-created plugin-page drafts:
|
||||
Install Relay for Terminal/TUI, notifications, desktop tools, enhanced voice,
|
||||
Relay sessions, approval-gated page drafts, optional Device Control, and media
|
||||
compatibility or sensitivity metadata:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
hermes relay doctor
|
||||
hermes relay start --no-ssl
|
||||
hermes pair
|
||||
```
|
||||
|
||||
Use the legacy installer instead if you also want the systemd user service,
|
||||
shell shims, and the full clone/update workflow:
|
||||
Use `--no-ssl` only on a trusted LAN or VPN. Use the
|
||||
[remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/) before
|
||||
exposing any Hermes surface beyond that network.
|
||||
|
||||
Refresh or restart the Dashboard/Gateway, open **Relay → Pair new device**, and
|
||||
scan the one-time QR from Android **Settings → Gateways → Access → Pair Relay**.
|
||||
Leave mode on **Auto** for the recommended route discovery. The same dialog
|
||||
shows a copyable invite for Desktop CLI clients:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Codename-11/hermes-relay/main/install.sh | bash
|
||||
hermes-relay pair --pair-qr "hermes-relay://pair?payload=…" --grant-tools
|
||||
```
|
||||
|
||||
Installed Hermes plugins can expose bounded, host-rendered pages to Android
|
||||
through the authenticated Dashboard without running plugin code on the phone.
|
||||
Relay 1.5.0 additionally supports approval-gated agent-created page drafts. The
|
||||
plugin-manager install owns the plugin code, dashboard tab, CLI commands, and
|
||||
agent tools. `hermes relay compat status/install/remove` manages only the
|
||||
optional legacy API compatibility hook when an older Hermes build needs it. Scan
|
||||
the QR from the phone's Connections screen — or use
|
||||
`hermes pair --register-code ABCD12` with the manual code from Android
|
||||
**Settings → Connections → Advanced**.
|
||||
As alternatives, `hermes pair` renders the same Android QR and pasteable invite
|
||||
in a terminal, while URL + six-character code and `--register-code` remain
|
||||
manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
|
||||
- **Plugin-manager uninstall:** `hermes relay compat remove --all` if you installed the optional hook, then `hermes plugins remove hermes-relay`.
|
||||
- **Legacy installer update:** `hermes-relay-update` (idempotent) — or re-run the install one-liner.
|
||||
- **Legacy installer uninstall:** `bash ~/.hermes/hermes-relay/uninstall.sh` — removes the service, shims, clone, external skill path, editable package, and compat hook. It never touches shared Hermes state. Flags: `--dry-run`, `--keep-clone`, `--remove-secret`.
|
||||
- **Dashboard plugin:** installs with the same symlink — restart the gateway and a **Relay** tab (paired devices, bridge activity, media tokens) appears in the web UI.
|
||||
**Next:** [Android + Hermes-Relay Quick Start](https://hermes-relay.dev/docs/guide/quick-start) ·
|
||||
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
|
||||
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
|
||||
|
||||
Full server setup, TLS, and systemd details: [docs/relay-server.md](docs/relay-server.md).
|
||||
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ on the server. The API server and Relay are optional.
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -162,11 +159,16 @@ Full server setup, TLS, and systemd details: [docs/relay-server.md](docs/relay-s
|
||||
<tr>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/05_themes.png" alt="App themes" width="100%"><br><sub><b>App themes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/06_manage.png" alt="Manage your agent" width="100%"><br><sub><b>Manage your agent</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/07_connections.png" alt="Connections and routes" width="100%"><br><sub><b>Connections & routes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/07_connections.png" alt="Gateways and routes" width="100%"><br><sub><b>Gateways & routes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/08_appearance.png" alt="Agent avatar & skins" width="100%"><br><sub><b>Avatars & skins</b></sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/supplemental/15_git_workspace.png" alt="Native Git workspace showing repository changes, an inline diff, and staging controls" width="260"><br>
|
||||
<sub><b>Native Git workspace</b> — upstream session context with optional Relay discovery and operations</sub>
|
||||
</p>
|
||||
|
||||
### Simplified Chinese
|
||||
|
||||
<table>
|
||||
@@ -193,16 +195,16 @@ tracked independently so community corrections remain easy to contribute.
|
||||
- **Hands-free voice** — talk on a vanilla install: speech rides your server's configured providers, unlocked by the same Manage sign-in. Relay-paired setups add per-profile voice and an opt-in provider-native Realtime Agent with background task handoff.
|
||||
- **Works away from home** — add a Tailscale or public URL and the app roams automatically (LAN at home, fallback elsewhere). An unreachable server gets a diagnosis, not just a red dot.
|
||||
- **Multi-Connection + profiles** — pair multiple Hermes servers (home + work, dev + prod) and switch in one tap; overlay a profile's model + `SOUL.md` per chat.
|
||||
- **Phone control (bridge)** — with Relay paired, the agent reads the screen and acts: tap, type, swipe, scroll, screenshots, clipboard, media keys, batched macros. Guarded by per-app blocklist (banking/2FA blocked by default), destructive-verb confirmation, idle auto-disable, and a full activity log.
|
||||
- **Device Control (Sideload + Hermes-Relay required)** — the agent can read the screen and act: tap, type, swipe, scroll, screenshots, clipboard, media keys, and batched macros. This is not included in the Google Play build. It is guarded by a per-app blocklist (banking/2FA blocked by default), destructive-verb confirmation, idle auto-disable, and a full activity log.
|
||||
- **Notification companion** — opt-in access so the agent can triage, summarize, and route incoming notifications.
|
||||
- **Security & pairing** — QR pairing, Android Keystore session storage (StrongBox-preferred), TOFU cert pinning, per-channel time-bound grants, user-chosen session TTL.
|
||||
- **Stats for Nerds** — local-only analytics: TTFT, token usage, stream health, peak-time charts.
|
||||
|
||||
> Sideload builds add direct SMS, contact search, one-tap dialing, and location awareness — handy for fully hands-free intents like *"text Sam I'll be 10 minutes late."* See [Release tracks](https://hermes-relay.dev/docs/guide/release-tracks).
|
||||
|
||||
## Hands on any machine — the Hermes-Relay CLI <sub>(alpha)</sub>
|
||||
## Hands on any machine — the Hermes-Relay CLI <sub>(beta)</sub>
|
||||
|
||||
> **Alpha.** Self-contained CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64 — no Node required. Windows also has an optional compact management tray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
|
||||
> **Beta.** Self-contained CLI binaries ship for Windows x64, Linux x64/arm64, and macOS x64/arm64 — no Node required. Windows also has an optional compact management tray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
|
||||
|
||||
The agent's brain stays on the host; the CLI lets it call tools **on your machine** over the same WSS relay — `read_file`, `write_file`, `terminal`, `search_files`, `screenshot`, `clipboard`, `open_in_editor`, and more — behind a one-time consent gate, interactive diff approval for patches, and a `--no-tools` kill-switch.
|
||||
|
||||
@@ -218,7 +220,15 @@ hermes-relay update # self-update via GitHub Releases
|
||||
|
||||
It pairs against the **same relay and credential store** as the Android app — pair once from either, both work. Tagged on the `desktop-v*` [release track](https://github.com/Codename-11/hermes-relay/releases?q=desktop), with historical releases still visible under `cli-v*`.
|
||||
|
||||
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.
|
||||
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. `hermes-relay update` detects this bundle and updates the CLI and UI together; explicit CLI-only installations stay headless and continue using the standalone binary updater. The UI is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/desktop-ui/overview.png" alt="Hermes-Relay CLI UI connected overview" width="100%"><br><sub><b>Connection & activity</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/desktop-ui/host-access.png" alt="Hermes-Relay CLI UI host access presets" width="100%"><br><sub><b>Per-host access</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/desktop-ui/settings.png" alt="Hermes-Relay CLI UI computer control and updates" width="100%"><br><sub><b>Control & maintenance</b></sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
Structured Windows computer control prefers a compatible local CUA Driver
|
||||
runtime for window-targeted background actions and virtual per-session agent
|
||||
@@ -234,17 +244,17 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice, inbound files]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media enhancements, relay voice, sessions]
|
||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||
```
|
||||
|
||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
||||
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
|
||||
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
|
||||
install needs no plugin for either. The optional relay on `:8767` adds the power
|
||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
||||
install needs no plugin for those surfaces or ordinary inbound files. The optional relay on `:8767` adds
|
||||
terminal, bridge phone control, media compatibility/metadata, machine tools, and
|
||||
relay-side voice, which is preferred automatically when paired. One QR can
|
||||
configure API, dashboard, and relay routes without merging their auth models.
|
||||
|
||||
@@ -348,7 +358,7 @@ hermes-relay/
|
||||
|
||||
<br>
|
||||
|
||||
End users should install via the [one-liner](#4--optional-install-relay-for-power-tools) above. For local development:
|
||||
End users should follow the [recommended Hermes-Relay setup](#4--recommended-pair-relay-for-the-complete-experience) above. For local development:
|
||||
|
||||
```bash
|
||||
hermes relay start --no-ssl # if you installed the plugin
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — 随身携带您的 Hermes 代理" width="800">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>运行在您的电脑上,连接到您的设备。</strong><br>
|
||||
Hermes-Relay 是 <a href="https://github.com/NousResearch/hermes-agent">Hermes Agent</a> 的原生 Android 客户端,提供流式聊天、免手动语音和代理管理;另有单文件 CLI,让代理在已配对的电脑上安全使用终端、文件和截图工具。
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>简体中文</strong> · <a href="README.md">English</a><br>
|
||||
<a href="https://hermes-relay.dev/docs/zh-CN/">中文文档</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/releases">版本下载</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/discussions">社区讨论</a> ·
|
||||
<a href="CHANGELOG.md">更新日志</a>
|
||||
</p>
|
||||
|
||||
> 英文 [README.md](README.md) 是最新、完整的项目说明。本页维护中文安装入口和核心功能摘要;协议、架构和维护者文档以英文版本为准。
|
||||
|
||||
## 功能简介
|
||||
|
||||
- **Android 应用**:流式聊天、会话历史、文件附件、Hermes 管理、语音模式、原生插件页面、Petdex 悬浮宠物、多连接和配置文件;也可将 Hermes 设为 Android 助手。
|
||||
- **无需插件的标准路径**:聊天、管理和标准语音可直接连接未修改的上游 Hermes Agent。
|
||||
- **可选 Relay 插件**:增加终端、手机控制、媒体传输、通知助手、Relay 语音、电脑工具,以及需确认的代理创建插件页面草稿。
|
||||
- **安全连接**:二维码配对、Android Keystore、证书固定、按通道授权和可配置会话有效期。
|
||||
- **远程使用**:可配置 Tailscale 或 HTTPS 地址,在家庭局域网和远程路由之间自动切换。
|
||||
- **两种 Android 发行渠道**:Google Play 版本适合日常使用;sideload 版本包含完整手机控制能力。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装 Android 应用
|
||||
|
||||
- [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay):自动更新,包含聊天、语音、管理、终端、媒体和通知功能。
|
||||
- [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases):下载最新 `android-v*` 版本中以 `-sideload-release.apk` 结尾的文件,获得完整手机控制功能。
|
||||
|
||||
### 2. 启动 Hermes API 服务
|
||||
|
||||
手机需要能够访问 Hermes API 服务,并使用 API 密钥进行身份验证:
|
||||
|
||||
```bash
|
||||
hermes setup --portal
|
||||
|
||||
mkdir -p ~/.hermes
|
||||
API_SERVER_KEY="$(openssl rand -hex 32)"
|
||||
cat >> ~/.hermes/.env <<EOF
|
||||
API_SERVER_ENABLED=true
|
||||
API_SERVER_HOST=0.0.0.0
|
||||
API_SERVER_PORT=8642
|
||||
API_SERVER_KEY=$API_SERVER_KEY
|
||||
EOF
|
||||
chmod 600 ~/.hermes/.env
|
||||
|
||||
echo "Android API URL: http://<电脑IP>:8642 key: $API_SERVER_KEY"
|
||||
hermes gateway
|
||||
```
|
||||
|
||||
`0.0.0.0` 会让同一网络中的设备访问 API。请保留强密钥;离开可信局域网时,应使用 Tailscale 或 HTTPS 反向代理,不要直接把端口暴露到互联网。
|
||||
|
||||
### 3. 在手机上连接
|
||||
|
||||
打开应用后,可以:
|
||||
|
||||
- 扫描局域网中的 Hermes;
|
||||
- 手动输入 `http://<主机>:8642` 和 API 密钥;
|
||||
- 扫描包含 API、Dashboard 和可选 Relay 地址的设置二维码。
|
||||
|
||||
如需在手机上管理模型、密钥、技能和配置文件,请运行 Hermes Dashboard,并在应用的 **管理** 页面登录一次。同一登录会话也会启用标准语音。
|
||||
|
||||
### 4. 可选:安装 Relay
|
||||
|
||||
仅在需要终端、手机控制、媒体路由、Relay 会话、实时语音、电脑工具或代理创建插件页面草稿时安装:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
hermes relay doctor
|
||||
hermes relay start --no-ssl
|
||||
hermes pair
|
||||
```
|
||||
|
||||
已安装的 Hermes 插件可通过已认证的 Dashboard 向 Android 提供由应用安全渲染的原生页面,无需在手机上运行插件代码。Relay 1.5.0 另支持需用户确认的代理创建页面草稿。
|
||||
|
||||
完整说明请阅读[中文快速开始](https://hermes-relay.dev/docs/zh-CN/guide/quick-start);远程访问、协议和高级配置暂时链接到英文参考文档。
|
||||
|
||||
安装问题、早期想法、一般交流和作品分享请使用 [GitHub Discussions](https://github.com/Codename-11/hermes-relay/discussions)。可复现的错误和明确、可执行的功能请求请提交到 [Issues](https://github.com/Codename-11/hermes-relay/issues/new)。
|
||||
|
||||
## 中文界面
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh01.jpg" alt="中文设置界面" width="100%"><br><sub><b>设置</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh02.jpg" alt="中文管理界面" width="100%"><br><sub><b>管理</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh03.jpg" alt="中文导航界面" width="100%"><br><sub><b>导航</b></sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 参与翻译
|
||||
|
||||
Android 英文资源是规范来源。新增语言必须保持资源名称、类型和格式参数一致,并通过:
|
||||
|
||||
```bash
|
||||
python scripts/check-android-locales.py
|
||||
./gradlew lint
|
||||
```
|
||||
|
||||
翻译规范、目录命名、复数和占位符规则见 [docs/localization.md](docs/localization.md)。
|
||||
|
||||
## 许可证
|
||||
|
||||
[MIT](LICENSE) — Copyright (c) 2026 [Axiom-Labs](https://codename-11.dev)
|
||||
@@ -200,6 +200,11 @@ never create a staging branch. Stable production tags are cut only from the new
|
||||
10. Build and publish that surface's artifacts, roll out or deploy from the
|
||||
immutable tag, and verify the release and live environment.
|
||||
|
||||
Do not back-merge a normal release. The `main` release merge already has the
|
||||
released `dev` tip as its integration parent, so merging it back only adds
|
||||
history noise. The release-backmerge workflow detects this topology and exits
|
||||
successfully without changing `dev`.
|
||||
|
||||
### Branch names
|
||||
|
||||
| Prefix | When | Example |
|
||||
@@ -258,7 +263,9 @@ The intended settings are:
|
||||
- **`main`** — PRs required; `Required checks` required and current; force push
|
||||
and deletion blocked. Normal work does not target this branch.
|
||||
- **`dev`** — PRs and `Required checks` required; force push and deletion
|
||||
blocked. This is the normal contribution target.
|
||||
blocked. This is the normal contribution target. The release-backmerge
|
||||
workflow is the sole exception: its automation identity may compare-and-swap
|
||||
`dev` to an exact checked merge commit after a stable hotfix release.
|
||||
- **Merge policy** — merge commits allowed; squash and rebase merges disabled so
|
||||
the no-ff contract cannot be bypassed in the GitHub UI.
|
||||
- **Default branch** — `main`, which remains the release-history branch and the
|
||||
@@ -523,10 +530,17 @@ the new app version and a higher `appVersionCode`.
|
||||
run Android's retrace tool with the matching flavor mapping:
|
||||
`retrace <mapping.txt> <obfuscated-trace.txt>`. Play reports can additionally
|
||||
use the mapping bundled into the uploaded AAB through Play Console.
|
||||
- `app/src/main/assets/whats_new.txt` — in-app "What's New" content
|
||||
shown in the settings/about screen. Update with the version number
|
||||
and a brief feature summary. Gets stale silently if forgotten
|
||||
(v0.4.0 shipped with 0.1.0 content until caught post-release).
|
||||
- `app/src/main/assets/changelog.json` — curated source for the in-app
|
||||
**What's New** dialog and Android release history. Prepend one schema-3 entry
|
||||
with a single descriptive release `title`, a plain-language `summary`, and a
|
||||
complete `changes` inventory. Every user-visible change has a stable `id`, a
|
||||
`kind` (`added`, `improved`, or `fixed`), a short title, a useful explanation,
|
||||
and an optional `highlight: true`; select 1–4 highlights. Add `compatibility`
|
||||
bullets only when users need an availability, migration, flavor, or Plugin
|
||||
boundary, plus Android-only `playNotes`. The app derives toast counts and
|
||||
previews from the same inventory and renders every change exactly once.
|
||||
- `app/src/main/assets/whats_new.txt` — legacy in-app fallback generated from
|
||||
the newest structured entry. Do not edit it independently.
|
||||
- `app/src/googlePlay/play/release-notes/en-US/default.txt` — the Play
|
||||
Console **"What's new"** text, which gradle-play-publisher reads at
|
||||
upload to fill the Production-draft release notes. This is **separate**
|
||||
@@ -534,19 +548,62 @@ the new app version and a higher `appVersionCode`.
|
||||
this file is missing or stale, the Play draft ships with empty/wrong
|
||||
notes (shipped empty in v1.1.0 until caught post-release). Keep it
|
||||
**≤500 chars per language**, user-facing, Android-only.
|
||||
- `docs/play-store-listing.md` — Play Store listing copy. Update
|
||||
the version reference and the "Release Notes" section that gets
|
||||
pasted into the Play Console "What's new" field. Keep the Play
|
||||
"What's new" within **500 characters** and framed around the
|
||||
release's themes, not a feature dump. Compare its **Foreground service
|
||||
- `docs/play-store-listing.md` — Play Store listing copy. Its release-note
|
||||
block and the Gradle Play Publisher note are generated from `playNotes`.
|
||||
After editing the newest structured entry, run
|
||||
`python scripts/check-android-release-notes.py --write`, then run it again
|
||||
without `--write` to validate complete unique change records, 1–4 highlights,
|
||||
the current Android version, GitHub-release/changelog headings, derived files, and Play's
|
||||
**500-character** limit. Frame Play copy around the release's themes, not a
|
||||
feature dump. Compare its **Foreground service
|
||||
permissions** section with the merged `googlePlayRelease` manifest and
|
||||
complete Play Console declarations for every declared service type before
|
||||
approval; the Publisher API can upload a draft and still reject promotion
|
||||
when an App content declaration is missing.
|
||||
|
||||
#### Generate release copy from the verified changes
|
||||
|
||||
When release copy is generated with an agent, this section is the canonical
|
||||
authoring contract; do not maintain a separate prompt file.
|
||||
|
||||
1. Read the exact Android version/SHA, the Android-only entries selected from
|
||||
`[Unreleased]`, the implemented behavior, and any compatibility or security
|
||||
boundary that users must understand. Do not generate from commit titles or
|
||||
a mixed-surface changelog block alone.
|
||||
2. Before editing release files, show a temporary coverage ledger in the task
|
||||
output. Map every selected Android source change to one stable change id and
|
||||
one kind (`added`, `improved`, or `fixed`), and mark whether it is a
|
||||
highlight. The ledger is review evidence, not a committed public artifact;
|
||||
no selected user-visible change may disappear silently or be counted twice.
|
||||
3. Write one release title that describes the release as a whole. Do not let a
|
||||
narrow feature name, internal project label, or poetic codename replace the
|
||||
title users see in the toast and history. Follow it with a one- or two-sentence
|
||||
summary that gives the release's overall outcome without becoming a feature dump.
|
||||
4. Select 1–4 highlights from the complete change inventory. A highlight is a
|
||||
strong reason to care, not a second copy of the change: the app presents it
|
||||
once in the highlight section and derives the remaining counts and previews
|
||||
from non-highlighted changes.
|
||||
5. Include every meaningful user-visible addition, improvement, and fix in
|
||||
`changes`, using plain titles and enough explanation for someone to recognize
|
||||
the affected behavior. Internal refactors, tests, CI mechanics, branch work,
|
||||
and debugging history stay in `RELEASE_NOTES.md`, `CHANGELOG.md`, or engineering
|
||||
records unless they materially change reliability, security, or compatibility.
|
||||
6. Write each surface for its audience:
|
||||
- `RELEASE_NOTES.md`: concise Summary plus Added/Changed/Fixed; keep the
|
||||
deterministic Download and Install/Verify scaffolding intact.
|
||||
- `CHANGELOG.md`: complete, crisp public history for the released surface.
|
||||
- `changelog.json`: overall title/summary, complete typed changes, selected
|
||||
highlights, compatibility boundaries, and Play copy. Counts and previews
|
||||
are derived; never author a parallel digest.
|
||||
- `playNotes`: Android-only themes within the rendered 500-character limit.
|
||||
7. Before presenting the draft, check that wording begins with user outcomes,
|
||||
avoids unexplained implementation terminology, uses exact public product
|
||||
names, makes no unverified device claim, and passes the public-distribution
|
||||
scrub below.
|
||||
|
||||
#### Scrub for public distribution
|
||||
|
||||
This is a **public repo** and these four files are user-facing. Before
|
||||
This is a **public repo** and these release-note files are user-facing. Before
|
||||
promoting the `[Unreleased]` block and writing the notes, scrub the
|
||||
versioned CHANGELOG block and all three release-notes artifacts for
|
||||
wording that shouldn't ship publicly. The CHANGELOG accumulates in a
|
||||
@@ -571,6 +628,21 @@ and the release notes and learn only what the software does.
|
||||
|
||||
### 3. Build and verify locally
|
||||
|
||||
During release-note/version iteration, use the narrow release-prep lane:
|
||||
|
||||
```powershell
|
||||
python scripts/android-prepush.py --release-prep
|
||||
```
|
||||
|
||||
It runs release metadata checks plus the rendered Changelog/What's New tests in
|
||||
the serialized Android lane. Once the exact commit is pushed, current-head CI
|
||||
and Play preflight own lint, focused shards, both-flavor assemblies, signing,
|
||||
and final package scans. Do not repeat the complete local release build unless
|
||||
cloud execution is unavailable or explicit local artifact/device proof is
|
||||
needed.
|
||||
|
||||
For that explicit full local proof:
|
||||
|
||||
```bat
|
||||
scripts\dev.bat bundle
|
||||
keytool -printcert -jarfile app\build\outputs\bundle\googlePlayRelease\hermes-relay-*-googlePlay-release.aab
|
||||
@@ -604,14 +676,17 @@ The preflight workflow:
|
||||
3. builds and release-signs the same APK/AAB variants used by the public release;
|
||||
4. scans the final minified APK DEX for unsupported collection calls;
|
||||
5. uploads the Google Play AAB as a private **Production draft**; and
|
||||
6. records a 30-day preflight proof keyed to the version and Git tree hash.
|
||||
6. retains the exact signed sideload APK, Play AAB, R8 mappings, manifest, and
|
||||
checksums as one immutable 30-day artifact keyed to version and Git tree.
|
||||
|
||||
No sideload APK or GitHub Release is published by preflight. A successful signed
|
||||
build, final DEX scan, and Production-draft upload is the automated Play release
|
||||
gate. Play Console pre-review and pre-launch reports are informational and
|
||||
non-blocking because their detailed results are not exposed through the release
|
||||
automation API. If the release source changes after preflight, rerun it—the
|
||||
approval workflow matches the complete Git tree, not just the version number.
|
||||
build, final package scans, and Production-draft upload is the automated Play
|
||||
release gate. The private artifact is immutable and hash-verified again before
|
||||
publication; the stable release workflow does not rebuild those bytes. Play
|
||||
Console pre-review and pre-launch reports are informational and non-blocking
|
||||
because their detailed results are not exposed through the release automation
|
||||
API. If the release source changes after preflight, rerun it—the approval
|
||||
workflow matches the complete Git tree, not just the version number.
|
||||
|
||||
GitHub exposes manual workflows only after their workflow file exists on the
|
||||
default branch. For the first release that introduces this process, merge the
|
||||
@@ -632,7 +707,9 @@ git checkout dev
|
||||
git pull --ff-only origin dev
|
||||
|
||||
git add gradle/libs.versions.toml RELEASE_NOTES.md CHANGELOG.md \
|
||||
app/src/main/assets/whats_new.txt docs/play-store-listing.md
|
||||
app/src/main/assets/changelog.json app/src/main/assets/whats_new.txt \
|
||||
app/src/googlePlay/play/release-notes/en-US/default.txt \
|
||||
docs/play-store-listing.md
|
||||
git commit -m "release(android): android-v0.6.2"
|
||||
git push origin dev
|
||||
|
||||
@@ -650,12 +727,13 @@ from `main`; every release job explicitly checks out and verifies the immutable
|
||||
an existing tag or changing its artifact tree. Manual stable tags are still
|
||||
guarded by the same preflight proof in the tag workflow.
|
||||
|
||||
The tag-triggered `.github/workflows/release-android.yml` rebuilds and scans the
|
||||
artifacts, changes the existing Play Production draft to `completed` (submitting
|
||||
it for review), and only after Play accepts that operation creates the public
|
||||
GitHub Release with the sideload APK. A missing preflight, changed release tree,
|
||||
missing Play credential, or Play submission failure prevents public GitHub
|
||||
publication.
|
||||
The tag-triggered `.github/workflows/release-android.yml` downloads the exact
|
||||
private preflight artifact by ID, verifies its source workflow, manifest, tree,
|
||||
version, sizes, and hashes, reruns the package scanners, then changes the
|
||||
existing Play Production draft to `completed` (submitting it for review). Only
|
||||
after Play accepts that operation does it publish those same APK/AAB bytes on
|
||||
GitHub. A missing preflight, changed release tree, artifact mismatch, missing
|
||||
Play credential, or Play submission failure prevents public publication.
|
||||
|
||||
Plugin/Python version files are intentionally not part of an Android app
|
||||
release unless the plugin package itself is also being released.
|
||||
@@ -684,14 +762,19 @@ git commit -m "release(server): server-v0.6.2"
|
||||
git push origin dev
|
||||
|
||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
||||
# After merge, tag from the new main tip:
|
||||
git checkout main
|
||||
git pull --ff-only origin main
|
||||
git tag server-v0.6.2
|
||||
git push origin server-v0.6.2
|
||||
# Then run "Hermes-Relay Plugin and CLI+UI Release Approval" from main,
|
||||
# select plugin, and enter 0.6.2. The workflow selects and validates main
|
||||
# before it creates server-v0.6.2 and starts the immutable-tag release workflow.
|
||||
```
|
||||
|
||||
Pushing `server-v*` triggers `.github/workflows/release-plugin.yml`, which
|
||||
For a Plugin prerelease, keep the release-prepared commit on `dev` and run the
|
||||
same trusted approval workflow from `main`; the version suffix makes it select
|
||||
and validate the exact `origin/dev` tip before creating the tag. Stable versions
|
||||
select `origin/main` instead.
|
||||
Direct `server-v*` tag pushes remain a recovery path and are guarded by the same
|
||||
branch-containment and metadata checks.
|
||||
|
||||
The approval workflow dispatches `.github/workflows/release-plugin.yml`, which
|
||||
validates all plugin-owned version metadata with
|
||||
`scripts/check-plugin-version-sync.py`. Run
|
||||
`python scripts/check-version-tracks.py` locally before tagging when a change
|
||||
@@ -722,20 +805,25 @@ git add desktop/package.json desktop/package-lock.json desktop/src/version.ts `
|
||||
git commit -m "release(desktop): desktop-v0.4.0-alpha.2"
|
||||
git push origin dev
|
||||
|
||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
||||
# After merge, tag from main:
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
cd desktop
|
||||
npm run check:version-sync -- --expect 0.4.0-alpha.2
|
||||
cd ..
|
||||
git tag desktop-v0.4.0-alpha.2
|
||||
git push origin desktop-v0.4.0-alpha.2
|
||||
# This is a prerelease: run "Hermes-Relay Plugin and CLI+UI Release Approval"
|
||||
# from main, select desktop, and enter 0.4.0-alpha.2. The workflow validates dev
|
||||
# before it creates the tag and starts the immutable-tag release workflow.
|
||||
```
|
||||
|
||||
The tag workflow rejects version drift and tags whose commit is not in
|
||||
`origin/main`, reruns CLI tests, builds all four standalone binaries, tests and
|
||||
packages the Windows tray, generates checksums, and publishes the GitHub Release.
|
||||
For a stable CLI+UI version, first merge the release PR from `dev` to `main`,
|
||||
then run the approval workflow from `main`. The version determines the source:
|
||||
prereleases select the exact `origin/dev` tip and stable releases select the
|
||||
exact `origin/main` tip before creating any tag. Direct `desktop-v*` tag pushes
|
||||
remain a recovery path.
|
||||
|
||||
The release workflow rejects version drift and requires prerelease tags to be
|
||||
contained in `origin/dev` and stable tags to be contained in `origin/main`. It
|
||||
reruns CLI tests, builds all four standalone binaries, tests and packages the
|
||||
Windows tray, generates checksums, and publishes the GitHub Release.
|
||||
Trusted desktop CI and the release installer job share a Cargo/target cache
|
||||
keyed by the lockfile and exact tray sources. A `main` push for the release tree
|
||||
warms the exact cache before the immutable tag build; a miss safely performs the
|
||||
ordinary Rust/Tauri build.
|
||||
|
||||
### 6. Play review and publishing behavior
|
||||
|
||||
@@ -836,7 +924,7 @@ gradlew promoteReleaseArtifact --from-track=internal --promote-track=production
|
||||
(This step was only needed as a retrofit for v0.1.0 — v0.1.1+ inherit
|
||||
the Download section automatically from `RELEASE_NOTES.md`.)
|
||||
- Confirm Play Console shows the new versionCode on the target track.
|
||||
- Update `DEVLOG.md` with a short entry for the release.
|
||||
- Update `docs/project/DEVLOG.md` with a short entry for the release.
|
||||
|
||||
## CI Behavior
|
||||
|
||||
@@ -844,28 +932,40 @@ Android, Plugin, dashboard, and desktop now have separate CI/release lanes.
|
||||
This keeps a dashboard CSS fix from running the full server suite, and keeps
|
||||
plugin changes from forcing an Android app `versionCode` bump.
|
||||
|
||||
Every successful `Required checks` run records a short-lived proof keyed to the
|
||||
checked Git tree. For the canonical `dev` → `main` release PR, CI first proves
|
||||
the simulated merge tree is identical to the `dev` tree. If an unexpired proof
|
||||
from a successful Required-checks run exists, the PR verifies and reuses it;
|
||||
otherwise it automatically falls back to the normal path-aware matrix. Content
|
||||
changes can never reuse an older proof because they change the tree hash.
|
||||
|
||||
On every push of a tag matching `android-v*`, `.github/workflows/release-android.yml`:
|
||||
|
||||
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. For stable releases, builds all four flavored release artifacts
|
||||
(`./gradlew bundleRelease assembleRelease`); only the sideload APK and
|
||||
googlePlay AAB are attached. For prereleases, builds only the side-by-side
|
||||
`sideloadCandidate` APK.
|
||||
5. Generates `SHA256SUMS.txt` covering the two attached files.
|
||||
6. For stable releases only, promotes the exact preflighted Production draft to
|
||||
2. For stable releases, verifies and downloads the exact immutable Play
|
||||
preflight artifact; prereleases run the focused CI slice and build the
|
||||
side-by-side `sideloadCandidate` APK.
|
||||
3. Revalidates stable artifact hashes, DEX collection compatibility, packaged
|
||||
native compatibility, and retained R8 mappings without recompiling.
|
||||
4. Generates candidate checksums when applicable; stable checksums come from
|
||||
the verified preflight artifact and cover the two public files.
|
||||
5. 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
|
||||
6. 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.
|
||||
8. Prints a `$GITHUB_STEP_SUMMARY` with the release and Play result.
|
||||
7. Prints a `$GITHUB_STEP_SUMMARY` with the release and Play result.
|
||||
|
||||
On every push of a tag matching `server-v*`,
|
||||
For an approved multi-surface train, run **Hermes-Relay Coordinated Release
|
||||
Approval** from `main`, select the affected surfaces, and enter their prepared
|
||||
versions. It dispatches Android, Plugin, and CLI+UI approval jobs concurrently;
|
||||
each surface keeps its independent source, validation, tag, artifact, and
|
||||
publication workflow.
|
||||
|
||||
On every direct push of a tag matching `server-v*`, or after an approved
|
||||
dispatch from `.github/workflows/approve-release-extensions.yml`,
|
||||
`.github/workflows/release-plugin.yml`:
|
||||
|
||||
1. Verifies a stable tag commit is contained in `main`, or a prerelease tag is
|
||||
@@ -878,7 +978,8 @@ On every push of a tag matching `server-v*`,
|
||||
5. Creates a GitHub Release named `Hermes-Relay Plugin v<version>` with the wheel,
|
||||
sdist, and checksum file attached.
|
||||
|
||||
On every push of a tag matching `desktop-v*`,
|
||||
On every direct push of a tag matching `desktop-v*`, or after an approved
|
||||
dispatch from `.github/workflows/approve-release-extensions.yml`,
|
||||
`.github/workflows/release-cli.yml` builds and publishes the CLI binaries and
|
||||
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
|
||||
@@ -922,8 +1023,23 @@ When production has a bug, use the same invariant for every surface:
|
||||
4. Open the focused hotfix PR into `main` and merge with a merge commit/no-ff.
|
||||
5. Tag the new `main` tip with the affected surface's patch tag.
|
||||
6. Verify the artifacts and production rollout or deployment.
|
||||
7. Merge `main` back into `dev` immediately so integration inherits the fix and
|
||||
version history.
|
||||
7. Let the stable release workflow dispatch `Release Backmerge`. A
|
||||
conflict-free candidate runs the same path-aware `Required checks` against
|
||||
its exact SHA, then compare-and-swaps `dev` only if the base ref is unchanged.
|
||||
Conflicts, failed checks, stale refs, or a denied update require a normal
|
||||
reconciliation PR.
|
||||
|
||||
`Release Backmerge` accepts only published stable `android-v*`, `server-v*`, or
|
||||
`desktop-v*` SemVer tags contained in `main`. It exits without mutation for a
|
||||
normal release whose integration parent is already in `dev`. For a selective
|
||||
hotfix, it pushes a temporary merge ref, dispatches `Required checks` with full
|
||||
base/head SHAs, and updates `dev` with an explicit force-with-lease only after
|
||||
that exact candidate passes. The lease is a compare-and-swap guard, not
|
||||
permission to rewrite history: the candidate's first parent must be the
|
||||
unchanged `dev` tip and its second parent the released commit. The repository
|
||||
ruleset must allow this workflow's automation identity to perform that one
|
||||
checked branch update; if it does not, the workflow fails closed and the
|
||||
reconciliation uses a PR.
|
||||
|
||||
For an Android app hotfix:
|
||||
|
||||
@@ -938,21 +1054,21 @@ For an Android app hotfix:
|
||||
6. `git tag android-v0.6.2` from the new `main` tip and `git push origin android-v0.6.2`
|
||||
so Android release CI builds and publishes.
|
||||
7. Verify the automated Play submission, GitHub artifacts, and rollout.
|
||||
8. Merge `main` back into `dev` (`git checkout dev && git merge --no-ff main`)
|
||||
so `dev` picks up the hotfix and the versionCode bump. Without this,
|
||||
`dev`'s `appVersionCode` lags behind `main` and the next app release
|
||||
bump collides.
|
||||
8. Verify the automated release backmerge completed. If it stopped, open a
|
||||
reconciliation PR so `dev` picks up the hotfix and versionCode bump. Without
|
||||
reconciliation, `dev`'s `appVersionCode` lags behind `main` and the next app
|
||||
release bump collides.
|
||||
|
||||
For a Plugin hotfix, branch from the affected `server-v*` tag, apply
|
||||
the fix, run `bash scripts/bump-plugin-version.sh <next-version>`, merge to
|
||||
`main`, tag `server-v<next-version>`, verify the package/deployment, and merge
|
||||
`main` back to `dev`. Do not touch
|
||||
`main`, tag `server-v<next-version>`, verify the package/deployment, and verify
|
||||
the automated release backmerge. Do not touch
|
||||
`gradle/libs.versions.toml` unless an Android app release is also shipping.
|
||||
|
||||
For a CLI+UI hotfix, branch from the affected `desktop-v*` tag, update only
|
||||
`desktop/package.json` and its generated lock/runtime/tray metadata, merge to
|
||||
`main`, tag `desktop-v<next-version>`, verify all binaries and the installer,
|
||||
then merge `main` back to `dev`.
|
||||
then verify the automated release backmerge or use the PR fallback.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.12.1
|
||||
# Hermes-Relay Android v1.17.0
|
||||
|
||||
**Release Date:** August 22, 2026
|
||||
**Release Date:** September 13, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.12.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.17.0-sideload-release.apk` and tap it for the full feature set, or install 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,18 +12,28 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This patch makes Android sharing and recovery dependable. Shared links, text, images, and files open as complete reviewable drafts; connection renewal no longer stalls; offline and history failures are visible; and secure-storage recovery appears in Diagnostics.
|
||||
Google Play gains optional voice controls over other apps. This release also makes Clarify batches, profile identity, and chat context easier to follow while preserving confirmed answers and saved conversations.
|
||||
|
||||
## Added
|
||||
|
||||
- Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Permission grants require a separate Start action. Stop voice from the overlay or persistent notification; screen lock, task removal, and permission loss end the session.
|
||||
|
||||
## Changed
|
||||
|
||||
- Standalone response cards use one surface, assistant bubbles are subtler, and timestamps share a row with delivery status.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Open shared links, text, images, files, and mixed or multi-item shares as a fresh reviewable draft without sending automatically.
|
||||
- Keep Add and Renew connection setup on the correct connection-scoped authentication store, with bounded Retry or Cancel recovery instead of an indefinite preparation screen.
|
||||
- Surface unavailable chat routes and profile-history failures clearly instead of silently dropping Send or presenting missing history as an empty conversation.
|
||||
- Report Android Keystore fallback, encrypted-store recovery, and temporary credential storage in Diagnostics without exposing credentials.
|
||||
- Answer upstream Clarify batches one question at a time, with independent choices, custom answers, and confirmed progress across reconnects. (#474)
|
||||
- Context previews show that Gateway chats cannot send phone status or general turn context. Automatic phone-status sharing remains supported for API-only chats. (#556)
|
||||
- Profiles display their Hermes names and group the resolved server default under its agent identity, preserving explicit selection and saved conversations.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.12.1** (versionCode **48**).
|
||||
- Standard Chat, sessions, Manage, sharing, profile switching, 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, sharing, session continuity, or Gateway recovery.
|
||||
- App version: **1.17.0** (versionCode **57**).
|
||||
- Standard Chat, sessions, profiles, Manage, voice, and ordinary media use current upstream Hermes. Speech-to-text still requires a configured provider on the host.
|
||||
- Hermes-Relay Plugin **1.11.3** is the optional release for Hermes-Relay tools and current Dashboard WebSocket compatibility.
|
||||
- Explicit Direct API/API-only connections remain supported and are not used as silent failover for Dashboard-owned chats.
|
||||
- Voice Overlay is available in Google Play and sideload builds. Device Control remains sideload-only.
|
||||
- Gateway phone-status delivery and automatic Android identification remain unavailable pending upstream support.
|
||||
- Physical Android 14-16 and OEM voice-overlay testing was not performed for this release. Code, rendered UI, existing emulator evidence, CI, and signed-package preflight provide the recorded verification.
|
||||
|
||||
@@ -100,9 +100,9 @@ android {
|
||||
}
|
||||
|
||||
// ─── Bridge release tracks ─────────────────────────────────────────────────
|
||||
// Google Play ships Bridge Core only: pairing, chat, voice, terminal/TUI,
|
||||
// Google Play ships Bridge Core and user-started voice-only overlay: pairing, chat, voice, terminal/TUI,
|
||||
// media, notification companion, relay sessions, and status. It does not
|
||||
// declare AccessibilityService, overlay, MediaProjection, wake-lock device
|
||||
// declare AccessibilityService, MediaProjection, wake-lock device
|
||||
// control, SMS/call/contact/location, or unattended-control permissions.
|
||||
//
|
||||
// googlePlay — canonical Play Store install. Bridge Core only.
|
||||
@@ -249,6 +249,58 @@ android {
|
||||
it.systemProperty("roborazzi.test.record", "true")
|
||||
it.maxHeapSize = "2g"
|
||||
}
|
||||
|
||||
// On-demand only. Keep each form factor as an individually selected
|
||||
// Gradle-managed device; there is deliberately no aggregate matrix
|
||||
// task or scheduled emulator job. See docs/android-emulator-testing.md.
|
||||
managedDevices {
|
||||
localDevices {
|
||||
create("compactPhoneApi36") {
|
||||
device = "Pixel 2"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("standardPhoneApi36") {
|
||||
device = "Pixel 6"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("largePhoneApi36") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("foldableApi36") {
|
||||
device = "Pixel Fold"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("tabletApi36") {
|
||||
device = "Pixel Tablet"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("futureApi37Ps16k") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 37
|
||||
systemImageSource = "google_apis_playstore"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
pageAlignment =
|
||||
com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,8 +367,9 @@ dependencies {
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.okhttp.sse)
|
||||
|
||||
// Media3 ExoPlayer — gapless TTS queue playback (replaces MediaPlayer in VoicePlayer)
|
||||
// Media3 ExoPlayer + lifecycle-aware Compose video surface.
|
||||
implementation(libs.media3.exoplayer)
|
||||
implementation(libs.media3.ui.compose)
|
||||
|
||||
// android-vad Silero — on-device VAD for barge-in (B2)
|
||||
// Bundled ONNX Silero model (~2.2 MB); pulled from JitPack.
|
||||
@@ -390,6 +443,12 @@ dependencies {
|
||||
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
|
||||
testImplementation(libs.konsist)
|
||||
androidTestImplementation(libs.compose.ui.test.junit4)
|
||||
// Compose UI Test still declares Espresso 3.5.0 transitively. API 37
|
||||
// removed the reflected InputManager.getInstance() seam; Espresso 3.7.0
|
||||
// uses Context.getSystemService and is the current stable AndroidX line.
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
androidTestImplementation("androidx.test:runner:1.7.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
// On-device vanilla-Gateway contract tests exercise the production
|
||||
// Dashboard ticket + WebSocket stack over real loopback sockets.
|
||||
androidTestImplementation(libs.okhttp.mockwebserver)
|
||||
@@ -399,8 +458,8 @@ dependencies {
|
||||
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
|
||||
// Renders real composables on the JVM at an exact canvas — no device, no
|
||||
// status bar, no clipping. See StoreScreenshotTest.
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.72.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.72.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.74.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.74.0")
|
||||
testImplementation(libs.compose.ui.test.junit4)
|
||||
testImplementation(libs.compose.ui.test.manifest)
|
||||
testImplementation("androidx.test.ext:junit:1.3.0")
|
||||
|
||||
@@ -55,6 +55,9 @@
|
||||
-keep class androidx.camera.** { *; }
|
||||
-dontwarn androidx.camera.**
|
||||
|
||||
# sherpa-onnx JNI resolves Kotlin configuration classes and fields by name.
|
||||
-keep class com.k2fsa.sherpa.onnx.** { *; }
|
||||
|
||||
# ── General ──────────────────────────────────────────────────────────
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.ApiEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Protocol
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.InterruptedIOException
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EndpointResolverConcurrencyInstrumentedTest {
|
||||
|
||||
@Test
|
||||
fun probeCompletionRacingInvalidation_staysCrashFreeOnAndroidCollections() = runBlocking {
|
||||
repeat(25) { iteration ->
|
||||
val candidateCount = 8
|
||||
val requestsStarted = CountDownLatch(candidateCount)
|
||||
val releaseRequests = CountDownLatch(1)
|
||||
val raceGate = CountDownLatch(1)
|
||||
val requestSequence = AtomicInteger(0)
|
||||
val client = OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
if (requestSequence.incrementAndGet() <= candidateCount) {
|
||||
requestsStarted.countDown()
|
||||
releaseRequests.await(5, TimeUnit.SECONDS)
|
||||
throw InterruptedIOException("instrumented invalidation race")
|
||||
}
|
||||
Response.Builder()
|
||||
.request(chain.request())
|
||||
.protocol(Protocol.HTTP_1_1)
|
||||
.code(200)
|
||||
.message("OK")
|
||||
.body("{}".toResponseBody())
|
||||
.build()
|
||||
}
|
||||
.build()
|
||||
val resolver = EndpointResolver(client)
|
||||
val candidates = (1..candidateCount).map { index ->
|
||||
EndpointCandidate(
|
||||
role = "instrumented-$iteration-$index",
|
||||
priority = 0,
|
||||
api = ApiEndpoint(host = "127.0.0.1", port = 1, tls = false),
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
val staleResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(candidates, EndpointSurface.Api)
|
||||
}
|
||||
assertTrue(requestsStarted.await(5, TimeUnit.SECONDS))
|
||||
|
||||
val invalidation = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
resolver.clearCache()
|
||||
}
|
||||
val completions = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
releaseRequests.countDown()
|
||||
}
|
||||
raceGate.countDown()
|
||||
|
||||
withTimeout(2_000L) {
|
||||
invalidation.await()
|
||||
completions.await()
|
||||
staleResolve.await()
|
||||
}
|
||||
assertTrue(resolver.cacheSnapshot().isEmpty())
|
||||
|
||||
resolver.clearCache()
|
||||
val freshWinner = withTimeout(2_000L) {
|
||||
resolver.resolve(listOf(candidates.first()), EndpointSurface.Api)
|
||||
}
|
||||
assertEquals(candidates.first(), freshWinner)
|
||||
assertTrue(
|
||||
resolver.probeOutcomes.value.getValue(
|
||||
EndpointResolver.cacheKey(candidates.first(), EndpointSurface.Api),
|
||||
).reachable,
|
||||
)
|
||||
} finally {
|
||||
raceGate.countDown()
|
||||
releaseRequests.countDown()
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.data.setGatewayKeepAlive
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Real ActivityManager/notification lifecycle; no Gateway or personal data. */
|
||||
class GatewayKeepAliveServiceInstrumentedTest {
|
||||
@get:Rule val activity = createAndroidComposeRule<ComponentActivity>()
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
private val context get() = instrumentation.targetContext
|
||||
|
||||
@Before fun setup() {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
instrumentation.uiAutomation.executeShellCommand(
|
||||
"pm grant ${context.packageName} android.permission.POST_NOTIFICATIONS",
|
||||
).close()
|
||||
}
|
||||
runBlocking { context.setGatewayKeepAlive(false) }
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.stop(context)
|
||||
ActiveTurnKeepAliveRegistry.releaseAll()
|
||||
}
|
||||
await("service shutdown") { serviceState() == null }
|
||||
runBlocking { context.setGatewayKeepAlive(false) }
|
||||
}
|
||||
|
||||
@Test fun immediateStopsAndOverlappingStartsSurviveThePlatformWatchdog() {
|
||||
// All changes happen before Android can dispatch onCreate/onStartCommand.
|
||||
instrumentation.runOnMainSync {
|
||||
repeat(25) {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
GatewayKeepAliveService.stop(context)
|
||||
}
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2, 1))
|
||||
}
|
||||
await("foreground promotion") { serviceState()?.foreground == true }
|
||||
instrumentation.runOnMainSync { GatewayKeepAliveService.stop(context) }
|
||||
await("settled shutdown") { serviceState() == null }
|
||||
// Observation window, not a startup workaround: an asynchronous system
|
||||
// foreground-start crash fails the instrumentation process during it.
|
||||
CountDownLatch(1).await(12, TimeUnit.SECONDS)
|
||||
assertTrue(serviceState() == null)
|
||||
}
|
||||
|
||||
@Test fun notificationDisablesAlwaysOnWhileANewerTurnStaysProtected() {
|
||||
runBlocking { context.setGatewayKeepAlive(true) }
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
}
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
await("persistent notification") {
|
||||
manager.activeNotifications.any { it.id == GatewayKeepAliveService.NOTIFICATION_ID }
|
||||
}
|
||||
val action = manager.activeNotifications.single {
|
||||
it.id == GatewayKeepAliveService.NOTIFICATION_ID
|
||||
}.notification.actions.single().actionIntent
|
||||
instrumentation.runOnMainSync {
|
||||
ActiveTurnKeepAliveRegistry.acquire("fixture::profile-a::session")
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
}
|
||||
action.send()
|
||||
await("persisted notification action") {
|
||||
runBlocking { context.relayDataStore.data.first()[KEY_GATEWAY_KEEP_ALIVE] == false }
|
||||
}
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
}
|
||||
assertTrue(serviceState()?.foreground == true)
|
||||
assertTrue(ActiveTurnKeepAliveRegistry.snapshot.value.required)
|
||||
await("active-turn notification without always-on action") {
|
||||
manager.activeNotifications.singleOrNull {
|
||||
it.id == GatewayKeepAliveService.NOTIFICATION_ID
|
||||
}?.notification?.let { it.actions.isNullOrEmpty() } == true
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun serviceState(): ActivityManager.RunningServiceInfo? =
|
||||
context.getSystemService(ActivityManager::class.java).getRunningServices(100)
|
||||
.singleOrNull { it.service.className == GatewayKeepAliveService::class.java.name }
|
||||
|
||||
private fun await(description: String, condition: () -> Boolean) {
|
||||
val deadline = SystemClock.uptimeMillis() + 10_000
|
||||
while (!condition() && SystemClock.uptimeMillis() < deadline) {
|
||||
instrumentation.waitForIdleSync()
|
||||
SystemClock.sleep(20)
|
||||
}
|
||||
assertTrue(description, condition())
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
@@ -28,50 +27,6 @@ class AmbientVisualizationVisibilityTest {
|
||||
@get:Rule
|
||||
val composeTestRule = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun cleanMode_backgroundOff_hidesSphereAndKeepsComposer() {
|
||||
composeTestRule.setContent {
|
||||
AmbientTestProviders(enabled = false) {
|
||||
CleanChatMode(
|
||||
messages = emptyList(),
|
||||
isStreaming = false,
|
||||
sphereState = SphereState.Idle,
|
||||
streamingIntensity = 0f,
|
||||
toolCallBurst = 0f,
|
||||
animationEnabled = true,
|
||||
enabled = true,
|
||||
onSend = {},
|
||||
onExit = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertDoesNotExist()
|
||||
composeTestRule.onNodeWithContentDescription(targetString(R.string.agent_text_send_cd))
|
||||
.assertExists()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cleanMode_backgroundOn_rendersSphere() {
|
||||
composeTestRule.setContent {
|
||||
AmbientTestProviders(enabled = true) {
|
||||
CleanChatMode(
|
||||
messages = emptyList(),
|
||||
isStreaming = false,
|
||||
sphereState = SphereState.Idle,
|
||||
streamingIntensity = 0f,
|
||||
toolCallBurst = 0f,
|
||||
animationEnabled = false,
|
||||
enabled = true,
|
||||
onSend = {},
|
||||
onExit = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composeTestRule.onNodeWithTag(AMBIENT_RENDERER_TAG).assertExists()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun voiceMode_backgroundOff_hidesSphereAndKeepsVoiceUi() {
|
||||
composeTestRule.setContent {
|
||||
|
||||
@@ -3,224 +3,97 @@ package com.hermesandroid.relay.ui.onboarding
|
||||
import android.app.Application
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import androidx.compose.ui.test.performTextReplacement
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Instrumented tests for the Standard-first onboarding pager.
|
||||
*/
|
||||
/** Standard setup stays separate from Direct API and optional Relay grants. */
|
||||
class OnboardingFlowTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@get:Rule
|
||||
val composeTestRule = createComposeRule()
|
||||
|
||||
private fun setOnboardingContent() {
|
||||
val app = ApplicationProvider.getApplicationContext<Application>()
|
||||
val connectionViewModel = ConnectionViewModel(app)
|
||||
composeTestRule.setContent {
|
||||
HermesRelayTheme {
|
||||
OnboardingScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onComplete = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
private fun start() {
|
||||
val model = ConnectionViewModel(ApplicationProvider.getApplicationContext<Application>())
|
||||
compose.setContent { HermesRelayTheme { OnboardingScreen(model, onComplete = {}) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstPage_showsHermesForAndroidTitle() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes-Relay for Android")
|
||||
.assertIsDisplayed()
|
||||
private fun connectPage() {
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
repeat(3) { compose.onNodeWithText("Next").performClick(); compose.waitForIdle() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstPage_showsStandardFirstDescription() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Chat with Hermes and manage your dashboard from your phone.")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Standard")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Advanced")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Setup Guide")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes Docs")
|
||||
.assertIsDisplayed()
|
||||
@Test fun welcomeOffersStartAndDemo() {
|
||||
start()
|
||||
compose.onNodeWithText("Hermes,\nin your pocket").assertIsDisplayed()
|
||||
compose.onNodeWithText("Get started").assertIsDisplayed().assertIsEnabled()
|
||||
compose.onNodeWithText("Try the demo").assertIsDisplayed().assertIsEnabled()
|
||||
compose.onNodeWithText("Back").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nextButton_navigatesForward_toChatPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Chat")
|
||||
.assertIsDisplayed()
|
||||
@Test fun introNavigationAndSkipRemainAvailable() {
|
||||
start()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
compose.onNodeWithText("Chat").assertIsDisplayed()
|
||||
compose.onNodeWithText("Back").performClick()
|
||||
compose.onNodeWithText("Get started").assertIsDisplayed()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
compose.onNodeWithText("Skip").performClick()
|
||||
compose.onNodeWithText("Skip setup?").assertIsDisplayed()
|
||||
compose.onNodeWithText("Go back").performClick()
|
||||
compose.onNodeWithText("Chat").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canNavigateForward_throughStandardAndPowerPages() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Hermes-Relay for Android").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Chat").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Manage").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Power tools").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Connect").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Connect to Hermes").assertIsDisplayed()
|
||||
@Test fun standardMethodsDoNotAskForApiCredentials() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Hermes nearby").assertIsDisplayed()
|
||||
compose.onNodeWithText("Remote gateway").assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Hermes address").assertIsDisplayed()
|
||||
compose.onNodeWithText("API key").assertDoesNotExist()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backButton_hiddenOnFirstPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Back")
|
||||
.assertDoesNotExist()
|
||||
@Test fun publicHttpConsentResetsWhenAddressChanges() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Remote gateway").performClick()
|
||||
compose.onNodeWithText("Hermes address").performTextReplacement("http://11.0.0.1:9119")
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
compose.onNodeWithText("I accept the risk and allow HTTP for this address").performScrollTo().performClick()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsEnabled()
|
||||
compose.onNodeWithText("Hermes address").performScrollTo().performTextReplacement("http://11.0.0.1:9120")
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backButton_navigatesBackward() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
composeTestRule.onNodeWithText("Chat").assertIsDisplayed()
|
||||
|
||||
composeTestRule.onNodeWithText("Back").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
composeTestRule.onNodeWithText("Hermes-Relay for Android").assertIsDisplayed()
|
||||
@Test fun advancedKeepsApiAndRelaySeparate() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Advanced").performScrollTo().performClick()
|
||||
compose.onNodeWithText("API-only connection").assertIsDisplayed()
|
||||
compose.onNodeWithText("Pair Relay by code").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectPage_recommendsGeneralSetupQr() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Scan Hermes setup QR")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Recommended")
|
||||
.assertIsDisplayed()
|
||||
@Test fun setupSkipIsScrollReachable() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Skip for now — set up later in Settings").performScrollTo().assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Skip setup?").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualSetup_showsHermesAddressWithoutApiCredentials() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Server or VPS").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes address")
|
||||
.assertIsDisplayed()
|
||||
@Test fun hostedGatewayKeepsItsSeparateAddressEntry() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Nous-hosted Hermes").performClick()
|
||||
compose.onNodeWithText("Connect to Nous-hosted Hermes").assertIsDisplayed()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualSetup_findButton_isShown() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Server or VPS").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Find Hermes")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cloudSetup_requestsTheHostedDashboardAddress() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Nous-hosted Hermes").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Connect to Nous-hosted Hermes")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Use the complete HTTPS address shown for your hosted agent.")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectPage_keepsPairingOptional() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Advanced").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Pair Relay by code")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Power-user path for Terminal, Bridge, Relay sessions, and grants")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun powerPage_linksToPermissionReview() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(3)
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Review permissions")
|
||||
.assertIsDisplayed()
|
||||
.assertIsEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipButton_visibleOnIntroPages_andWizardSkipOnConnectPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
repeat(4) {
|
||||
composeTestRule.onNodeWithText("Skip").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText(if (it == 3) "Connect" else "Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
}
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Skip for now — set up later in Settings")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
private fun navigateToPage(pageIndex: Int) {
|
||||
repeat(pageIndex) {
|
||||
composeTestRule.onNodeWithText(if (it == 3) "Connect" else "Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
}
|
||||
@Test fun optionalPowerPermissionsRemainReachable() {
|
||||
start()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
repeat(2) { compose.onNodeWithText("Next").performClick(); compose.waitForIdle() }
|
||||
compose.onNodeWithText("Review permissions").performScrollTo().assertIsDisplayed().assertIsEnabled()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.hermesandroid.relay.data.BotGatewayRoute
|
||||
import com.hermesandroid.relay.data.BotGatewayRouteKey
|
||||
import com.hermesandroid.relay.data.BotRosterEntry
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.viewmodel.AndroidGatewayContractFixture
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import okhttp3.OkHttpClient
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/** On-device proof for the route-owned first-composition collection boundary. */
|
||||
class BotChatScreenBindingInstrumentedTest {
|
||||
private lateinit var fixture: AndroidGatewayContractFixture
|
||||
private lateinit var gatewayScope: CoroutineScope
|
||||
private lateinit var dashboardClient: DashboardApiClient
|
||||
private lateinit var gatewayClient: GatewayChatClient
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var handler: ChatHandler
|
||||
private var activityScenario: ActivityScenario<BotChatBindingTestActivity>? = null
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
dashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
)
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = dashboardClient,
|
||||
okHttpClient = OkHttpClient(),
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
viewModel = ChatViewModel()
|
||||
handler = ChatHandler()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
activityScenario?.close()
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
dashboardClient.shutdown()
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fastInitialHistoryRendersBeforeNavigationAndSurvivesLifecycleResume() {
|
||||
val route = BotGatewayRoute(
|
||||
key = BotGatewayRouteKey("fixture-gateway", PROFILE_NAME),
|
||||
connectionLabel = "Fixture gateway",
|
||||
)
|
||||
val bot = BotRosterEntry(
|
||||
profile = Profile(
|
||||
name = PROFILE_NAME,
|
||||
model = "fixture-model",
|
||||
description = "Fixture profile",
|
||||
),
|
||||
displayName = "Research",
|
||||
route = route,
|
||||
)
|
||||
val scenario = ActivityScenario.launch(BotChatBindingTestActivity::class.java)
|
||||
.also { activityScenario = it }
|
||||
|
||||
scenario.onActivity { activity ->
|
||||
activity.setContent {
|
||||
MaterialTheme {
|
||||
BotChatScreen(
|
||||
route = route,
|
||||
bot = bot,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
gatewayClient = gatewayClient,
|
||||
dashboardClient = dashboardClient,
|
||||
chatViewModel = viewModel,
|
||||
onBack = {},
|
||||
handlerFactory = { handler },
|
||||
historyLoader = { _, _, _ ->
|
||||
Result.success(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = HISTORY_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(HISTORY_TEXT),
|
||||
timestamp = 1.0,
|
||||
finishReason = "stop",
|
||||
),
|
||||
),
|
||||
)
|
||||
},
|
||||
profileIconFlow = { _, _ -> MutableStateFlow(null) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
waitUntil { handler.messages.value.singleOrNull()?.content == HISTORY_TEXT }
|
||||
waitUntil { renderedTextExists(HISTORY_TEXT) }
|
||||
|
||||
scenario.moveToState(Lifecycle.State.STARTED)
|
||||
scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
waitUntil { renderedTextExists(HISTORY_TEXT) }
|
||||
assertEquals(0, fixture.rpcCount("prompt.submit"))
|
||||
}
|
||||
|
||||
private fun renderedTextExists(expected: String): Boolean {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
instrumentation.waitForIdleSync()
|
||||
val root = instrumentation.uiAutomation.rootInActiveWindow ?: return false
|
||||
return root.containsText(expected)
|
||||
}
|
||||
|
||||
private fun AccessibilityNodeInfo.containsText(expected: String): Boolean {
|
||||
if (text?.toString() == expected || contentDescription?.toString() == expected) return true
|
||||
return (0 until childCount).any { index -> getChild(index)?.containsText(expected) == true }
|
||||
}
|
||||
|
||||
private fun waitUntil(condition: () -> Boolean) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (condition()) return
|
||||
Thread.sleep(25)
|
||||
}
|
||||
assertTrue("Condition was not satisfied within 5 seconds", condition())
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PROFILE_NAME = "research"
|
||||
const val STORED_SESSION_ID = "20260829_120000_bot_chat"
|
||||
const val HISTORY_ID = "persisted-bot-history"
|
||||
const val HISTORY_TEXT = "Durable Bot Chat history is ready."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.longClick
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||
import com.hermesandroid.relay.ui.components.ChatDebugDrawer
|
||||
import com.hermesandroid.relay.ui.components.ChatDebugOverlay
|
||||
import com.hermesandroid.relay.ui.components.chatDebugHeaderGesture
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class ChatDebugDrawerInstrumentedTest {
|
||||
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
|
||||
@Test
|
||||
fun longPressOpensDiagnosticsBelowHeaderAndCloseRestoresChat() {
|
||||
compose.setContent {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
Text("Hermes", Modifier.fillMaxWidth().height(64.dp).testTag("header")
|
||||
.chatDebugHeaderGesture(true, onClick = {}, onHold = { open = true }))
|
||||
ChatDebugOverlay(open, 64.dp, onClose = { open = false }) {
|
||||
ChatDebugDrawer(
|
||||
profile = "Server Default", model = "Example", sessionId = "session",
|
||||
gateway = true, signedIn = true, signInRequired = false,
|
||||
socketState = GatewayConnectionState.Ready, preparing = false,
|
||||
streaming = false, loadingHistory = false, directoryUnavailable = false,
|
||||
failure = null, onClose = { open = false }, onConnections = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val header = compose.onNodeWithTag("header")
|
||||
val before = header.fetchSemanticsNode().boundsInRoot
|
||||
header.performTouchInput { longClick() }
|
||||
compose.onNodeWithText("Session diagnostics").assertIsDisplayed()
|
||||
assertEquals(before, header.fetchSemanticsNode().boundsInRoot)
|
||||
compose.onNodeWithContentDescription("Close session diagnostics").performClick()
|
||||
compose.onNodeWithText("Session diagnostics").assertDoesNotExist()
|
||||
header.assertIsDisplayed()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import android.app.UiModeManager
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.hermesandroid.relay.HermesRelayApp
|
||||
import com.hermesandroid.relay.MainActivity
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.runtime.HermesRuntimeInitializationState
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/** Real Activity/DataStore/Compose ownership, with the device set to dark mode. */
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class AppearanceColdStartInstrumentedTest {
|
||||
@Test
|
||||
fun savedAppearanceOwnsColdStartAndLaterModeChanges() {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
val app = ApplicationProvider.getApplicationContext<HermesRelayApp>()
|
||||
val previousPreferences = runBlocking { app.relayDataStore.data.first() }
|
||||
val originalNightMode =
|
||||
(app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager).nightMode
|
||||
assumeTrue(
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_AUTO ||
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_NO ||
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_YES,
|
||||
)
|
||||
val custom = CustomThemePreset(
|
||||
id = "day",
|
||||
name = "Day",
|
||||
mode = CustomThemePreset.MODE_LIGHT,
|
||||
backgroundHex = "#F5F5F5",
|
||||
surfaceHex = "#FFFFFF",
|
||||
accentHex = "#0E18D6",
|
||||
textHex = "#111111",
|
||||
)
|
||||
instrumentation.uiAutomation.executeShellCommand("cmd uimode night yes").close()
|
||||
try {
|
||||
runBlocking {
|
||||
app.relayDataStore.edit { preferences ->
|
||||
preferences[AppearancePreferences.themeKey] = "light"
|
||||
preferences[AppearancePreferences.appThemeKey] = AppThemes.DEFAULT_ID
|
||||
}
|
||||
}
|
||||
instrumentation.runOnMainSync {
|
||||
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
|
||||
}
|
||||
ActivityScenario.launch(MainActivity::class.java).use {
|
||||
runBlocking {
|
||||
withTimeout(30_000) {
|
||||
app.runtime.connectionViewModel.isReady.first { it }
|
||||
app.runtime.initializationState.first {
|
||||
it == HermesRuntimeInitializationState.Ready
|
||||
}
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = false, nightMode = AppCompatDelegate.MODE_NIGHT_NO)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.themeKey] = "dark"
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = true, nightMode = AppCompatDelegate.MODE_NIGHT_YES)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.themeKey] = "auto"
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = true, nightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.customThemesKey] =
|
||||
AppearancePreferences.encodeCustomThemes(listOf(custom))
|
||||
it[AppearancePreferences.appThemeKey] = custom.appThemeId
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = false, nightMode = AppCompatDelegate.MODE_NIGHT_NO)
|
||||
}
|
||||
} finally {
|
||||
runBlocking {
|
||||
app.relayDataStore.edit { preferences ->
|
||||
previousPreferences[AppearancePreferences.themeKey]?.let {
|
||||
preferences[AppearancePreferences.themeKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.themeKey)
|
||||
previousPreferences[AppearancePreferences.appThemeKey]?.let {
|
||||
preferences[AppearancePreferences.appThemeKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.appThemeKey)
|
||||
previousPreferences[AppearancePreferences.customThemesKey]?.let {
|
||||
preferences[AppearancePreferences.customThemesKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.customThemesKey)
|
||||
}
|
||||
}
|
||||
val restoreMode = when (originalNightMode) {
|
||||
UiModeManager.MODE_NIGHT_YES -> "yes"
|
||||
UiModeManager.MODE_NIGHT_NO -> "no"
|
||||
else -> "auto"
|
||||
}
|
||||
instrumentation.uiAutomation.executeShellCommand("cmd uimode night $restoreMode").close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun awaitTheme(isDark: Boolean, nightMode: Int) {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
val deadline = SystemClock.uptimeMillis() + 15_000
|
||||
while (SystemClock.uptimeMillis() < deadline) {
|
||||
instrumentation.waitForIdleSync()
|
||||
if (RelayRefresh.activePalette.isDark == isDark &&
|
||||
AppCompatDelegate.getDefaultNightMode() == nightMode
|
||||
) {
|
||||
assertEquals(nightMode, AppCompatDelegate.getDefaultNightMode())
|
||||
if (isDark) assertTrue(RelayRefresh.activePalette.isDark)
|
||||
else assertFalse(RelayRefresh.activePalette.isDark)
|
||||
return
|
||||
}
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
fail(
|
||||
"Appearance did not settle: paletteDark=${RelayRefresh.activePalette.isDark}, " +
|
||||
"nightMode=${AppCompatDelegate.getDefaultNightMode()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.ChatActivityPhase
|
||||
import com.hermesandroid.relay.data.InMemoryChatActivityStore
|
||||
import com.hermesandroid.relay.data.projectChatActivityReceipts
|
||||
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.ui.components.ChatActivityReceipt
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessSheet
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.WebSocket
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
/** Real Gateway callbacks drive production activity surfaces through Android lifecycle changes. */
|
||||
class ChatActivityReceiptInstrumentedTest {
|
||||
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
|
||||
private lateinit var fixture: AndroidGatewayContractFixture
|
||||
private lateinit var gatewayScope: CoroutineScope
|
||||
private lateinit var gateway: GatewayChatClient
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var socket: WebSocket
|
||||
private val owner = AgentDisplay.profileContextKey("fixture-connection", "research")
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture().also { it.profileName = "research" }
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val http = OkHttpClient()
|
||||
gateway = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(fixture.server.url("/").toString().trimEnd('/'), okHttpClient = http),
|
||||
okHttpClient = http,
|
||||
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.setSessionProfileNameProvider { "research" }
|
||||
it.setProfileMessageLoader { Result.success(emptyList()) }
|
||||
it.setChatActivityStore(InMemoryChatActivityStore())
|
||||
it.switchProfileContext(owner, STORED_SESSION_ID)
|
||||
it.updateGatewayClient(gateway)
|
||||
it.setChatVisible(true)
|
||||
}
|
||||
compose.setContent {
|
||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||
val records by viewModel.activityRecords.collectAsStateWithLifecycle()
|
||||
val children by viewModel.subagentActivities.collectAsStateWithLifecycle()
|
||||
val retained by viewModel.retainedActivityPreview.collectAsStateWithLifecycle()
|
||||
val childPreview by viewModel.subagentChildPreview.collectAsStateWithLifecycle()
|
||||
val session by viewModel.currentSessionId.collectAsStateWithLifecycle()
|
||||
var sheetOpen by remember { mutableStateOf(false) }
|
||||
MaterialTheme {
|
||||
Column {
|
||||
GatewayBackgroundProcessStrip(
|
||||
processes = emptyList(), subagentActivities = children,
|
||||
subagentPreviewVisibility = SubagentPreviewVisibility(), loading = false,
|
||||
onClick = { viewModel.openCurrentActivityPreview(); sheetOpen = true },
|
||||
modifier = Modifier.testTag("active-activity"),
|
||||
)
|
||||
projectChatActivityReceipts(messages, records, owner, session).forEach { message ->
|
||||
message.activityRecord?.let { record ->
|
||||
ChatActivityReceipt(
|
||||
record = record,
|
||||
onClick = { sheetOpen = viewModel.openRetainedActivity(record) },
|
||||
modifier = Modifier.testTag("activity-receipt"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sheetOpen) {
|
||||
GatewayBackgroundProcessSheet(
|
||||
processes = retained?.processes.orEmpty(),
|
||||
subagentActivities = retained?.record?.previewActivities() ?: children,
|
||||
subagentChildPreview = childPreview,
|
||||
subagentPreviewVisibility = SubagentPreviewVisibility(),
|
||||
loading = false, stoppingProcessIds = emptySet(),
|
||||
onRefresh = viewModel::refreshBackgroundProcesses,
|
||||
onStop = viewModel::stopBackgroundProcess,
|
||||
onDismissProcess = viewModel::dismissBackgroundProcess,
|
||||
onOpenSubagentChild = viewModel::openSubagentChildPreview,
|
||||
onDismiss = { viewModel.closeActivityPreview(); sheetOpen = false },
|
||||
readOnlyHistory = retained != null,
|
||||
historyNotice = "Recorded activity. Available child history is read-only.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
socket = fixture.awaitServerSocket()
|
||||
fixture.awaitRpc("session.resume")
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
gateway.shutdown()
|
||||
gatewayScope.cancel()
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detachedCompletionLeavesReopenableReceiptAcrossActivityResume() {
|
||||
viewModel.sendMessage("Delegate a background task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
socket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
socket.send(fixture.event("subagent.start", buildJsonObject {
|
||||
put("subagent_id", "receipt-child")
|
||||
put("delegation_id", "receipt-delegation")
|
||||
put("task_count", 1)
|
||||
put("goal", "Inspect activity lifecycle")
|
||||
}, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { viewModel.subagentActivities.value.size == 1 }
|
||||
compose.onNodeWithTag("active-activity").assertIsDisplayed()
|
||||
socket.send(fixture.event("message.complete", buildJsonObject { put("text", "Launched") }, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { !handler.isStreaming.value }
|
||||
compose.onNodeWithTag("active-activity").assertIsDisplayed()
|
||||
|
||||
socket.send(fixture.event("subagent.complete", buildJsonObject {
|
||||
put("subagent_id", "receipt-child")
|
||||
put("delegation_id", "receipt-delegation")
|
||||
put("status", "completed")
|
||||
}, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { viewModel.activityRecords.value.singleOrNull()?.phase == ChatActivityPhase.COMPLETE }
|
||||
compose.onNodeWithTag("active-activity").assertDoesNotExist()
|
||||
compose.onNodeWithTag("activity-receipt").assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Chat activity").assertIsDisplayed()
|
||||
compose.onNodeWithText("Recorded activity. Available child history is read-only.").assertIsDisplayed()
|
||||
compose.onNodeWithText("Stop").assertDoesNotExist()
|
||||
compose.onNodeWithContentDescription("Close activity preview").performClick()
|
||||
compose.onNodeWithTag("activity-receipt").assertIsDisplayed()
|
||||
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithTag("active-activity").assertDoesNotExist()
|
||||
compose.onNodeWithTag("activity-receipt").assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Chat activity").assertIsDisplayed()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
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.ui.components.MessageBubble
|
||||
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 okhttp3.OkHttpClient
|
||||
import okhttp3.WebSocket
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
/** Production socket, ViewModel, transcript, Compose and IME actions on a virtual device. */
|
||||
class ClarifyBatchInstrumentedTest {
|
||||
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
private lateinit var fixture: AndroidGatewayContractFixture
|
||||
private lateinit var scope: CoroutineScope
|
||||
private lateinit var gateway: GatewayChatClient
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var socket: WebSocket
|
||||
|
||||
@Before fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val http = OkHttpClient()
|
||||
gateway = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(fixture.server.url("/").toString().trimEnd('/'), http),
|
||||
okHttpClient = http, scope = scope,
|
||||
callbackDispatcher = { Handler(Looper.getMainLooper()).post(it) },
|
||||
)
|
||||
handler = ChatHandler().also { it.setSessionId("20260821_120000_fixture") }
|
||||
viewModel = ChatViewModel().also {
|
||||
it.initialize(HermesApiClient(fixture.server.url("/").toString(), "fixture-key"), handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoader { Result.success(emptyList()) }
|
||||
it.updateGatewayClient(gateway)
|
||||
}
|
||||
compose.setContent {
|
||||
val messages by handler.messages.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(messages.size, key = { messages[it].id }) { index ->
|
||||
MessageBubble(messages[index], showTimestamps = false,
|
||||
onCardInput = viewModel::answerAsk, animationEnabled = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait("20260821_120000_fixture") })
|
||||
socket = fixture.awaitServerSocket()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
gateway.shutdown()
|
||||
scope.cancel()
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test fun confirmedProgressSurvivesLifecycleAndCustomAnswerUsesIme() {
|
||||
compose.runOnIdle { viewModel.sendMessage("Ask two questions") }
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
socket.send(fixture.event("clarify.request", Json.parseToJsonElement("""
|
||||
{"request_id":"batch-device","questions":[
|
||||
{"qid":"route/a","question":"Which route?","choices":["Canary","Immediate"]},
|
||||
{"qid":"notes:b","question":"Anything else?","choices":null}
|
||||
]}
|
||||
""") as JsonObject, "fixture-live-1"))
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value != null }
|
||||
compose.onNodeWithText("Canary").performClick()
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "Canary" }
|
||||
assertEquals(JsonPrimitive("route/a"), fixture.awaitRpc("clarify.respond")["question_id"])
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithText("Question 2 of 2").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("Type an answer…").apply {
|
||||
performClick()
|
||||
performTextInput(" Keep rollback ready ")
|
||||
performImeAction()
|
||||
}
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value == null }
|
||||
compose.onNodeWithText("All questions answered").assertIsDisplayed()
|
||||
assertEquals(2, fixture.rpcCount("clarify.respond"))
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,10 @@ 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.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
@@ -58,9 +62,17 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
private var gatewayScope: CoroutineScope? = null
|
||||
private var gatewayClient: GatewayChatClient? = null
|
||||
private var viewModel: ChatViewModel? = null
|
||||
private var voiceViewModel: VoiceViewModel? = null
|
||||
private var voicePlayer: com.hermesandroid.relay.audio.VoicePlayer? = null
|
||||
private var voiceSfx: com.hermesandroid.relay.audio.VoiceSfxPlayer? = null
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
compose.runOnUiThread {
|
||||
voiceViewModel?.exitVoiceMode()
|
||||
voicePlayer?.release()
|
||||
voiceSfx?.release()
|
||||
}
|
||||
viewModel?.updateGatewayClient(null)
|
||||
gatewayClient?.shutdown()
|
||||
gatewayScope?.cancel()
|
||||
@@ -171,6 +183,155 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedStopResume_preservesWorkAcrossLifecycleAndUsesExplicitResume() {
|
||||
val base = InstrumentationRegistry.getArguments().getString(ARG_FIXTURE_BASE_URL)?.trimEnd('/')
|
||||
assumeTrue("Pass a queued_stop_resume fixture URL", !base.isNullOrBlank())
|
||||
requireNotNull(base)
|
||||
val http = OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build()
|
||||
assertEquals("queued_stop_resume", readFixtureJson(http, "$base/__fixture__/state")["scenario"]?.jsonString())
|
||||
val dashboard = DashboardApiClient(base, http)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard, okHttpClient = http, scope = scope,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val vm = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, session, mode -> dashboard.getSessionMessages(session, profile, mode) }
|
||||
it.updateGatewayClient(gateway)
|
||||
it.switchProfileContext(com.hermesandroid.relay.data.AgentDisplay.profileContextKey("fixture-queue", null), STORED_SESSION_ID)
|
||||
}.also { viewModel = it }
|
||||
compose.setContent {
|
||||
val queue by vm.queuedMessages.collectAsStateWithLifecycle()
|
||||
val paused by vm.queuePaused.collectAsStateWithLifecycle()
|
||||
com.hermesandroid.relay.ui.theme.HermesRelayTheme(themePreference = "dark") {
|
||||
androidx.compose.material3.Surface {
|
||||
Column {
|
||||
com.hermesandroid.relay.ui.components.ChatBusyActionSelector(
|
||||
com.hermesandroid.relay.data.BusyMessageAction.QueueNext, {}, onStop = vm::cancelStream,
|
||||
)
|
||||
com.hermesandroid.relay.ui.components.ChatMessageQueue(
|
||||
queue, paused, vm::resumeQueue, vm::clearQueue, {}, vm::removeQueuedAt, canEdit = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
compose.runOnIdle { vm.sendMessage("Original work") }
|
||||
compose.waitUntil(10_000) { handler.isStreaming.value && vm.steerableTurn.value }
|
||||
compose.runOnIdle {
|
||||
vm.sendMessage("Remove this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
vm.sendMessage("Keep this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
}
|
||||
compose.onAllNodesWithContentDescription("Remove queued message")[0].performClick()
|
||||
compose.onNodeWithContentDescription("Stop streaming").performClick()
|
||||
compose.onNodeWithText("Queue paused").assertIsDisplayed()
|
||||
assertEquals(listOf("Keep this follow-up"), vm.queuedMessages.value)
|
||||
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.CREATED)
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithText("Keep this follow-up").assertIsDisplayed()
|
||||
compose.onNodeWithText("Resume").performClick()
|
||||
try {
|
||||
compose.waitUntil(15_000) {
|
||||
vm.queuedMessages.value.isEmpty() && !handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == "Resumed follow-up." }
|
||||
}
|
||||
} catch (error: androidx.compose.ui.test.ComposeTimeoutException) {
|
||||
throw AssertionError(
|
||||
"Synthetic queue fixture did not settle: queued=${vm.queuedMessages.value.size}, " +
|
||||
"paused=${vm.queuePaused.value}, streaming=${handler.isStreaming.value}, " +
|
||||
"messages=${handler.messages.value.map { it.role to it.content }}, " +
|
||||
"error=${handler.error.value}",
|
||||
error,
|
||||
)
|
||||
}
|
||||
val evidence = readFixtureJson(http, "$base/__fixture__/evidence")["entries"] as JsonArray
|
||||
assertEquals(2, evidence.rpcCount("prompt.submit"))
|
||||
assertEquals(1, evidence.rpcCount("session.interrupt"))
|
||||
assertEquals(0, evidence.rpcCount("session.redirect"))
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unsolicitedVoiceCompletions_surviveActivityPauseWithoutHistorySpeech() {
|
||||
val base = InstrumentationRegistry.getArguments().getString(ARG_FIXTURE_BASE_URL)
|
||||
?.trim()?.trimEnd('/')
|
||||
assumeTrue("Pass the unsolicited_voice_completions fixture URL", !base.isNullOrBlank())
|
||||
requireNotNull(base)
|
||||
val http = OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build()
|
||||
assertEquals("unsolicited_voice_completions", readFixtureJson(http, "$base/__fixture__/state")["scenario"]?.jsonString())
|
||||
val dashboard = DashboardApiClient(base, http)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard, okHttpClient = http,
|
||||
callbackDispatcher = { Handler(Looper.getMainLooper()).post(it) }, scope = scope,
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val spoken = java.util.concurrent.CopyOnWriteArrayList<String>()
|
||||
lateinit var vm: ChatViewModel
|
||||
compose.runOnUiThread {
|
||||
val app = compose.activity.application
|
||||
vm = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, id, mode ->
|
||||
dashboard.getSessionMessages(id, profile, mode)
|
||||
}
|
||||
it.updateGatewayClient(gateway)
|
||||
viewModel = it
|
||||
}
|
||||
val audio = object : com.hermesandroid.relay.network.shared.VoiceAudioClient {
|
||||
override val route = com.hermesandroid.relay.data.VoiceAudioRoute.Standard
|
||||
override suspend fun transcribe(audioFile: java.io.File) = Result.success("")
|
||||
override suspend fun synthesize(text: String): Result<java.io.File> {
|
||||
spoken.add(text)
|
||||
// A short silent WAV exercises the production play/drain path without a provider.
|
||||
val pcm = ByteArray(3200)
|
||||
val header = java.nio.ByteBuffer.allocate(44).order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
.put("RIFF".toByteArray()).putInt(36 + pcm.size).put("WAVEfmt ".toByteArray())
|
||||
.putInt(16).putShort(1).putShort(1).putInt(16000).putInt(32000)
|
||||
.putShort(2).putShort(16).put("data".toByteArray()).putInt(pcm.size).array()
|
||||
val file = java.io.File.createTempFile("fixture-voice", ".wav", app.cacheDir)
|
||||
file.writeBytes(header + pcm)
|
||||
return Result.success(file)
|
||||
}
|
||||
}
|
||||
val player = com.hermesandroid.relay.audio.VoicePlayer(app).also { voicePlayer = it }
|
||||
val sfx = com.hermesandroid.relay.audio.VoiceSfxPlayer(app).also { voiceSfx = it }
|
||||
voiceViewModel = VoiceViewModel(app).also {
|
||||
it.initialize(
|
||||
voiceClient = com.hermesandroid.relay.network.relay.RelayVoiceClient(app, http, { null }, { null }),
|
||||
voiceAudioClient = audio, chatViewModel = vm,
|
||||
recorder = com.hermesandroid.relay.audio.VoiceRecorder(app, scope),
|
||||
player = player, sfxPlayer = sfx,
|
||||
)
|
||||
it.enterVoiceMode()
|
||||
}
|
||||
}
|
||||
compose.setContent {
|
||||
val messages by vm.messages.collectAsStateWithLifecycle()
|
||||
Text(messages.joinToString("\n") { it.content }, Modifier.testTag("voice-fixture-history"))
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
compose.runOnUiThread { vm.sendMessage("Start background work.") }
|
||||
compose.waitUntil(10_000) { handler.messages.value.any { it.content == "Work started." } }
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.STARTED)
|
||||
compose.waitUntil(15_000) { spoken.size == 3 }
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
compose.runOnUiThread { voiceViewModel?.onAppResumed() }
|
||||
compose.waitForIdle()
|
||||
assertEquals(listOf("Process finished.", "Watch matched.", "Delegated work finished."), spoken.toList())
|
||||
assertEquals(1, readFixtureJson(http, "$base/__fixture__/evidence")["entries"].let { it as JsonArray }.rpcCount("prompt.submit"))
|
||||
assertTrue(handler.messages.value.any { it.content == "Delegated work finished." })
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -4,11 +4,13 @@ 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.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
@@ -16,16 +18,29 @@ 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.AgentDisplay
|
||||
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||
import com.hermesandroid.relay.ui.screens.shouldOwnVisibleGateway
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
@@ -44,6 +59,7 @@ import okhttp3.mockwebserver.RecordedRequest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
@@ -74,10 +90,13 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
|
||||
@Volatile
|
||||
private var persistedHistory: List<MessageItem> = emptyList()
|
||||
private val historySignInRequired = MutableStateFlow(false)
|
||||
private val coldStartAdmissionEnabled = MutableStateFlow(false)
|
||||
private val coldStartGatewayAvailability = MutableStateFlow(GatewayAvailability.Unknown)
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
fixture = AndroidGatewayContractFixture().also { it.profileName = PROFILE_NAME }
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
@@ -97,6 +116,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
handler,
|
||||
)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setSessionProfileNameProvider { PROFILE_NAME }
|
||||
it.setProfileMessageLoader { Result.success(persistedHistory) }
|
||||
it.updateGatewayClient(gatewayClient)
|
||||
it.setChatVisible(true)
|
||||
@@ -105,8 +125,31 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
compose.setContent {
|
||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||
val children by viewModel.subagentActivities.collectAsStateWithLifecycle()
|
||||
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
||||
val admissionEnabled by coldStartAdmissionEnabled.collectAsStateWithLifecycle()
|
||||
val admissionAvailability by coldStartGatewayAvailability.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(admissionEnabled, admissionAvailability) {
|
||||
if (admissionEnabled) {
|
||||
viewModel.setChatVisible(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = admissionAvailability,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("contract-transcript")) {
|
||||
GatewayBackgroundProcessStrip(
|
||||
processes = emptyList(),
|
||||
subagentActivities = children,
|
||||
subagentPreviewVisibility = SubagentPreviewVisibility(),
|
||||
loading = false,
|
||||
onClick = {},
|
||||
modifier = Modifier.testTag("child-activity"),
|
||||
)
|
||||
Text(
|
||||
text = if (streaming) "STREAMING" else "IDLE",
|
||||
modifier = Modifier.testTag("stream-state"),
|
||||
@@ -117,6 +160,14 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
modifier = Modifier.testTag("message-${message.id}"),
|
||||
)
|
||||
}
|
||||
if (signInRequired) {
|
||||
Button(
|
||||
onClick = {},
|
||||
modifier = Modifier.testTag("dashboard-sign-in-recovery"),
|
||||
) {
|
||||
Text("SIGN IN")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,6 +177,122 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
fixture.awaitRpc("session.resume")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun authenticatedUnknownColdLaunch_opensObservationSocketWithoutLifecycleBounce() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val ticketMintsBefore = fixture.requestsTo("/api/auth/ws-ticket")
|
||||
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 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
coldStartGatewayAvailability.value = GatewayAvailability.Unknown
|
||||
coldStartAdmissionEnabled.value = true
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
gatewayClient.connectionState.value == GatewayConnectionState.Ready
|
||||
}
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
assertEquals(ticketMintsBefore + 1, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"cold observation sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardOnlyColdLaunch_waitsForExactDirectoryThenOpensObservationSocket() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val directoryStarted = CompletableDeferred<Unit>()
|
||||
val directoryResult = CompletableDeferred<Result<List<SessionItem>>>()
|
||||
viewModel.setProfileSessionLister { profile ->
|
||||
assertEquals(PROFILE_NAME, profile)
|
||||
directoryStarted.complete(Unit)
|
||||
directoryResult.await()
|
||||
}
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val ticketMintsBefore = fixture.requestsTo("/api/auth/ws-ticket")
|
||||
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 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
viewModel.setChatVisible(true)
|
||||
|
||||
// This is the production binder's Dashboard/profile hydration edge.
|
||||
// The socket must stay passive and closed until the exact-owner REST
|
||||
// directory publishes, then open without a lifecycle bounce.
|
||||
viewModel.refreshSessions()
|
||||
compose.waitUntil(5_000) { directoryStarted.isCompleted }
|
||||
assertEquals(ticketMintsBefore, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
|
||||
directoryResult.complete(
|
||||
Result.success(listOf(SessionItem(id = STORED_SESSION_ID, title = "Fixture session"))),
|
||||
)
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
gatewayClient.connectionState.value == GatewayConnectionState.Ready
|
||||
}
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
assertEquals(ticketMintsBefore + 1, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"directory-gated cold observation sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
@@ -134,6 +301,37 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detachedChildActivity_survivesParentTerminalAndActivityResume() {
|
||||
viewModel.sendMessage("Delegate a background task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(fixture.event("subagent.start", buildJsonObject {
|
||||
put("subagent_id", "detached-child")
|
||||
put("goal", "Inspect")
|
||||
}, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { viewModel.subagentActivities.value.size == 1 }
|
||||
compose.onNodeWithTag("child-activity").assertIsDisplayed()
|
||||
serverSocket.send(fixture.event("message.complete", buildJsonObject { put("text", "Launched") }, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { !handler.isStreaming.value }
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
serverSocket.send(fixture.event("subagent.progress", buildJsonObject {
|
||||
put("subagent_id", "detached-child")
|
||||
put("text", "Still working")
|
||||
}, LIVE_SESSION_ID))
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
compose.waitUntil(5_000) { viewModel.subagentActivities.value.single().events.last().text == "Still working" }
|
||||
compose.onNodeWithTag("child-activity").assertIsDisplayed()
|
||||
assertFalse(viewModel.subagentActivities.value.single().isTerminal)
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
serverSocket.send(fixture.event("subagent.complete", buildJsonObject {
|
||||
put("subagent_id", "detached-child")
|
||||
put("status", "completed")
|
||||
}, LIVE_SESSION_ID))
|
||||
compose.waitUntil(5_000) { viewModel.subagentActivities.value.single().isTerminal }
|
||||
compose.onNodeWithTag("child-activity").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActivate_recoversForegroundTurnWithoutNavigationOrCrossSessionLeak() {
|
||||
viewModel.sendMessage("Run a long foreground task")
|
||||
@@ -239,6 +437,243 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActiveList_settlesExactOwnedTurnAndRendersAuthoritativeHistory() {
|
||||
viewModel.sendMessage("Run an Android-owned task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", PARTIAL_ANSWER) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.activeSessionStatus = "idle"
|
||||
runBlocking { gatewayClient.listActiveSessions() }
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gatewayClient.hasActiveTurn() &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
assertEquals(0, fixture.rpcCount("session.interrupt"))
|
||||
assertEquals(0, fixture.rpcCount("session.activate"))
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
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 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
assertTrue(runBlocking { gatewayClient.observeAwait() })
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
viewModel.updateSessionActivityDirectory(listOf(PROFILE_NAME to STORED_SESSION_ID))
|
||||
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.setChatVisible(true)
|
||||
fixture.awaitRpcCount("session.active_list", baselineActiveList + 1)
|
||||
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"passive lifecycle sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
assertEquals(
|
||||
"observer teardown interrupted the Desktop turn",
|
||||
baseline.getValue("session.interrupt"),
|
||||
fixture.rpcCount("session.interrupt"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalCompletion_genericHistory401RetainsTranscriptAndRequiresProfileSignIn() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = "Unauthorized",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
|
||||
viewModel.sendMessage("Keep this local transcript")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value &&
|
||||
!handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == LOCAL_COMPLETION }
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local transcript" })
|
||||
assertTrue(handler.messages.value.any { it.content == LOCAL_COMPLETION })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveredCompletion_sessionExpiredHistoryRetainsSettledTranscript() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = """{"reason":"session_expired"}""",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
val now = System.currentTimeMillis()
|
||||
val contextKey = AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME)
|
||||
viewModel.setChatTurnCheckpointStore(
|
||||
MemoryCheckpointStore(
|
||||
ChatTurnCheckpoint(
|
||||
contextKey = contextKey,
|
||||
profileKey = PROFILE_NAME,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
liveSessionId = LIVE_SESSION_ID,
|
||||
transport = "gateway",
|
||||
user = ChatTurnUserCheckpoint("recovered-user", "Resume this turn", now - 2_000L),
|
||||
assistant = ChatTurnAssistantCheckpoint(
|
||||
id = "recovered-assistant",
|
||||
content = "Recovered partial",
|
||||
timestamp = now - 1_900L,
|
||||
),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
startedAt = now - 2_000L,
|
||||
updatedAt = now,
|
||||
),
|
||||
),
|
||||
)
|
||||
fixture.recoveryRunning = true
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
|
||||
fixture.awaitRpc("session.activate")
|
||||
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value && !handler.isStreaming.value
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(
|
||||
"recovered completion was not retained: ${handler.messages.value}",
|
||||
handler.messages.value.any { it.content.contains(RECOVERED_COMPLETION.trim()) },
|
||||
)
|
||||
assertFalse(handler.messages.value.any { it.isStreaming || it.isThinkingStreaming })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
private fun bindDashboardHistoryFailure(body: String, profileName: String) {
|
||||
fixture.profileName = profileName
|
||||
fixture.historyFailureBody = body
|
||||
val dashboard = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
)
|
||||
viewModel.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
|
||||
dashboard.getSessionMessages(sessionId, profile, mode)
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler {
|
||||
historySignInRequired.value = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertExactProfileHistoryOnly(profileName: String) {
|
||||
val historyRequests = fixture.historyRequestPaths()
|
||||
assertTrue("no Dashboard history request was observed", historyRequests.isNotEmpty())
|
||||
assertTrue(
|
||||
"history escaped the exact profile: $historyRequests",
|
||||
historyRequests.all { it.contains("profile=$profileName") },
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
@@ -247,6 +682,23 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
const val PARTIAL_ANSWER = "Partial foreground answer"
|
||||
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
|
||||
const val FOREIGN_ANSWER = "Wrong session content"
|
||||
const val PROFILE_NAME = "research"
|
||||
const val LOCAL_COMPLETION = "Completed before Dashboard auth expired."
|
||||
const val RECOVERED_COMPLETION = " and then recovered to completion."
|
||||
}
|
||||
}
|
||||
|
||||
private class MemoryCheckpointStore(
|
||||
private var checkpoint: ChatTurnCheckpoint?,
|
||||
) : ChatTurnCheckpointStore {
|
||||
override suspend fun read(): ChatTurnCheckpoint? = checkpoint
|
||||
|
||||
override suspend fun write(checkpoint: ChatTurnCheckpoint) {
|
||||
this.checkpoint = checkpoint
|
||||
}
|
||||
|
||||
override suspend fun clear() {
|
||||
checkpoint = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +715,15 @@ internal class AndroidGatewayContractFixture {
|
||||
@Volatile
|
||||
var recoveryRunning = false
|
||||
|
||||
@Volatile
|
||||
var activeSessionStatus: String? = null
|
||||
|
||||
@Volatile
|
||||
var historyFailureBody: String? = null
|
||||
|
||||
@Volatile
|
||||
var profileName: String = "default"
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
@@ -282,6 +743,18 @@ internal class AndroidGatewayContractFixture {
|
||||
"session.activate" -> sessionSnapshot(
|
||||
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "fixture-live-1",
|
||||
)
|
||||
"session.active_list" -> buildJsonObject {
|
||||
put("sessions", kotlinx.serialization.json.buildJsonArray {
|
||||
activeSessionStatus?.let { status ->
|
||||
add(buildJsonObject {
|
||||
put("id", LIVE_SESSION_ID)
|
||||
put("session_key", STORED_SESSION_ID)
|
||||
put("status", status)
|
||||
put("last_active", 1.0)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
"prompt.submit", "session.interrupt" -> buildJsonObject { put("ok", true) }
|
||||
else -> JsonObject(emptyMap())
|
||||
}
|
||||
@@ -308,6 +781,11 @@ internal class AndroidGatewayContractFixture {
|
||||
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
|
||||
)
|
||||
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
|
||||
path.startsWith("/api/sessions/") && path.contains("/messages") &&
|
||||
historyFailureBody != null -> MockResponse()
|
||||
.setResponseCode(401)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(historyFailureBody.orEmpty())
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
@@ -319,7 +797,7 @@ internal class AndroidGatewayContractFixture {
|
||||
put("session_id", sessionId)
|
||||
put("running", recoveryRunning)
|
||||
put("status", if (recoveryRunning) "streaming" else "idle")
|
||||
put("info", buildJsonObject { put("profile_name", "default") })
|
||||
put("info", buildJsonObject { put("profile_name", profileName) })
|
||||
}
|
||||
|
||||
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
|
||||
@@ -337,7 +815,7 @@ internal class AndroidGatewayContractFixture {
|
||||
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
|
||||
|
||||
fun awaitRpc(method: String): JsonObject {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
|
||||
Thread.sleep(20)
|
||||
@@ -345,12 +823,30 @@ internal class AndroidGatewayContractFixture {
|
||||
error("Gateway RPC $method not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun awaitRpcCount(method: String, count: Int) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (rpcCount(method) >= count) return
|
||||
Thread.sleep(20)
|
||||
}
|
||||
error("Gateway RPC $method count $count not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun historyRequestPaths(): List<String> = requestPaths.filter {
|
||||
it.startsWith("/api/sessions/") && it.contains("/messages")
|
||||
}
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
|
||||
fun shutdown() {
|
||||
allSockets.forEach { socket -> runCatching { socket.close(1001, "teardown") } }
|
||||
runCatching { server.shutdown() }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<activity
|
||||
android:name="com.hermesandroid.relay.ui.screens.BotChatBindingTestActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait" />
|
||||
<activity
|
||||
android:name="com.hermesandroid.relay.ui.screens.VoiceSettingsDesignQaActivity"
|
||||
android:exported="true"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.activity.ComponentActivity
|
||||
|
||||
/** Empty debug-only host populated by the Bot Chat lifecycle instrumentation. */
|
||||
class BotChatBindingTestActivity : ComponentActivity()
|
||||
@@ -8,7 +8,7 @@
|
||||
Google Play ships Hermes Bridge Core only. It intentionally does not merge
|
||||
any Device Control services or permissions.
|
||||
|
||||
This file is intentionally kept as an empty overlay so future flavor-specific
|
||||
This overlay owns the voice-only special access so future flavor-specific
|
||||
permissions / activities have an obvious home. Mirror structural additions
|
||||
in `app/src/sideload/AndroidManifest.xml` unless the change is intentionally
|
||||
track-specific.
|
||||
@@ -22,6 +22,9 @@
|
||||
android:name="android.permission.WAKE_LOCK"
|
||||
tools:node="remove" />
|
||||
|
||||
<!-- User-started voice controls only; does not enable Device Control. -->
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
|
||||
<application />
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -1,62 +1,56 @@
|
||||
Hermes-Relay is the native Android client for the Hermes agent platform. Point it at your own Hermes instance and chat with your agent, talk to it hands-free, and manage models, keys, skills, and profiles from anywhere.
|
||||
Hermes-Relay is the native Android companion for the Hermes agent you run. Chat, talk hands-free, continue sessions, and manage models, keys, skills, profiles, and automations from your phone.
|
||||
|
||||
It is not a hosted AI service. It is a companion app for the Hermes agent you run, and it talks only to the instances you configure.
|
||||
It is not a hosted AI service. Your Hermes agent stays on infrastructure you control, and the app talks only to instances you configure.
|
||||
|
||||
QUICK START
|
||||
|
||||
1. Run hermes-agent with its API server and dashboard enabled on your computer or home server.
|
||||
2. Install Hermes-Relay and enter your server address, for example http://192.168.1.100:8642.
|
||||
3. The setup wizard checks what your server supports and shows a readiness card, then you are ready to chat.
|
||||
1. Start the Hermes Dashboard/Gateway on your computer or home server with hermes dashboard.
|
||||
2. Install Hermes-Relay from Google Play.
|
||||
3. For the recommended full setup, install the Hermes-Relay plugin on the host and refresh the Web Dashboard. A Relay page will appear.
|
||||
4. Scan Connect mobile app from Android Connect. Then scan Pair new device from Android Settings > Connections.
|
||||
|
||||
A plain Hermes install is enough. Chat, management, and voice work with no plugin or extra service.
|
||||
The QR codes are separate on purpose. Connect mobile app adds the standard Dashboard/Gateway connection. Pair new device grants a time-limited Hermes-Relay session for the additional capabilities you approve.
|
||||
|
||||
Standard Hermes without the plugin is supported. Choose Find Hermes on LAN or enter the Dashboard address you open in a browser, normally http://<host>:9119. Pair the Hermes-Relay plugin later when you want the full experience.
|
||||
|
||||
HOW IT WORKS
|
||||
|
||||
Chat streams directly from your Hermes API Server or dashboard gateway in real time. Manage and voice use your Hermes dashboard with one sign-in. Run the optional relay service and the app can pair by QR code to add power tools: remote terminal, notification companion, media handoff, relay-session management, and additional voice engines.
|
||||
Chat, sessions, Manage, sign-in, and standard voice use the unmodified Hermes Dashboard/Gateway. The separate Hermes API server is an optional fallback for advanced or headless setups; it is not required for the normal Android connection.
|
||||
|
||||
GOOGLE PLAY BUILD
|
||||
The encouraged Hermes-Relay plugin adds Terminal/TUI, notifications, media handoff, enhanced voice, Relay sessions, desktop-tool handoff, and time-limited per-feature grants. When upstream Hermes provides a compatible capability, Hermes-Relay prefers it instead of duplicating it.
|
||||
|
||||
The Google Play build ships Hermes Bridge Core only. It has no AccessibilityService Device Control: it cannot read your screen, tap, type, swipe, screenshot, send SMS, place calls, or access contacts or location. Device Control is reserved for sideload builds distributed outside Google Play.
|
||||
GOOGLE PLAY AND SIDELOAD
|
||||
|
||||
The Google Play build includes Chat, voice, sessions, Manage, profiles, notifications, media, and Terminal/TUI when the Hermes-Relay plugin is paired.
|
||||
|
||||
Google Play does not include Android Device Control. It cannot tap, type, swipe, send SMS, place calls, or access contacts or location. Optional Voice Overlay provides user-started voice controls over other apps, with microphone notification and Stop voice. Selecting Hermes as Android Digital Assistant can provide bounded screen text and a screenshot for an explicit unlocked assistant invocation; this context goes to your configured server and AI provider.
|
||||
|
||||
Device Control is available only in the signed Sideload build on this project's GitHub Releases. It requires the Sideload app, a paired Hermes-Relay plugin, explicit Android accessibility permission, and the app's safety controls.
|
||||
|
||||
FEATURES
|
||||
|
||||
- Streaming Chat: real-time responses with reasoning, markdown, tool-call visibility, attachments, mid-turn steering, edit-and-resend, and a searchable command palette.
|
||||
|
||||
- Manage Your Agent: use your Hermes dashboard from your phone to switch models, manage provider keys, edit profiles, and browse, install, and update skills.
|
||||
|
||||
- Voice Mode: talk hands-free using your server's speech providers. Relay-paired setups add per-profile voices and an experimental realtime engine.
|
||||
|
||||
- Works Away From Home: add LAN, Tailscale, or public routes and the app chooses the best available path on connect.
|
||||
|
||||
- Sessions: create, switch, rename, and delete chats. Message history loads on demand.
|
||||
|
||||
- Multiple Servers and Profiles: connect to more than one server and switch in a tap; overlay an agent profile or personality per conversation.
|
||||
|
||||
- Relay Power Tools: optional QR pairing for remote terminal, relay-session management, media handoff, and per-feature grants.
|
||||
|
||||
- Notification Companion: optionally forward notification metadata to your paired relay so your assistant can summarize it. Toggle it anytime in system settings.
|
||||
|
||||
- Stats for Nerds: local-only counters for response timing, token usage, cost, and stream health.
|
||||
|
||||
- Material You: Material 3 dynamic color, light/dark/system themes, and haptics.
|
||||
- Streaming Chat with reasoning, markdown, tool progress, attachments, mid-turn steering, edit-and-resend, and searchable commands.
|
||||
- Manage models and provider keys, edit profiles, and browse, install, or update skills through the Hermes Dashboard.
|
||||
- Hands-free voice through your server's speech providers. Hermes-Relay pairing adds per-profile voices and an experimental realtime engine.
|
||||
- Inspect connection readiness, routes, response timing, token usage, and stream health without exposing credentials.
|
||||
|
||||
SECURITY AND PRIVACY
|
||||
|
||||
- API keys and relay tokens are stored in encrypted Android storage.
|
||||
- HTTPS is enforced for remote connections; cleartext is limited to localhost or LAN setups.
|
||||
- Dashboard sessions and Hermes-Relay tokens use encrypted Android storage.
|
||||
- Cleartext is limited to trusted local-network setups. Use a VPN or HTTPS remotely.
|
||||
- No telemetry, ads, tracking, or third-party analytics SDKs.
|
||||
- Notification access and the microphone are optional and user-controlled.
|
||||
- All app traffic goes only to servers you configure.
|
||||
- Notification and microphone access are optional and user-controlled.
|
||||
- App traffic goes only to servers you configure.
|
||||
|
||||
REQUIREMENTS
|
||||
|
||||
- Android 8.0 or later.
|
||||
- A running Hermes agent for chat, management, and voice.
|
||||
- Optional Hermes relay service for power tools such as terminal, notifications, and media.
|
||||
- Network access to your server by local network, VPN, or internet.
|
||||
- A reachable Hermes Dashboard/Gateway.
|
||||
- The Hermes-Relay plugin is encouraged for the complete experience but never blocks standard Hermes.
|
||||
- Network access through a local network, VPN, or operator-managed internet route.
|
||||
|
||||
OPEN SOURCE
|
||||
|
||||
Hermes-Relay is MIT licensed. Source, docs, and issue tracking are on GitHub.
|
||||
Hermes-Relay is MIT licensed. Source, setup guides, downloads, and issue tracking are on GitHub.
|
||||
|
||||
This app is a community project and is not affiliated with or endorsed by NousResearch.
|
||||
This community project is not affiliated with or endorsed by NousResearch.
|
||||
|
||||
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 509 KiB |
|
Before Width: | Height: | Size: 176 KiB After Width: | Height: | Size: 185 KiB |
|
Before Width: | Height: | Size: 186 KiB After Width: | Height: | Size: 207 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 232 KiB After Width: | Height: | Size: 226 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 180 KiB After Width: | Height: | Size: 168 KiB |
@@ -1 +1 @@
|
||||
Your Hermes AI agent, in your pocket - chat, voice, and control.
|
||||
Your Hermes agent on Android — chat, voice, sessions, and Manage.
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
Shared links, text, images, and files now open as complete reviewable drafts without sending automatically. Add and Renew connection setup no longer stalls. Offline chat and profile-history failures surface clear recovery guidance instead of doing nothing or showing empty history. Diagnostics now reports secure-storage fallback and recovery without exposing credentials.
|
||||
v1.17.0 - Voice over other apps and clearer conversations
|
||||
|
||||
Use optional voice controls over other apps, with clear permission setup and an immediate Stop action. Answer Clarify batches one question at a time, with progress preserved across reconnects. Enjoy cleaner chat cards, recognizable profile names, and context previews that show what your connection supports. Phone control remains sideload-only.
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
共享链接、文本、图片和文件现在会作为完整、可检查的草稿打开,不会自动发送。添加或续订连接时不再卡在准备阶段。离线聊天和配置文件历史记录失败会显示明确的恢复提示,而不是无响应或显示空历史记录。诊断现在会报告安全存储降级与恢复,且不会暴露凭据。
|
||||
v1.17.0 - 跨应用语音与更清晰的对话
|
||||
|
||||
可选的语音悬浮控件让你在使用其他应用时继续语音会话,提供清晰的权限说明和随时停止操作。逐题回答 Clarify 批量问题,重连后保留已确认的进度。聊天卡片更简洁,配置文件显示名称更易辨认,上下文预览准确说明当前连接支持发送哪些信息。设备控制仍仅限侧载版本。
|
||||
|
||||
@@ -1,5 +1,497 @@
|
||||
{
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.17.0",
|
||||
"title": "Voice over other apps and clearer conversations",
|
||||
"date": "2026-09-13",
|
||||
"summary": "Google Play gains optional voice controls over other apps. Clarify questions, profile names, and chat context are easier to follow without losing confirmed answers or saved conversations.",
|
||||
"changes": [
|
||||
{"id": "play-voice-overlay", "kind": "added", "title": "Keep voice controls over other apps", "summary": "Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Stop voice from its controls or persistent notification; screen lock and permission loss end the session.", "highlight": true},
|
||||
{"id": "clarify-batches", "kind": "fixed", "title": "Answer Clarify questions one at a time", "summary": "Multi-question requests support separate choices and custom answers. Confirmed progress survives reconnects, and failed sends keep the current answer available.", "highlight": true},
|
||||
{"id": "chat-card-surfaces", "kind": "improved", "title": "Read cleaner chat cards", "summary": "Standalone response cards lose the extra outer bubble, assistant messages use quieter surfaces, and delivery status sits beside the timestamp."},
|
||||
{"id": "transport-context-preview", "kind": "fixed", "title": "See which context your chat can send", "summary": "Gateway previews mark phone status and turn context as unavailable. Automatic phone-status sharing is labeled for API-only chats, where it remains supported."},
|
||||
{"id": "profile-display-names", "kind": "fixed", "title": "Recognize profiles by their display names", "summary": "Profiles use their Hermes display names, and the resolved server default appears under its agent identity. Explicit profile choices and saved conversations are preserved.", "highlight": true}
|
||||
],
|
||||
"compatibility": [
|
||||
"Voice Overlay is now available in Google Play and sideload builds. Device Control remains sideload-only.",
|
||||
"Standard Chat and voice use upstream Hermes without requiring Hermes-Relay Plugin. Gateway phone-status delivery and automatic Android identification remain unavailable."
|
||||
],
|
||||
"playNotes": "Use optional voice controls over other apps, with clear permission setup and an immediate Stop action. Answer Clarify batches one question at a time, with progress preserved across reconnects. Enjoy cleaner chat cards, recognizable profile names, and context previews that show what your connection supports. Phone control remains sideload-only.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.16.1",
|
||||
"title": "Dashboard-only cold starts recover",
|
||||
"date": "2026-09-12",
|
||||
"summary": "Dashboard-only connections can now prepare the selected profile and open Gateway chat without waiting for a background, resume, or network-route change.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "gateway-directory-bootstrap",
|
||||
"kind": "fixed",
|
||||
"title": "Open Gateway chat from a Dashboard-only cold start",
|
||||
"summary": "The selected profile's session directory starts before Gateway readiness, so it cannot wait on the same passive socket that depends on its result.",
|
||||
"highlight": true
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Dashboard and Gateway chat continue to use current upstream Hermes without requiring the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.2 remains the matching optional release for Relay tools."
|
||||
],
|
||||
"playNotes": "Dashboard-only connections now prepare the selected profile before Gateway readiness, fixing a remaining cold-start path that could stay on waking or waiting for Gateway until the app resumed or its network route changed.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.16.0",
|
||||
"title": "Safer startup, connections, and activity",
|
||||
"date": "2026-09-10",
|
||||
"summary": "Gateway chat opens reliably from a cold launch, saved sign-ins stay with the correct connection, and network changes no longer race the route cache. Bot Mode and delegated-work feedback also remain stable across multiple gateways and later review.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "gateway-cold-start",
|
||||
"kind": "fixed",
|
||||
"title": "Open Gateway chat on the first launch",
|
||||
"summary": "An authenticated Gateway wakes and opens from a cold foreground start instead of waiting for the app to background and resume.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "connection-owned-signin",
|
||||
"kind": "fixed",
|
||||
"title": "Keep saved sign-ins with their connection",
|
||||
"summary": "Switching gateways cannot reuse an outgoing resolver route to invalidate another connection's saved Dashboard session.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "network-change-invalidation",
|
||||
"kind": "fixed",
|
||||
"title": "Recover safely when the network changes",
|
||||
"summary": "Route-probe completion and endpoint-cache invalidation are serialized so Wi-Fi, mobile-data, VPN, or Tailscale changes do not trigger the reported crash.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "bot-mode-connection-identity",
|
||||
"kind": "fixed",
|
||||
"title": "Open same-named bots from multiple gateways",
|
||||
"summary": "Bot Mode and Active Now keep connection and profile identity together, avoiding duplicate list keys and opening progress on the selected bot."
|
||||
},
|
||||
{
|
||||
"id": "delegated-activity-receipts",
|
||||
"kind": "improved",
|
||||
"title": "Review delegated work after it finishes",
|
||||
"summary": "Compact, bounded activity receipts survive parent replies and remain available read-only, while the live strip appears only during active work.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "chat-feedback-surfaces",
|
||||
"kind": "improved",
|
||||
"title": "Keep feedback with the surface that owns it",
|
||||
"summary": "Themed banners and action cards replace platform popups, global actions stay clear of the composer, and local Developer previews make feedback states inspectable."
|
||||
},
|
||||
{
|
||||
"id": "attachment-error-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Retry missing attachments in place",
|
||||
"summary": "A missing attachment keeps its error and Retry action in the attachment card without producing repeated global messages."
|
||||
},
|
||||
{
|
||||
"id": "session-preparation-diagnostics",
|
||||
"kind": "improved",
|
||||
"title": "See session preparation and initialization failures",
|
||||
"summary": "Chat distinguishes session preparation from response streaming, retains early initialization errors, and opens session diagnostics from the agent header."
|
||||
},
|
||||
{
|
||||
"id": "pasted-dashboard-credentials",
|
||||
"kind": "fixed",
|
||||
"title": "Paste Dashboard credentials without hidden line breaks",
|
||||
"summary": "Username and password fields remove pasted carriage returns and line feeds while preserving every other credential character."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, profiles, Manage, voice, Bot Mode, and delegated activity continue to use current upstream Hermes without requiring the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.2 is the matching optional release for Relay tools. Existing erased or revoked Dashboard credentials still require a legitimate sign-in.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain sideload-only."
|
||||
],
|
||||
"playNotes": "Gateway chat now opens reliably on a cold launch. Saved Dashboard sign-ins stay bound to the correct connection, pasted credentials ignore accidental line breaks, and network changes no longer race the route cache. Bot Mode supports duplicate profile names across gateways, while delegated work, session setup, attachment errors, and feedback remain visible and easier to review.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.15.1",
|
||||
"title": "Steadier chat, media, and voice",
|
||||
"date": "2026-09-02",
|
||||
"summary": "Chats use less memory, attachment previews stay in place, and voice failures are easier to recover from. Follow-up controls make it clear whether a message changes the current response or waits for the next turn.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "follow-up-controls",
|
||||
"kind": "improved",
|
||||
"title": "Choose when follow-up messages are sent",
|
||||
"summary": "A slim tray behind the composer offers Correct now or Queue next. Chat settings sets the default, and a composer choice applies to one message. Stop pauses pending work until Resume; editing or removing an item keeps the remaining queue usable.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "tablet-layouts",
|
||||
"kind": "improved",
|
||||
"title": "Make better use of wider screens",
|
||||
"summary": "Chat and Voice keep text and controls on readable centered layouts. Landscape Voice Focus separates identity controls from conversation activity."
|
||||
},
|
||||
{
|
||||
"id": "delivery-labels",
|
||||
"kind": "fixed",
|
||||
"title": "Read message delivery status clearly",
|
||||
"summary": "Correction and delivery labels use contrasting text instead of disappearing into the message bubble."
|
||||
},
|
||||
{
|
||||
"id": "voice-error-dialog",
|
||||
"kind": "fixed",
|
||||
"title": "Read and dismiss voice errors",
|
||||
"summary": "Voice errors open in a contained dialog with scrollable details and separate Retry and Dismiss actions, without overlapping chat controls."
|
||||
},
|
||||
{
|
||||
"id": "attachment-previews",
|
||||
"kind": "fixed",
|
||||
"title": "Keep attachment previews open through rotation",
|
||||
"summary": "Image, video, audio, PDF, text, and file previews stay open as the screen rotates. Videos retain their original proportions.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "wake-word-startup",
|
||||
"kind": "fixed",
|
||||
"title": "Fix wake-word startup in release builds",
|
||||
"summary": "Release optimization now preserves the native speech configuration names needed to initialize wake-word detection."
|
||||
},
|
||||
{
|
||||
"id": "attachment-downloads",
|
||||
"kind": "fixed",
|
||||
"title": "Download attachments with less memory",
|
||||
"summary": "Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced."
|
||||
},
|
||||
{
|
||||
"id": "chat-memory-safety",
|
||||
"kind": "fixed",
|
||||
"title": "Keep large chats and media manageable",
|
||||
"summary": "Automatic session refresh no longer loops. Routine history loads, chat rendering, image previews, and media exports use bounded memory instead of allocating entire large responses.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "image-progress",
|
||||
"kind": "fixed",
|
||||
"title": "Keep image-generation progress visible",
|
||||
"summary": "The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events."
|
||||
},
|
||||
{
|
||||
"id": "first-message-readiness",
|
||||
"kind": "fixed",
|
||||
"title": "Wait for new chats to be ready",
|
||||
"summary": "The first message waits for the Gateway session to initialize. Ownership refusals keep the prompt retryable and show the server's error."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, media, and voice continue to use upstream Hermes. Voice transcription still requires a configured speech-to-text provider on the Hermes host.",
|
||||
"Paused text queues can be restored. Attachment bytes are not stored in preferences; an attachment queue that cannot be restored must be reviewed and sent again."
|
||||
],
|
||||
"playNotes": "More reliable chats and media: fewer memory-heavy refreshes, smoother large histories, and attachment previews that survive rotation. Choose whether follow-ups correct the current response or wait in a queue. Voice errors are easier to read, image-generation progress stays visible, and wake-word startup and first-message readiness are fixed.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.15.0",
|
||||
"title": "Standard Hermes first, with clearer Relay boundaries",
|
||||
"date": "2026-08-31",
|
||||
"summary": "Chat, voice, attachments, inbound files, current-session Git, usage, and Hermes notices now prefer current upstream Dashboard and Gateway support. Relay stays optional for compatibility and the tools it uniquely provides.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "upstream-standard-surfaces",
|
||||
"kind": "improved",
|
||||
"title": "Use standard Hermes without Relay prompts",
|
||||
"summary": "Chat attachments, inbound files, current-session Git, Nous usage, and Hermes notices use upstream routes first.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "stable-inbound-media",
|
||||
"kind": "fixed",
|
||||
"title": "Keep returned files loaded",
|
||||
"summary": "Images, audio, video, and documents download through the Dashboard and no longer flash Relay errors or return to Loading.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "supervised-parent-access",
|
||||
"kind": "improved",
|
||||
"title": "Use app-specific parent access",
|
||||
"summary": "A parent PIN or password plus recovery phrase protects Supervised Mode without trusting the phone unlock credential.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "settings-relay-boundaries",
|
||||
"kind": "improved",
|
||||
"title": "See which features need Relay",
|
||||
"summary": "Media sits with standard Hermes settings while Threads, Terminal, notifications, enhanced voice, and device tools stay under Relay tools."
|
||||
},
|
||||
{
|
||||
"id": "complete-release-history",
|
||||
"kind": "improved",
|
||||
"title": "Read the complete release record",
|
||||
"summary": "What's New shows one release summary, selected highlights, every remaining change, and relevant compatibility notes."
|
||||
},
|
||||
{
|
||||
"id": "relay-removal-voice",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Standard voice after removing Relay",
|
||||
"summary": "Dashboard voice remains ready, temporary outages preserve choices, and shared default-profile settings stay isolated."
|
||||
},
|
||||
{
|
||||
"id": "passive-external-activity",
|
||||
"kind": "fixed",
|
||||
"title": "Observe another client's activity safely",
|
||||
"summary": "A uniquely matched Desktop or TUI turn can show Working or Waiting without Android taking control."
|
||||
},
|
||||
{
|
||||
"id": "chat-transport-ownership",
|
||||
"kind": "fixed",
|
||||
"title": "Keep each chat on its chosen transport",
|
||||
"summary": "Dashboard chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing databases."
|
||||
},
|
||||
{
|
||||
"id": "history-auth-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Preserve completed replies at sign-in expiry",
|
||||
"summary": "A Dashboard history authentication failure keeps completed text visible and opens the existing sign-in recovery path."
|
||||
},
|
||||
{
|
||||
"id": "compaction-watchdog",
|
||||
"kind": "fixed",
|
||||
"title": "Let long context compaction finish",
|
||||
"summary": "Visible compaction activity refreshes the turn watchdog instead of being interrupted as idle."
|
||||
},
|
||||
{
|
||||
"id": "bot-chat-binding",
|
||||
"kind": "fixed",
|
||||
"title": "Render Bot Chat history immediately",
|
||||
"summary": "Route-owned Bot Chats observe their bound history from first composition."
|
||||
},
|
||||
{
|
||||
"id": "missing-terminal-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Settle turns after a lost terminal frame",
|
||||
"summary": "An exact idle live-session snapshot reconciles the Android-owned turn and drains its queued follow-up."
|
||||
},
|
||||
{
|
||||
"id": "supervised-gateway-setup",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Gateway setup parent-owned",
|
||||
"summary": "Relock and back navigation cancel the exact pending setup without bypassing parent authority."
|
||||
},
|
||||
{
|
||||
"id": "generated-image-retention",
|
||||
"kind": "fixed",
|
||||
"title": "Keep completed generated images visible",
|
||||
"summary": "Generated media survives marker persistence lag and retains its intended Chat animation."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Current upstream Hermes provides standard Chat, sessions, Manage, voice, attachments, inbound files, current-session Git reads, usage, and notices without the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.1 remains required for Terminal, proactive Threads and offline delivery, Notification Companion, Relay sessions, enhanced voice, Secure Link, and phone or device control.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain sideload-only."
|
||||
],
|
||||
"playNotes": "Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.14.0",
|
||||
"title": "Connections, delegated work, Git, and voice",
|
||||
"date": "2026-08-30",
|
||||
"summary": "Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "route-aware-connections",
|
||||
"kind": "improved",
|
||||
"title": "Connections recover independently",
|
||||
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "delegated-agent-previews",
|
||||
"kind": "added",
|
||||
"title": "Follow delegated-agent activity",
|
||||
"summary": "See lifecycle, progress, tool previews, and available read-only child history from the parent chat.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "native-git-workspace",
|
||||
"kind": "added",
|
||||
"title": "Work with repositories from Android",
|
||||
"summary": "Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "voice-focus-controls",
|
||||
"kind": "improved",
|
||||
"title": "Steer voice at any time",
|
||||
"summary": "Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "non-blocking-release-notice",
|
||||
"kind": "improved",
|
||||
"title": "Release notes stay out of your way",
|
||||
"summary": "A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings."
|
||||
},
|
||||
{
|
||||
"id": "single-chat-presentation",
|
||||
"kind": "improved",
|
||||
"title": "Chat uses one consistent presentation",
|
||||
"summary": "The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available."
|
||||
},
|
||||
{
|
||||
"id": "wake-word-runtime",
|
||||
"kind": "fixed",
|
||||
"title": "Wake-word detection starts reliably",
|
||||
"summary": "Compatible native voice components are now packaged for every supported phone architecture."
|
||||
},
|
||||
{
|
||||
"id": "sphere-motion",
|
||||
"kind": "fixed",
|
||||
"title": "The visible Sphere keeps moving smoothly",
|
||||
"summary": "Foreground animation no longer falls back to a stepped ambient pulse."
|
||||
},
|
||||
{
|
||||
"id": "continuous-microphone-handoff",
|
||||
"kind": "fixed",
|
||||
"title": "Continuous voice keeps the microphone",
|
||||
"summary": "The next listening turn waits for barge-in recording to release cleanly."
|
||||
},
|
||||
{
|
||||
"id": "fresh-profile-drafts",
|
||||
"kind": "fixed",
|
||||
"title": "New chats keep the selected profile",
|
||||
"summary": "Fresh drafts no longer reopen an older session or carry a Thread route into another profile."
|
||||
},
|
||||
{
|
||||
"id": "provisional-thread-removal",
|
||||
"kind": "fixed",
|
||||
"title": "Provisional Threads can be removed safely",
|
||||
"summary": "Local removal and later session promotion no longer risk duplicate rows or server history."
|
||||
},
|
||||
{
|
||||
"id": "clarify-custom-answers",
|
||||
"kind": "fixed",
|
||||
"title": "Clarify keeps custom answers reachable",
|
||||
"summary": "Other answers, keyboard Send, and expired prompts now behave consistently."
|
||||
},
|
||||
{
|
||||
"id": "passive-session-observation",
|
||||
"kind": "fixed",
|
||||
"title": "Browsing no longer interrupts another client",
|
||||
"summary": "Passive Android observation does not claim a turn owned by Desktop, TUI, or another client."
|
||||
},
|
||||
{
|
||||
"id": "assistant-recovery-privacy",
|
||||
"kind": "fixed",
|
||||
"title": "Assistant sessions recover more clearly",
|
||||
"summary": "No-speech feedback, recreated session state, and keyguard privacy now remain intact."
|
||||
},
|
||||
{
|
||||
"id": "relay-auth-boundaries",
|
||||
"kind": "fixed",
|
||||
"title": "Protected Relay routes report the right problem",
|
||||
"summary": "Authentication challenges are no longer presented as outages, while unsafe routes still fail closed."
|
||||
},
|
||||
{
|
||||
"id": "connection-session-readiness",
|
||||
"kind": "fixed",
|
||||
"title": "Connections and sessions become ready sooner",
|
||||
"summary": "Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.",
|
||||
"The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain available only in the sideload build."
|
||||
],
|
||||
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.13.2",
|
||||
"title": "Supervised Mode and clearer activity",
|
||||
"date": "2026-08-25",
|
||||
"highlight": {
|
||||
"title": "Supervised Mode",
|
||||
"summary": "Create a simpler, profile-focused chat and choose which features remain available.",
|
||||
"bullets": [
|
||||
"Protect parent settings with your phone's device authentication.",
|
||||
"Choose access to attachments, Standard voice, generated media, history, actions, and technical details.",
|
||||
"Keep Supervised Chat open when returning from parent settings."
|
||||
]
|
||||
},
|
||||
"improvements": [
|
||||
"Activity indicators now appear only while Hermes is genuinely working."
|
||||
],
|
||||
"toastDigest": {
|
||||
"additionalFeatureCount": 0,
|
||||
"fixCount": 2,
|
||||
"preview": [
|
||||
"Accurate activity",
|
||||
"safer return"
|
||||
]
|
||||
},
|
||||
"playNotes": "Supervised Mode creates a simpler, profile-focused chat with device-protected parent settings and control over attachments, Standard voice, generated media, history, actions, and technical details. Activity indicators now appear only while Hermes is genuinely working, and returning from parent settings keeps Supervised Chat open.",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Use a supervised chat",
|
||||
"bullets": [
|
||||
"Configure a profile-pinned restricted chat with parent-controlled attachments, voice, media, history, actions, and technical details.",
|
||||
"Protect full settings with device authentication and keep Supervised Chat visible when parent access relocks."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Show only confirmed activity",
|
||||
"bullets": [
|
||||
"Keep session rows neutral while optional live activity is unavailable or still loading.",
|
||||
"Show full-row activity borders only during actual Starting or Working turns."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.13.1",
|
||||
"title": "Accurate session activity",
|
||||
"date": "2026-08-25",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Follow live Hermes state",
|
||||
"bullets": [
|
||||
"Show Working, Starting, Needs input, Idle, Checking, Unavailable, and Background work from live runtime state instead of a recent-activity estimate.",
|
||||
"Keep stale activity visible until a complete, unambiguous snapshot safely clears it."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.13.0",
|
||||
"title": "Bots, usage, and reliable chat",
|
||||
"date": "2026-08-25",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Talk across saved gateways",
|
||||
"bullets": [
|
||||
"Use Bot Mode as one messenger-style workspace for bots and read-only groups across saved Hermes gateways.",
|
||||
"Keep every Bot Chat bound to its exact gateway and profile without changing the foreground connection."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Understand account limits",
|
||||
"bullets": [
|
||||
"Review Codex credential pools, Nous balances, and OpenCode Go windows from one provider-neutral Usage and limits screen.",
|
||||
"Choose Summary, Expanded, or Hidden presentation while provider credentials remain on the Hermes host."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Keep chat and voice in context",
|
||||
"bullets": [
|
||||
"Settle orphaned Gateway busy state automatically while preserving another session's active or detached turn.",
|
||||
"Include bounded visible text and an available screenshot in the first compatible Assistant voice turn."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.12.1",
|
||||
"title": "Sharing and recovery that work",
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
v1.12.1 - Sharing and recovery that work
|
||||
v1.17.0 - Voice over other apps and clearer conversations
|
||||
|
||||
* Open shared links, text, images, and files as a reviewable draft without auto-sending.
|
||||
* Add or renew a connection without getting stuck during secure setup.
|
||||
* See clear recovery guidance when chat or profile history is unavailable.
|
||||
* Find secret-free secure-storage fallback and recovery evidence in Diagnostics.
|
||||
Summary
|
||||
* Google Play gains optional voice controls over other apps. Clarify questions, profile names, and chat context are easier to follow without losing confirmed answers or saved conversations.
|
||||
|
||||
Highlights
|
||||
* Keep voice controls over other apps — Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Stop voice from its controls or persistent notification; screen lock and permission loss end the session.
|
||||
* Answer Clarify questions one at a time — Multi-question requests support separate choices and custom answers. Confirmed progress survives reconnects, and failed sends keep the current answer available.
|
||||
* Recognize profiles by their display names — Profiles use their Hermes display names, and the resolved server default appears under its agent identity. Explicit profile choices and saved conversations are preserved.
|
||||
|
||||
Improved
|
||||
* Read cleaner chat cards — Standalone response cards lose the extra outer bubble, assistant messages use quieter surfaces, and delivery status sits beside the timestamp.
|
||||
|
||||
Fixed
|
||||
* See which context your chat can send — Gateway previews mark phone status and turn context as unavailable. Automatic phone-status sharing is labeled for API-only chats, where it remains supported.
|
||||
|
||||
Compatibility
|
||||
* Voice Overlay is now available in Google Play and sideload builds. Device Control remains sideload-only.
|
||||
* Standard Chat and voice use upstream Hermes without requiring Hermes-Relay Plugin. Gateway phone-status delivery and automatic Android identification remain unavailable.
|
||||
|
||||
@@ -13,10 +13,15 @@ import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||
import coil3.request.crossfade
|
||||
import com.hermesandroid.relay.bridge.UnattendedAccessManager
|
||||
import com.hermesandroid.relay.data.AppAnalytics
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.power.WakeLockManager
|
||||
import com.hermesandroid.relay.runtime.HermesProcessRuntime
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceNightMode
|
||||
import com.hermesandroid.relay.util.AppForegroundTracker
|
||||
import com.hermesandroid.relay.util.CrashReporter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
|
||||
@@ -57,6 +62,10 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
// Install the crash handler FIRST so any failure in the rest of app
|
||||
// init (or anywhere later) is captured and surfaced on next launch.
|
||||
CrashReporter.install(this)
|
||||
// Apply saved Light/Dark/Auto before the first Activity frame so DayNight
|
||||
// does not briefly follow the system when Appearance is explicitly Light.
|
||||
// Bounded + best-effort: HermesRelayTheme SideEffect is the durable path.
|
||||
applyPersistedAppearanceNightMode()
|
||||
AppAnalytics.initialize(this)
|
||||
// A8 — wire the bridge-gesture wake-lock wrapper so
|
||||
// ActionExecutor.tap/tapText/typeText/swipe/scroll can hold
|
||||
@@ -76,6 +85,19 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
AppForegroundTracker.initialize()
|
||||
}
|
||||
|
||||
private fun applyPersistedAppearanceNightMode() {
|
||||
try {
|
||||
runBlocking {
|
||||
val preferences = withTimeoutOrNull(400L) {
|
||||
relayDataStore.data.first()
|
||||
} ?: return@runBlocking
|
||||
AppearanceNightMode.applyFromPreferences(preferences)
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// Non-fatal — theme root reapplies once DataStore is ready.
|
||||
}
|
||||
}
|
||||
|
||||
private fun isMainApplicationProcess(): Boolean {
|
||||
val processName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
getProcessName()
|
||||
|
||||
@@ -39,14 +39,38 @@ enum class AssistantSessionPhase {
|
||||
Closed,
|
||||
}
|
||||
|
||||
enum class AssistantSessionNotice {
|
||||
NoSpeech,
|
||||
}
|
||||
|
||||
data class AssistantSessionSnapshot(
|
||||
val phase: AssistantSessionPhase = AssistantSessionPhase.Launching,
|
||||
val transcript: String? = null,
|
||||
val response: String = "",
|
||||
val notice: AssistantSessionNotice? = null,
|
||||
val error: String? = null,
|
||||
val screenContextSupported: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun assistantSnapshotForPresentation(
|
||||
snapshot: AssistantSessionSnapshot,
|
||||
locked: Boolean,
|
||||
): AssistantSessionSnapshot = if (locked) {
|
||||
snapshot.copy(
|
||||
transcript = null,
|
||||
response = "",
|
||||
error = null,
|
||||
screenContextSupported = false,
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
}
|
||||
|
||||
internal fun assistantSnapshotMatchesActivation(
|
||||
expectedActivationId: String?,
|
||||
receivedActivationId: String?,
|
||||
): Boolean = expectedActivationId != null && expectedActivationId == receivedActivationId
|
||||
|
||||
object AssistantRole {
|
||||
fun status(context: Context): AssistantRoleStatus {
|
||||
val component = ComponentName(context, HermesVoiceInteractionService::class.java)
|
||||
@@ -209,6 +233,7 @@ object AssistantSessionProtocol {
|
||||
onFailure = { failure ->
|
||||
publish(
|
||||
application,
|
||||
activation.id,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = failure.message ?: "Hermes voice could not start",
|
||||
@@ -219,13 +244,19 @@ object AssistantSessionProtocol {
|
||||
return true
|
||||
}
|
||||
|
||||
fun publish(context: Context, snapshot: AssistantSessionSnapshot) {
|
||||
fun publish(
|
||||
context: Context,
|
||||
activationId: String,
|
||||
snapshot: AssistantSessionSnapshot,
|
||||
) {
|
||||
context.sendBroadcast(
|
||||
Intent(context, AssistantSessionStateReceiver::class.java).apply {
|
||||
action = ACTION_STATUS
|
||||
putExtra(EXTRA_ACTIVATION_ID, activationId)
|
||||
putExtra(EXTRA_PHASE, snapshot.phase.name)
|
||||
putExtra(EXTRA_TRANSCRIPT, snapshot.transcript)
|
||||
putExtra(EXTRA_RESPONSE, snapshot.response)
|
||||
putExtra(EXTRA_NOTICE, snapshot.notice?.name)
|
||||
putExtra(EXTRA_ERROR, snapshot.error)
|
||||
putExtra(EXTRA_SCREEN_CONTEXT_SUPPORTED, snapshot.screenContextSupported)
|
||||
}
|
||||
@@ -238,10 +269,6 @@ object AssistantSessionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(context: Context, state: VoiceUiState) {
|
||||
publish(context, snapshotFromVoiceState(state))
|
||||
}
|
||||
|
||||
internal fun snapshotFromVoiceState(state: VoiceUiState): AssistantSessionSnapshot {
|
||||
val phase = when {
|
||||
!state.voiceMode -> AssistantSessionPhase.Closed
|
||||
@@ -256,7 +283,10 @@ object AssistantSessionProtocol {
|
||||
phase = phase,
|
||||
transcript = state.transcribedText?.take(MAX_SESSION_TEXT_CHARS),
|
||||
response = state.responseText.take(MAX_SESSION_TEXT_CHARS),
|
||||
error = state.error?.take(MAX_SESSION_ERROR_CHARS),
|
||||
notice = state.assistantNotice,
|
||||
error = state.error
|
||||
?.takeIf { phase == AssistantSessionPhase.Error }
|
||||
?.take(MAX_SESSION_ERROR_CHARS),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -350,6 +380,9 @@ object AssistantSessionProtocol {
|
||||
phase = phase,
|
||||
transcript = intent.getStringExtra(EXTRA_TRANSCRIPT),
|
||||
response = intent.getStringExtra(EXTRA_RESPONSE).orEmpty(),
|
||||
notice = intent.getStringExtra(EXTRA_NOTICE)?.let { raw ->
|
||||
runCatching { AssistantSessionNotice.valueOf(raw) }.getOrNull()
|
||||
},
|
||||
error = intent.getStringExtra(EXTRA_ERROR),
|
||||
screenContextSupported = intent.getBooleanExtra(
|
||||
EXTRA_SCREEN_CONTEXT_SUPPORTED,
|
||||
@@ -360,24 +393,33 @@ object AssistantSessionProtocol {
|
||||
|
||||
private const val MAX_SESSION_TEXT_CHARS = 4_000
|
||||
private const val MAX_SESSION_ERROR_CHARS = 1_000
|
||||
private const val EXTRA_NOTICE = "notice"
|
||||
}
|
||||
|
||||
object AssistantSessionState {
|
||||
private val _snapshot = MutableStateFlow(AssistantSessionSnapshot())
|
||||
val snapshot: StateFlow<AssistantSessionSnapshot> = _snapshot.asStateFlow()
|
||||
@Volatile private var activationId: String? = null
|
||||
|
||||
internal fun update(snapshot: AssistantSessionSnapshot) {
|
||||
internal fun update(receivedActivationId: String?, snapshot: AssistantSessionSnapshot) {
|
||||
if (!assistantSnapshotMatchesActivation(activationId, receivedActivationId)) return
|
||||
_snapshot.value = snapshot
|
||||
}
|
||||
|
||||
internal fun reset() {
|
||||
internal fun reset(activationId: String) {
|
||||
this.activationId = activationId
|
||||
_snapshot.value = AssistantSessionSnapshot()
|
||||
}
|
||||
}
|
||||
|
||||
class AssistantSessionStateReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
AssistantSessionState.update(AssistantSessionProtocol.readSnapshot(intent))
|
||||
AssistantSessionState.update(
|
||||
receivedActivationId = intent.getStringExtra(
|
||||
AssistantSessionProtocol.EXTRA_ACTIVATION_ID
|
||||
),
|
||||
snapshot = AssistantSessionProtocol.readSnapshot(intent),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,6 +465,7 @@ class AssistantSessionLifecycleReceiver : BroadcastReceiver() {
|
||||
onFailure = { failure ->
|
||||
AssistantSessionProtocol.publish(
|
||||
application,
|
||||
id,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = failure.message ?: "Hermes voice could not start",
|
||||
@@ -430,6 +473,7 @@ class AssistantSessionLifecycleReceiver : BroadcastReceiver() {
|
||||
)
|
||||
},
|
||||
)
|
||||
application.runtime.republishAssistantSnapshot(id)
|
||||
return
|
||||
}
|
||||
if (AssistantSessionProtocol.isStartAction(intent.action)) {
|
||||
|
||||
@@ -3,6 +3,11 @@ package com.hermesandroid.relay.assistant
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.app.KeyguardManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
@@ -67,6 +72,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
@@ -108,6 +114,11 @@ internal fun shouldCancelVoiceWhenSessionUiEnds(
|
||||
presentation: AssistantSessionPresentation,
|
||||
): Boolean = presentation == AssistantSessionPresentation.Overlay
|
||||
|
||||
internal fun assistantPresentationLocked(
|
||||
currentKeyguardLocked: Boolean?,
|
||||
fallbackLocked: Boolean,
|
||||
): Boolean = currentKeyguardLocked ?: fallbackLocked
|
||||
|
||||
private class HermesVoiceInteractionSession(
|
||||
private val service: HermesVoiceInteractionSessionService,
|
||||
) : VoiceInteractionSession(service) {
|
||||
@@ -118,12 +129,19 @@ private class HermesVoiceInteractionSession(
|
||||
private var surfaceExpanded by mutableStateOf(false)
|
||||
private var activationId: String? = null
|
||||
private var manualMic = false
|
||||
private var keyguardLocked by mutableStateOf(false)
|
||||
private var expectScreenContext: Boolean? = null
|
||||
private var pendingSemantic = AssistantSemanticContext()
|
||||
private var pendingScreenshot: ByteArray? = null
|
||||
private var screenContextUi by mutableStateOf(AssistantScreenContextUi())
|
||||
private val contextStore = assistantContextStore(service)
|
||||
private var heartbeatJob: Job? = null
|
||||
private var keyguardReceiverRegistered = false
|
||||
private val keyguardReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
refreshKeyguardState()
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
@@ -139,6 +157,17 @@ private class HermesVoiceInteractionSession(
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
ContextCompat.registerReceiver(
|
||||
service,
|
||||
keyguardReceiver,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
keyguardReceiverRegistered = true
|
||||
window.window?.apply {
|
||||
setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
|
||||
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
|
||||
@@ -155,6 +184,7 @@ private class HermesVoiceInteractionSession(
|
||||
PersistedHermesRelayTheme {
|
||||
AssistantSessionSurface(
|
||||
expanded = surfaceExpanded,
|
||||
locked = keyguardLocked,
|
||||
screenContext = screenContextUi,
|
||||
onExpandedChange = { surfaceExpanded = it },
|
||||
onCancel = { finishSession(cancelVoice = true) },
|
||||
@@ -183,11 +213,22 @@ private class HermesVoiceInteractionSession(
|
||||
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
if (args?.getBoolean(HermesVoiceInteractionService.EXTRA_FROM_KEYGUARD, false) == true) {
|
||||
refreshKeyguardState(
|
||||
fallbackLocked = args?.getBoolean(
|
||||
HermesVoiceInteractionService.EXTRA_FROM_KEYGUARD,
|
||||
false,
|
||||
) == true,
|
||||
)
|
||||
if (keyguardLocked) {
|
||||
window.window?.addFlags(
|
||||
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
|
||||
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
|
||||
)
|
||||
} else {
|
||||
window.window?.clearFlags(
|
||||
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
|
||||
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
|
||||
)
|
||||
}
|
||||
setUiEnabled(true)
|
||||
val startsNewLifecycle = presentation == AssistantSessionPresentation.Inactive
|
||||
@@ -195,10 +236,10 @@ private class HermesVoiceInteractionSession(
|
||||
if (!startsNewLifecycle) return
|
||||
|
||||
surfaceExpanded = false
|
||||
AssistantSessionState.reset()
|
||||
screenContextUi = AssistantScreenContextUi()
|
||||
activationId = args?.getString(AssistantSessionProtocol.EXTRA_ACTIVATION_ID)
|
||||
?: UUID.randomUUID().toString()
|
||||
AssistantSessionState.reset(activationId!!)
|
||||
manualMic = args?.getBoolean(AssistantSessionProtocol.EXTRA_MANUAL_MIC, false) ?: false
|
||||
expectScreenContext = args?.getBoolean(
|
||||
AssistantSessionProtocol.EXTRA_EXPECT_SCREEN_CONTEXT,
|
||||
@@ -300,6 +341,10 @@ private class HermesVoiceInteractionSession(
|
||||
pendingSemantic = AssistantSemanticContext()
|
||||
pendingScreenshot = null
|
||||
screenContextUi = AssistantScreenContextUi()
|
||||
if (keyguardReceiverRegistered) {
|
||||
runCatching { service.unregisterReceiver(keyguardReceiver) }
|
||||
keyguardReceiverRegistered = false
|
||||
}
|
||||
viewOwner.stop()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
@@ -319,6 +364,7 @@ private class HermesVoiceInteractionSession(
|
||||
)
|
||||
}.onFailure {
|
||||
AssistantSessionState.update(
|
||||
activationId,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = it.message ?: "Hermes could not open the voice session.",
|
||||
@@ -337,6 +383,7 @@ private class HermesVoiceInteractionSession(
|
||||
setUiEnabled(false)
|
||||
}.onFailure {
|
||||
AssistantSessionState.update(
|
||||
activationId,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = it.message ?: "Hermes could not open full voice.",
|
||||
@@ -377,6 +424,14 @@ private class HermesVoiceInteractionSession(
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshKeyguardState(fallbackLocked: Boolean = keyguardLocked) {
|
||||
keyguardLocked = assistantPresentationLocked(
|
||||
currentKeyguardLocked = service.getSystemService(KeyguardManager::class.java)
|
||||
?.isKeyguardLocked,
|
||||
fallbackLocked = fallbackLocked,
|
||||
)
|
||||
}
|
||||
|
||||
@RequiresApi(android.os.Build.VERSION_CODES.Q)
|
||||
private fun stageAssistState(state: AssistState) {
|
||||
stageAssistData(state.assistStructure, state.assistContent)
|
||||
@@ -463,6 +518,7 @@ private class AssistantSessionViewOwner :
|
||||
@Composable
|
||||
private fun AssistantSessionSurface(
|
||||
expanded: Boolean,
|
||||
locked: Boolean,
|
||||
screenContext: AssistantScreenContextUi,
|
||||
onExpandedChange: (Boolean) -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
@@ -471,7 +527,8 @@ private fun AssistantSessionSurface(
|
||||
onOpenFullVoice: () -> Unit,
|
||||
onSurfaceBoundsChanged: (android.graphics.Rect) -> Unit,
|
||||
) {
|
||||
val snapshot by AssistantSessionState.snapshot.collectAsState()
|
||||
val rawSnapshot by AssistantSessionState.snapshot.collectAsState()
|
||||
val snapshot = assistantSnapshotForPresentation(rawSnapshot, locked)
|
||||
val status = assistantStatus(snapshot.phase)
|
||||
val transmittedScreenContext = if (snapshot.screenContextSupported) {
|
||||
screenContext
|
||||
@@ -650,6 +707,13 @@ private fun ExpandedAssistantSurface(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
snapshot.notice?.let { notice ->
|
||||
Text(
|
||||
text = assistantNoticeText(notice),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
snapshot.error?.let { error ->
|
||||
Text(
|
||||
text = error,
|
||||
@@ -896,5 +960,11 @@ private fun assistantStatus(phase: AssistantSessionPhase): String = when (phase)
|
||||
private fun compactAssistantText(snapshot: AssistantSessionSnapshot): String =
|
||||
snapshot.transcript?.takeIf { it.isNotBlank() }
|
||||
?: snapshot.response.takeIf { it.isNotBlank() }
|
||||
?: snapshot.notice?.let { assistantNoticeText(it) }
|
||||
?: snapshot.error?.takeIf { it.isNotBlank() }
|
||||
?: assistantStatus(snapshot.phase)
|
||||
|
||||
@Composable
|
||||
private fun assistantNoticeText(notice: AssistantSessionNotice): String = when (notice) {
|
||||
AssistantSessionNotice.NoSpeech -> stringResource(R.string.voice_no_speech_try_again)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ 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.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.isSafeProfileUiMeta
|
||||
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
@@ -18,6 +19,8 @@ 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.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
@@ -53,6 +56,39 @@ sealed class AuthState {
|
||||
data class Failed(val reason: String) : AuthState()
|
||||
}
|
||||
|
||||
internal fun relaySupervisedModePayload(policy: SupervisedModePolicy): JsonObject {
|
||||
if (!policy.isActive) return buildJsonObject { put("active", false) }
|
||||
val capabilities = buildList {
|
||||
add("text_chat")
|
||||
if (policy.capabilities.newChat) add("new_chat")
|
||||
if (policy.capabilities.cancelResponse) add("cancel")
|
||||
if (policy.capabilities.steerResponse) add("steer")
|
||||
if (policy.capabilities.attachments) add("attachments")
|
||||
if (policy.capabilities.voice) add("voice")
|
||||
if (policy.capabilities.generatedImages) add("generated_images")
|
||||
if (policy.capabilities.shareGeneratedImages) add("share_images")
|
||||
if (policy.capabilities.copyResponses) add("copy")
|
||||
if (policy.capabilities.retryResponse) add("retry")
|
||||
if (policy.capabilities.quoteReplies) add("quote_reply")
|
||||
if (policy.visibility.resolved().showTimestamps) add("timestamps")
|
||||
}.take(12)
|
||||
return buildJsonObject {
|
||||
put("active", true)
|
||||
put("profile_label", policy.pinnedProfileName.orEmpty().take(80))
|
||||
put("capabilities", JsonArray(capabilities.map(::JsonPrimitive)))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun relaySupervisedModeUpdateEnvelope(
|
||||
policy: SupervisedModePolicy,
|
||||
): Envelope = Envelope(
|
||||
channel = "system",
|
||||
type = "supervised.update",
|
||||
payload = buildJsonObject {
|
||||
put("supervised_mode", relaySupervisedModePayload(policy))
|
||||
},
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ConnectionAuthSecrets(
|
||||
val sessionToken: String? = null,
|
||||
@@ -120,6 +156,60 @@ class AuthManager(
|
||||
private val eagerHydrate: Boolean = true,
|
||||
) : ChannelMultiplexer.ChannelHandler {
|
||||
|
||||
@Volatile
|
||||
private var supervisedMode: SupervisedModePolicy = SupervisedModePolicy()
|
||||
|
||||
@Volatile
|
||||
private var supervisedMetadataReconnectFallback: (() -> Unit)? = null
|
||||
private var pendingSupervisedUpdateId: String? = null
|
||||
private var supervisedUpdateFallbackJob: Job? = null
|
||||
|
||||
/**
|
||||
* Update the public client-mode tag sent on Relay auth. This does not grant
|
||||
* authority: Relay labels enforcement_owner=android_client and the Android
|
||||
* policy remains the enforcing surface.
|
||||
*/
|
||||
fun updateSupervisedMode(policy: SupervisedModePolicy) {
|
||||
if (supervisedMode == policy) return
|
||||
supervisedMode = policy
|
||||
if (_authState.value is AuthState.Paired) sendSupervisedModeUpdate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the narrow compatibility path used when an older Relay ignores
|
||||
* `system/supervised.update`. Reopening the authenticated socket causes
|
||||
* the current policy to travel through the legacy `system/auth` payload.
|
||||
*/
|
||||
fun setSupervisedMetadataReconnectFallback(callback: () -> Unit) {
|
||||
supervisedMetadataReconnectFallback = callback
|
||||
}
|
||||
|
||||
private fun sendSupervisedModeUpdate() {
|
||||
val envelope = relaySupervisedModeUpdateEnvelope(supervisedMode)
|
||||
pendingSupervisedUpdateId = envelope.id
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
multiplexer.send(envelope)
|
||||
supervisedUpdateFallbackJob = scope.launch {
|
||||
delay(SUPERVISED_UPDATE_ACK_TIMEOUT_MS)
|
||||
if (pendingSupervisedUpdateId == envelope.id) {
|
||||
pendingSupervisedUpdateId = null
|
||||
Log.i(TAG, "supervised.update unsupported or unacknowledged; refreshing Relay socket")
|
||||
supervisedMetadataReconnectFallback?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun settleSupervisedModeUpdate(envelope: Envelope, unsupported: Boolean) {
|
||||
if (envelope.id != pendingSupervisedUpdateId) return
|
||||
pendingSupervisedUpdateId = null
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
supervisedUpdateFallbackJob = null
|
||||
if (unsupported) {
|
||||
Log.i(TAG, "supervised.update rejected; refreshing Relay socket for compatibility")
|
||||
supervisedMetadataReconnectFallback?.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AuthManager"
|
||||
private const val KEY_SESSION_TOKEN = "session_token"
|
||||
@@ -134,6 +224,7 @@ class AuthManager(
|
||||
// migration has run, so we never rebuild the legacy keyset to re-check.
|
||||
private const val KEY_LEGACY_MIGRATED = "legacy_migrated"
|
||||
private const val PAIRING_CODE_LENGTH = 6
|
||||
private const val SUPERVISED_UPDATE_ACK_TIMEOUT_MS = 2_000L
|
||||
private val PAIRING_CODE_CHARS = ('A'..'Z') + ('0'..'9')
|
||||
|
||||
/**
|
||||
@@ -835,6 +926,10 @@ class AuthManager(
|
||||
put("device_form_factor", "phone")
|
||||
}
|
||||
|
||||
private fun JsonObjectBuilder.putSupervisedMode() {
|
||||
put("supervised_mode", relaySupervisedModePayload(supervisedMode))
|
||||
}
|
||||
|
||||
private fun relayDeviceName(): String {
|
||||
val configured = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "device_name")
|
||||
@@ -890,6 +985,7 @@ class AuthManager(
|
||||
put("device_id", deviceId)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
putSupervisedMode()
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
@@ -898,7 +994,7 @@ class AuthManager(
|
||||
val serverSource = if (serverIssuedCode != null) "QR" else "local-fallback"
|
||||
Log.i(
|
||||
TAG,
|
||||
"authenticate: sending pairing_code=$codeToSend source=$serverSource " +
|
||||
"authenticate: sending pairing credential source=$serverSource " +
|
||||
"ttl=$pendingTtlSeconds grants=${pendingGrants?.keys}"
|
||||
)
|
||||
buildJsonObject {
|
||||
@@ -906,6 +1002,7 @@ class AuthManager(
|
||||
put("device_id", deviceId)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
putSupervisedMode()
|
||||
pendingTtlSeconds?.let { put("ttl_seconds", it) }
|
||||
pendingGrants?.let { grants ->
|
||||
val obj = buildJsonObject {
|
||||
@@ -966,7 +1063,8 @@ class AuthManager(
|
||||
_currentPairedSession.value = null
|
||||
Log.i(
|
||||
TAG,
|
||||
"applyServerIssuedCodeAndReset: code=$normalized relayUrl=$relayUrl " +
|
||||
"applyServerIssuedCodeAndReset: credential=present " +
|
||||
"relayConfigured=${!relayUrl.isNullOrBlank()} " +
|
||||
"prevState=${prevState::class.simpleName} → Unpaired"
|
||||
)
|
||||
scope.launch {
|
||||
@@ -985,6 +1083,8 @@ class AuthManager(
|
||||
when (envelope.type) {
|
||||
"auth.ok" -> handleAuthOk(envelope)
|
||||
"auth.fail" -> handleAuthFail(envelope)
|
||||
"supervised.updated" -> settleSupervisedModeUpdate(envelope, unsupported = false)
|
||||
"error" -> settleSupervisedModeUpdate(envelope, unsupported = true)
|
||||
// `profiles.updated` push — sent by the v0.7.1+ relay on
|
||||
// the "pairing" channel whenever its in-memory profile
|
||||
// snapshot changes (file-watcher, SIGHUP, or a manual
|
||||
@@ -1129,6 +1229,11 @@ class AuthManager(
|
||||
get() = _authState.value is AuthState.Paired
|
||||
|
||||
private fun handleAuthOk(envelope: Envelope) {
|
||||
// A successful auth always carries the latest client report, including
|
||||
// after the compatibility reconnect used for older Relay versions.
|
||||
pendingSupervisedUpdateId = null
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
supervisedUpdateFallbackJob = null
|
||||
scope.launch {
|
||||
try {
|
||||
val payload = envelope.payload
|
||||
|
||||
@@ -10,6 +10,16 @@ package com.hermesandroid.relay.data
|
||||
*/
|
||||
object AgentDisplay {
|
||||
const val SERVER_DEFAULT_PROFILE_KEY: String = "__server_default__"
|
||||
private const val PROFILE_CONTEXT_SEPARATOR = "::"
|
||||
|
||||
data class ProfileContextIdentity(
|
||||
val connectionId: String,
|
||||
val profileKey: String,
|
||||
) {
|
||||
/** Null means the upstream request must inherit Server Default. */
|
||||
val requestProfileName: String?
|
||||
get() = profileRequestName(profileKey)
|
||||
}
|
||||
private val GENERIC_MODEL_ALIASES = setOf(
|
||||
"hermes-agent",
|
||||
"hermes_agent",
|
||||
@@ -24,9 +34,7 @@ object AgentDisplay {
|
||||
profiles: List<Profile>,
|
||||
): Profile? = selectedProfile
|
||||
|
||||
// Display can use the root default profile's metadata without making it a
|
||||
// request/session override. Verbose SOUL summaries are filtered by
|
||||
// profileDisplayName below, so this is safe for headers/cards.
|
||||
// Display resolution never changes selection or persistence identity.
|
||||
fun effectiveDisplayProfile(
|
||||
selectedProfile: Profile?,
|
||||
profiles: List<Profile>,
|
||||
@@ -34,36 +42,22 @@ object AgentDisplay {
|
||||
): Profile? {
|
||||
selectedProfile?.let { return it }
|
||||
val resolvedServerDefault = profileRequestName(serverDefaultProfileName)
|
||||
return resolvedServerDefault
|
||||
?.let { activeName ->
|
||||
profiles.firstOrNull { it.name.equals(activeName, ignoreCase = true) }
|
||||
}
|
||||
?: profiles.firstOrNull { it.name.equals("default", ignoreCase = true) }
|
||||
// An absent roster row is not authority to substitute the root profile.
|
||||
// Retain the confirmed name while its display metadata is loading.
|
||||
return resolvedServerDefault?.let { activeName ->
|
||||
profiles.firstOrNull { it.name == activeName }
|
||||
?: Profile(name = activeName, model = "")
|
||||
}
|
||||
}
|
||||
|
||||
// The NAME goes in the name slot. Non-default profiles use their profile
|
||||
// name first. The synthetic default profile uses its description only when
|
||||
// that description looks like a concise human agent name ("Victor"), not a
|
||||
// verbose SOUL summary.
|
||||
// Match upstream Desktop: presentation-only display_name, then exact request name.
|
||||
fun profileDisplayName(profile: Profile?): String? {
|
||||
if (profile == null) return null
|
||||
if (profile.name.equals("default", ignoreCase = true)) {
|
||||
return defaultProfileDisplayName(profile)
|
||||
}
|
||||
return when {
|
||||
profile.name.isNotBlank() -> titleCase(profile.name.trim())
|
||||
profile.description.isNotBlank() -> profile.description.trim()
|
||||
else -> null
|
||||
}
|
||||
return profile.displayName.trim().takeIf(String::isNotEmpty)
|
||||
?: profile.name.trim().takeIf(String::isNotEmpty)
|
||||
}
|
||||
|
||||
fun defaultProfileDisplayName(profile: Profile?): String? =
|
||||
profile
|
||||
?.description
|
||||
?.trim()
|
||||
?.takeIf { it.looksLikeConciseAgentName() }
|
||||
?.let(::titleCase)
|
||||
|
||||
@Suppress("UNUSED_PARAMETER") // connectionLabel retained for source compatibility.
|
||||
fun agentName(
|
||||
profile: Profile?,
|
||||
selectedPersonality: String,
|
||||
@@ -76,7 +70,7 @@ object AgentDisplay {
|
||||
|
||||
// "none"/"neutral" are the upstream "cleared overlay" aliases — treat
|
||||
// them like "default" for identity: fall through to the server default
|
||||
// (or the base connection identity) rather than rendering the literal
|
||||
// identity rather than rendering the literal
|
||||
// word as an agent name.
|
||||
val personalityName = if (
|
||||
isClearedPersonality(selectedPersonality) &&
|
||||
@@ -92,7 +86,6 @@ object AgentDisplay {
|
||||
return when {
|
||||
personalityName.isNotBlank() && personalityName != "default" ->
|
||||
titleCase(personalityName.trim())
|
||||
!connectionLabel.isNullOrBlank() -> connectionLabel.trim()
|
||||
else -> "Hermes"
|
||||
}
|
||||
}
|
||||
@@ -163,7 +156,25 @@ object AgentDisplay {
|
||||
profileRequestName(profileName) ?: SERVER_DEFAULT_PROFILE_KEY
|
||||
|
||||
fun profileContextKey(connectionId: String?, profileName: String?): String =
|
||||
"${connectionId.orEmpty()}::${profileSessionKey(profileName)}"
|
||||
"${connectionId.orEmpty()}$PROFILE_CONTEXT_SEPARATOR${profileSessionKey(profileName)}"
|
||||
|
||||
/**
|
||||
* Parse the canonical profile/context identity used by persisted chat state.
|
||||
*
|
||||
* Legacy or malformed opaque keys deliberately return null: recovery may
|
||||
* still use the exact key for ownership, but must not invent an upstream
|
||||
* profile override from it. The first separator is authoritative so legal
|
||||
* profile names containing `::` remain round-trippable.
|
||||
*/
|
||||
fun parseProfileContextKey(contextKey: String?): ProfileContextIdentity? {
|
||||
val raw = contextKey?.trim().orEmpty()
|
||||
val separator = raw.indexOf(PROFILE_CONTEXT_SEPARATOR)
|
||||
if (separator <= 0 || separator + PROFILE_CONTEXT_SEPARATOR.length >= raw.length) return null
|
||||
val connectionId = raw.substring(0, separator).trim()
|
||||
val profileKey = raw.substring(separator + PROFILE_CONTEXT_SEPARATOR.length).trim()
|
||||
if (connectionId.isEmpty() || profileKey.isEmpty()) return null
|
||||
return ProfileContextIdentity(connectionId, profileKey)
|
||||
}
|
||||
|
||||
fun localDisplayAlias(value: String?): String? =
|
||||
value
|
||||
@@ -171,16 +182,6 @@ object AgentDisplay {
|
||||
?.replace(Regex("\\s+"), " ")
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
|
||||
private fun String.looksLikeConciseAgentName(): Boolean {
|
||||
if (isBlank() || length > 40 || contains('\n') || contains('\r')) {
|
||||
return false
|
||||
}
|
||||
if (any { it == '.' || it == ':' || it == ';' }) {
|
||||
return false
|
||||
}
|
||||
return trim().split(Regex("\\s+")).size <= 4
|
||||
}
|
||||
|
||||
private fun titleCase(value: String): String =
|
||||
value.replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.ui.theme.AppFont
|
||||
@@ -35,23 +36,25 @@ internal object AppearancePreferences {
|
||||
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,
|
||||
)
|
||||
}
|
||||
.map(::decode)
|
||||
|
||||
fun decode(preferences: Preferences): PersistedAppearance {
|
||||
val customThemes = decodeCustomThemes(preferences[customThemesKey])
|
||||
val requestedThemeId = preferences[appThemeKey]
|
||||
val customTheme = CustomThemePreset.idFromAppTheme(requestedThemeId)
|
||||
?.let { id -> customThemes.firstOrNull { it.id == id } }
|
||||
return 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 }
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
data class BotGatewayRouteKey(
|
||||
val connectionId: String,
|
||||
val profileName: String,
|
||||
) {
|
||||
init {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
require(profileName.isNotBlank()) { "profileName must not be blank" }
|
||||
}
|
||||
}
|
||||
|
||||
class BotGatewayRoute(
|
||||
val key: BotGatewayRouteKey,
|
||||
val connectionLabel: String,
|
||||
val installId: String? = null,
|
||||
) {
|
||||
val connectionId: String get() = key.connectionId
|
||||
val profileName: String get() = key.profileName
|
||||
|
||||
override fun equals(other: Any?): Boolean = other is BotGatewayRoute && key == other.key
|
||||
override fun hashCode(): Int = key.hashCode()
|
||||
override fun toString(): String = "BotGatewayRoute(key=$key, label=$connectionLabel)"
|
||||
}
|
||||
|
||||
/** Bounded session summary published by upstream `profiles.list`. */
|
||||
data class BotSessionSummary(
|
||||
val id: String,
|
||||
val resolvedId: String = id,
|
||||
val title: String = "",
|
||||
val rootTitle: String = "",
|
||||
val preview: String = "",
|
||||
val startedAtMs: Long = 0L,
|
||||
val lastActiveAtMs: Long = 0L,
|
||||
val messageCount: Int = 0,
|
||||
)
|
||||
|
||||
data class BotRosterEntry(
|
||||
val profile: Profile,
|
||||
val displayName: String,
|
||||
val route: BotGatewayRoute? = null,
|
||||
val handle: String = profile.name,
|
||||
val stale: Boolean = false,
|
||||
val botTitle: String = "",
|
||||
val hidden: Boolean = false,
|
||||
val lastSession: BotSessionSummary? = null,
|
||||
val workerSession: BotSessionSummary? = null,
|
||||
val canonicalSession: BotSessionSummary? = null,
|
||||
) {
|
||||
val latestActivityAtMs: Long
|
||||
get() = maxOf(
|
||||
canonicalSession?.lastActiveAtMs ?: 0L,
|
||||
lastSession?.lastActiveAtMs ?: 0L,
|
||||
)
|
||||
|
||||
val presenceActivityAtMs: Long
|
||||
get() = maxOf(latestActivityAtMs, workerSession?.lastActiveAtMs ?: 0L)
|
||||
|
||||
val latestPreview: String
|
||||
get() = canonicalSession?.preview?.takeIf(String::isNotBlank)
|
||||
?: lastSession?.preview.orEmpty()
|
||||
}
|
||||
|
||||
data class BotGroupMember(
|
||||
val name: String,
|
||||
val handle: String? = null,
|
||||
val connectionId: String? = null,
|
||||
val connectionLabel: String? = null,
|
||||
)
|
||||
|
||||
data class BotGroupMessage(
|
||||
val id: String? = null,
|
||||
val senderName: String,
|
||||
val senderKind: String,
|
||||
val senderSource: String? = null,
|
||||
val text: String,
|
||||
val atMs: Long,
|
||||
)
|
||||
|
||||
data class BotGroupRoom(
|
||||
val key: String,
|
||||
val roomId: String? = null,
|
||||
val name: String,
|
||||
val revision: Long = 0L,
|
||||
val members: List<BotGroupMember> = emptyList(),
|
||||
val messages: List<BotGroupMessage> = emptyList(),
|
||||
val sourceConnectionIds: Set<String> = emptySet(),
|
||||
val stale: Boolean = false,
|
||||
) {
|
||||
val latestMessage: BotGroupMessage? get() = messages.maxByOrNull(BotGroupMessage::atMs)
|
||||
val latestActivityAtMs: Long get() = latestMessage?.atMs ?: 0L
|
||||
}
|
||||
|
||||
data class BotModeRoster(
|
||||
val bots: List<BotRosterEntry> = emptyList(),
|
||||
val groups: List<BotGroupRoom> = emptyList(),
|
||||
val botModeProtocolSupported: Boolean = false,
|
||||
)
|
||||
|
||||
data class BotGatewayRosterStatus(
|
||||
val connectionId: String,
|
||||
val label: String,
|
||||
val installId: String? = null,
|
||||
val loading: Boolean = false,
|
||||
val stale: Boolean = false,
|
||||
val error: String? = null,
|
||||
val botCount: Int = 0,
|
||||
)
|
||||
|
||||
data class BotChatTarget(
|
||||
/** Durable registry-row identity. */
|
||||
val storedSessionId: String,
|
||||
/** Compression-lineage tip that should be resumed. */
|
||||
val resolvedSessionId: String = storedSessionId,
|
||||
)
|
||||
|
||||
data class BotModeState(
|
||||
val loading: Boolean = false,
|
||||
val roster: BotModeRoster = BotModeRoster(),
|
||||
val gateways: List<BotGatewayRosterStatus> = emptyList(),
|
||||
val error: String? = null,
|
||||
)
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
/** Presentation only: canonical rows retain their wire identity, role and content. */
|
||||
internal fun projectChatActivityReceipts(
|
||||
messages: List<ChatMessage>,
|
||||
records: List<ChatActivityRecord>,
|
||||
scopeKey: String?,
|
||||
sessionId: String?,
|
||||
): List<ChatMessage> {
|
||||
val originals = messages.filterNot {
|
||||
it.clientOnly && it.id.startsWith("activity:") && it.activityRecord != null
|
||||
}
|
||||
if (scopeKey.isNullOrBlank() || sessionId.isNullOrBlank()) {
|
||||
return originals.map { it.copy(activityRecord = null) }
|
||||
}
|
||||
val owned = records.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||
.sortedByDescending { it.updatedAt }
|
||||
.distinctBy { it.id }
|
||||
val represented = mutableSetOf<String>()
|
||||
val canonical = originals.map { message ->
|
||||
val process = message.hermesProcessNotificationOrNull()
|
||||
val delegation = message.activitySourceId?.takeIf { it.startsWith("delegation:") }
|
||||
?.removePrefix("delegation:")?.takeIf { it.isNotBlank() }
|
||||
val kind = when {
|
||||
message.activitySourceId != null -> ChatActivityKind.SUBAGENTS
|
||||
process != null -> ChatActivityKind.PROCESS
|
||||
else -> return@map message.copy(activityRecord = null)
|
||||
}
|
||||
val sourceId = delegation ?: process?.processId
|
||||
val processTerminal = process?.let { notice ->
|
||||
PROCESS_TERMINAL_HEADLINE.matchEntire(notice.headline)?.let { match ->
|
||||
match.groupValues[2].toIntOrNull()?.let { code ->
|
||||
val phase = when {
|
||||
match.groupValues[1].startsWith("terminated by ") -> ChatActivityPhase.CANCELLED
|
||||
code == 0 -> ChatActivityPhase.COMPLETE
|
||||
else -> ChatActivityPhase.FAILED
|
||||
}
|
||||
phase to code
|
||||
}
|
||||
}
|
||||
}
|
||||
// A process id can be reused after a registry restart. A canonical row has
|
||||
// no start-generation field, so multiple generations must remain unmatched.
|
||||
val matching = if (sourceId == null) emptyList() else owned.filter {
|
||||
it.kind == kind && it.sourceId == sourceId
|
||||
}
|
||||
val record = matching.singleOrNull()?.also { represented += it.id }
|
||||
?: ChatActivityRecord(
|
||||
id = "canonical:${message.id}",
|
||||
scopeKey = scopeKey,
|
||||
sessionId = sessionId,
|
||||
kind = kind,
|
||||
sourceId = sourceId ?: "unavailable:${message.id}",
|
||||
title = process?.headline ?: message.content,
|
||||
phase = when {
|
||||
kind == ChatActivityKind.PROCESS -> processTerminal?.first ?: ChatActivityPhase.UNKNOWN
|
||||
(message.activityFailedCount ?: 0) > 0 ->
|
||||
if (message.activityFailedCount == message.activityTaskCount) {
|
||||
ChatActivityPhase.FAILED
|
||||
} else ChatActivityPhase.UNKNOWN
|
||||
(message.activityTaskCount ?: 0) > 0 -> ChatActivityPhase.COMPLETE
|
||||
else -> ChatActivityPhase.UNKNOWN
|
||||
},
|
||||
createdAt = message.timestamp,
|
||||
updatedAt = message.timestamp,
|
||||
taskCount = message.activityTaskCount?.coerceAtLeast(0) ?: 0,
|
||||
processId = process?.processId,
|
||||
exitCode = processTerminal?.second,
|
||||
)
|
||||
// Aggregate completion metadata never rewrites captured child phases.
|
||||
message.copy(activityRecord = record)
|
||||
}
|
||||
val pending = owned.filter { it.phase != ChatActivityPhase.RUNNING && it.id !in represented }
|
||||
.sortedWith(compareBy<ChatActivityRecord> { it.updatedAt }.thenBy { it.id })
|
||||
.map { record ->
|
||||
ChatMessage(
|
||||
id = "activity:${record.id}",
|
||||
role = MessageRole.SYSTEM,
|
||||
content = record.title,
|
||||
timestamp = record.updatedAt,
|
||||
clientOnly = true,
|
||||
activityRecord = record,
|
||||
)
|
||||
}
|
||||
// Stable merge: history order is authoritative even if server timestamps
|
||||
// regress. Only insert local receipts; never sort canonical messages.
|
||||
var next = 0
|
||||
return buildList {
|
||||
canonical.forEach { message ->
|
||||
while (next < pending.size && pending[next].timestamp < message.timestamp) {
|
||||
add(pending[next++])
|
||||
}
|
||||
add(message)
|
||||
}
|
||||
while (next < pending.size) add(pending[next++])
|
||||
}
|
||||
}
|
||||
|
||||
/** Upstream completion envelope only; never search arbitrary command/output text. */
|
||||
private val PROCESS_TERMINAL_HEADLINE = Regex(
|
||||
"""Background process \S+ (completed normally|exited|terminated by [^\r\n]+|marked lost because the process backend disappeared|failed to start) \(exit code (-?\d+)(?:, SIGTERM)?\)\.""",
|
||||
)
|
||||
@@ -0,0 +1,222 @@
|
||||
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.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import java.io.IOException
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
|
||||
@Serializable
|
||||
enum class ChatActivityKind { SUBAGENTS, PROCESS }
|
||||
|
||||
@Serializable
|
||||
enum class ChatActivityPhase { RUNNING, COMPLETE, FAILED, CANCELLED, UNKNOWN }
|
||||
|
||||
@Serializable
|
||||
data class ChatActivityChild(
|
||||
val id: String,
|
||||
val childSessionId: String? = null,
|
||||
val goal: String = "",
|
||||
val phase: ChatActivityPhase = ChatActivityPhase.UNKNOWN,
|
||||
val summary: String? = null,
|
||||
)
|
||||
|
||||
/** Local presentation metadata and exact references, never transcripts or process output. */
|
||||
@Serializable
|
||||
data class ChatActivityRecord(
|
||||
val id: String,
|
||||
val scopeKey: String,
|
||||
val sessionId: String,
|
||||
val kind: ChatActivityKind,
|
||||
val sourceId: String,
|
||||
val title: String,
|
||||
val phase: ChatActivityPhase,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long,
|
||||
val children: List<ChatActivityChild> = emptyList(),
|
||||
val taskCount: Int = 0,
|
||||
val processId: String? = null,
|
||||
val processStartedAt: String? = null,
|
||||
val exitCode: Int? = null,
|
||||
)
|
||||
|
||||
interface ChatActivityStore {
|
||||
/** Recovery is not live evidence: RUNNING becomes UNKNOWN, including child phases. */
|
||||
suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord>
|
||||
suspend fun upsert(record: ChatActivityRecord)
|
||||
suspend fun removeRecord(scopeKey: String, sessionId: String, id: String)
|
||||
suspend fun removeSession(scopeKey: String, sessionId: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded app-private history references in the shared settings DataStore.
|
||||
* Retains 30 days, 128 records overall, 32 per exact owner/session, and 32 children
|
||||
* per record. Titles are 160 characters; goals/summaries 512. Identity fields are
|
||||
* rejected above 512 characters (scope 2048), never truncated into another owner.
|
||||
* The complete encoded envelope is capped at 1 MiB, evicting oldest records first.
|
||||
* Five minutes of future skew allows monotonic local revisions within one clock tick.
|
||||
* All read/modify/write operations occur inside DataStore's serialized edit.
|
||||
*/
|
||||
class DataStoreChatActivityStore(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) : ChatActivityStore {
|
||||
constructor(context: Context) : this(context.applicationContext.relayDataStore)
|
||||
|
||||
override suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord> {
|
||||
val raw = try {
|
||||
dataStore.data.first()[CHAT_ACTIVITY_KEY]
|
||||
} catch (_: IOException) {
|
||||
return emptyList()
|
||||
}
|
||||
return boundChatActivities(decodeChatActivities(raw), now())
|
||||
.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||
.map(ChatActivityRecord::recovered)
|
||||
}
|
||||
|
||||
override suspend fun upsert(record: ChatActivityRecord) {
|
||||
dataStore.edit { preferences ->
|
||||
val records = mergeChatActivity(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), record, now())
|
||||
preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(records)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeSession(scopeKey: String, sessionId: String) {
|
||||
dataStore.edit { preferences ->
|
||||
val remaining = boundChatActivities(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), now())
|
||||
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||
if (remaining.isEmpty()) preferences.remove(CHAT_ACTIVITY_KEY)
|
||||
else preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(remaining)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeRecord(scopeKey: String, sessionId: String, id: String) {
|
||||
dataStore.edit { preferences ->
|
||||
val remaining = boundChatActivities(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), now())
|
||||
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId && it.id == id }
|
||||
if (remaining.isEmpty()) preferences.remove(CHAT_ACTIVITY_KEY)
|
||||
else preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(remaining)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Test/ephemeral implementation with the same bounds and recovery semantics. */
|
||||
class InMemoryChatActivityStore(
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) : ChatActivityStore {
|
||||
private val mutex = Mutex()
|
||||
private var records = emptyList<ChatActivityRecord>()
|
||||
|
||||
override suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord> = mutex.withLock {
|
||||
records = boundChatActivities(records, now())
|
||||
records.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||
.map(ChatActivityRecord::recovered)
|
||||
}
|
||||
|
||||
override suspend fun upsert(record: ChatActivityRecord) = mutex.withLock {
|
||||
records = mergeChatActivity(records, record, now())
|
||||
}
|
||||
|
||||
override suspend fun removeSession(scopeKey: String, sessionId: String) = mutex.withLock {
|
||||
records = boundChatActivities(records, now())
|
||||
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||
}
|
||||
|
||||
override suspend fun removeRecord(scopeKey: String, sessionId: String, id: String) = mutex.withLock {
|
||||
records = boundChatActivities(records, now())
|
||||
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId && it.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
internal const val CHAT_ACTIVITY_MAX_AGE_MS = 30L * 24L * 60L * 60L * 1_000L
|
||||
private const val MAX_RECORDS = 128
|
||||
private const val MAX_SESSION_RECORDS = 32
|
||||
private const val MAX_PAYLOAD_BYTES = 1_048_576
|
||||
private val CHAT_ACTIVITY_KEY = stringPreferencesKey("chat_activity_records_v1")
|
||||
private val activityJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||
|
||||
@Serializable
|
||||
private data class ChatActivityEnvelope(val version: Int = 1, val records: List<ChatActivityRecord>)
|
||||
|
||||
private fun encodeChatActivities(records: List<ChatActivityRecord>): String =
|
||||
activityJson.encodeToString(ChatActivityEnvelope(records = records))
|
||||
|
||||
internal fun decodeChatActivities(raw: String?): List<ChatActivityRecord> {
|
||||
if (raw == null || raw.length > MAX_PAYLOAD_BYTES || raw.toByteArray().size > MAX_PAYLOAD_BYTES) {
|
||||
return emptyList()
|
||||
}
|
||||
val envelope = runCatching { activityJson.parseToJsonElement(raw) as? JsonObject }.getOrNull()
|
||||
?: return emptyList()
|
||||
val version = runCatching { envelope["version"]?.jsonPrimitive?.intOrNull }.getOrNull()
|
||||
if (version != 1) return emptyList()
|
||||
val rows = envelope["records"] as? JsonArray ?: return emptyList()
|
||||
// One corrupt or newer row must not hide independently valid records.
|
||||
return rows.mapNotNull { row ->
|
||||
runCatching { activityJson.decodeFromJsonElement(ChatActivityRecord.serializer(), row) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
private fun ChatActivityRecord.identity() = Triple(scopeKey, sessionId, id)
|
||||
|
||||
private fun mergeChatActivity(
|
||||
existing: List<ChatActivityRecord>,
|
||||
record: ChatActivityRecord,
|
||||
now: Long,
|
||||
): List<ChatActivityRecord> {
|
||||
// Sorting first also rejects a late write for an older generation of the same record.
|
||||
return boundChatActivities(listOf(record) + existing, now)
|
||||
}
|
||||
|
||||
internal fun boundChatActivities(records: List<ChatActivityRecord>, now: Long): List<ChatActivityRecord> {
|
||||
val counts = mutableMapOf<Pair<String, String>, Int>()
|
||||
val bounded = records.mapNotNull { it.bounded(now) }
|
||||
.sortedByDescending(ChatActivityRecord::updatedAt)
|
||||
.distinctBy { it.identity() }
|
||||
.filter {
|
||||
val owner = it.scopeKey to it.sessionId
|
||||
val count = counts.getOrDefault(owner, 0)
|
||||
counts[owner] = count + 1
|
||||
count < MAX_SESSION_RECORDS
|
||||
}.take(MAX_RECORDS).toMutableList()
|
||||
while (bounded.isNotEmpty() && encodeChatActivities(bounded).toByteArray().size > MAX_PAYLOAD_BYTES) {
|
||||
bounded.removeAt(bounded.lastIndex)
|
||||
}
|
||||
return bounded
|
||||
}
|
||||
|
||||
private fun validIdentity(value: String, max: Int = 512) = value.isNotBlank() && value.length <= max
|
||||
|
||||
private fun ChatActivityRecord.bounded(now: Long): ChatActivityRecord? {
|
||||
if (!validIdentity(scopeKey, 2048) || !validIdentity(sessionId) || !validIdentity(id) ||
|
||||
!validIdentity(sourceId) || (processId != null && !validIdentity(processId)) ||
|
||||
(processStartedAt != null && !validIdentity(processStartedAt)) ||
|
||||
createdAt < 0 || updatedAt < createdAt || updatedAt > now + 300_000L ||
|
||||
now - updatedAt > CHAT_ACTIVITY_MAX_AGE_MS
|
||||
) return null
|
||||
return copy(
|
||||
title = title.take(160),
|
||||
taskCount = taskCount.coerceIn(0, 10_000),
|
||||
children = children.asSequence().filter {
|
||||
validIdentity(it.id) && (it.childSessionId == null || validIdentity(it.childSessionId))
|
||||
}.distinctBy(ChatActivityChild::id).take(32)
|
||||
.map { it.copy(goal = it.goal.take(512), summary = it.summary?.take(512)) }.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun ChatActivityRecord.recovered() = copy(
|
||||
phase = if (phase == ChatActivityPhase.RUNNING) ChatActivityPhase.UNKNOWN else phase,
|
||||
children = children.map {
|
||||
if (it.phase == ChatActivityPhase.RUNNING) it.copy(phase = ChatActivityPhase.UNKNOWN) else it
|
||||
},
|
||||
)
|
||||
@@ -22,6 +22,26 @@ enum class PhysicalKeyboardEnterBehavior(val storedValue: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Default intent for a message submitted while an agent is responding. */
|
||||
enum class BusyMessageAction(val storedValue: String) {
|
||||
CorrectNow("correct_now"),
|
||||
QueueNext("queue_next");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): BusyMessageAction =
|
||||
entries.firstOrNull { it.storedValue == value } ?: CorrectNow
|
||||
}
|
||||
}
|
||||
|
||||
fun canCorrectBusyMessage(
|
||||
steerable: Boolean,
|
||||
hasAttachments: Boolean,
|
||||
hasPendingInput: Boolean,
|
||||
status: String?,
|
||||
text: String,
|
||||
): Boolean = steerable && !hasAttachments && !hasPendingInput &&
|
||||
status?.contains("compact", ignoreCase = true) != true && !text.trimStart().startsWith("/")
|
||||
|
||||
/** Device-level chat input preferences shared by every Hermes profile. */
|
||||
class ChatInputPreferencesRepository(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
@@ -29,10 +49,13 @@ class ChatInputPreferencesRepository(
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
companion object {
|
||||
internal val KEY_BUSY_MESSAGE_ACTION = stringPreferencesKey("busy_message_action")
|
||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
internal val KEY_CONVERT_LARGE_PASTES =
|
||||
booleanPreferencesKey("convert_large_pastes_to_attachments")
|
||||
internal val KEY_SHOW_GIT_WORKSPACE_IN_CHAT =
|
||||
booleanPreferencesKey("show_git_workspace_in_chat")
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: Flow<PhysicalKeyboardEnterBehavior> = dataStore.data
|
||||
@@ -43,10 +66,22 @@ class ChatInputPreferencesRepository(
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
val busyMessageAction: Flow<BusyMessageAction> = dataStore.data
|
||||
.map { BusyMessageAction.fromStoredValue(it[KEY_BUSY_MESSAGE_ACTION]) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setBusyMessageAction(action: BusyMessageAction) {
|
||||
dataStore.edit { it[KEY_BUSY_MESSAGE_ACTION] = action.storedValue }
|
||||
}
|
||||
|
||||
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
val showGitWorkspaceInChat: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_SHOW_GIT_WORKSPACE_IN_CHAT] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_PHYSICAL_KEYBOARD_ENTER] = behavior.storedValue
|
||||
@@ -58,4 +93,10 @@ class ChatInputPreferencesRepository(
|
||||
preferences[KEY_CONVERT_LARGE_PASTES] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setShowGitWorkspaceInChat(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_SHOW_GIT_WORKSPACE_IN_CHAT] = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,16 @@ package com.hermesandroid.relay.data
|
||||
*/
|
||||
enum class AttachmentState { LOADING, LOADED, FAILED }
|
||||
|
||||
/**
|
||||
* Gateway tool events do not yet expose an output kind before completion.
|
||||
* Recognize the upstream built-in plus the profile-tool naming convention used
|
||||
* for image generators without guessing from generic prompt arguments.
|
||||
*/
|
||||
internal fun isImageGenerationToolName(name: String): Boolean {
|
||||
val normalized = name.trim().lowercase()
|
||||
return normalized == "image_generate" || normalized.endsWith("_create_image")
|
||||
}
|
||||
|
||||
/**
|
||||
* How the UI should render a loaded attachment. Derived from the MIME type.
|
||||
* - [IMAGE] inline image (decode bytes / load URI).
|
||||
@@ -160,6 +170,12 @@ data class ChatMessage(
|
||||
* but server history never owns these presentation blocks.
|
||||
*/
|
||||
val moaReferences: List<MoaReference> = emptyList(),
|
||||
/** Exact upstream identity on a persisted activity-completion marker. */
|
||||
val activitySourceId: String? = null,
|
||||
val activityTaskCount: Int? = null,
|
||||
val activityFailedCount: Int? = null,
|
||||
/** Read-only UI projection; never sent as model history or voice input. */
|
||||
val activityRecord: ChatActivityRecord? = null,
|
||||
)
|
||||
|
||||
data class MessageReaction(
|
||||
@@ -451,7 +467,8 @@ data class ChatSession(
|
||||
val outputTokens: Int = 0,
|
||||
val actualCostUsd: Double? = null,
|
||||
val estimatedCostUsd: Double? = null,
|
||||
val isActive: Boolean = false,
|
||||
/** Upstream REST five-minute recency hint; never evidence that a turn is running. */
|
||||
val recentlyActive: Boolean = false,
|
||||
val updatedAt: Long = 0L,
|
||||
val startedAt: Long = 0L,
|
||||
val lastActivityAt: Long = 0L,
|
||||
|
||||
@@ -5,6 +5,7 @@ import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.network.upstream.GatewayClarifyQuestion
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
@@ -23,6 +24,8 @@ import kotlinx.serialization.json.Json
|
||||
data class ChatTurnCheckpoint(
|
||||
val schemaVersion: Int = CURRENT_SCHEMA,
|
||||
val contextKey: String,
|
||||
/** Explicit persisted profile identity; null only for legacy checkpoints. */
|
||||
val profileKey: String? = null,
|
||||
val sessionId: String,
|
||||
val liveSessionId: String? = null,
|
||||
val transport: String,
|
||||
@@ -33,6 +36,9 @@ data class ChatTurnCheckpoint(
|
||||
val baselineAssistantCount: Int,
|
||||
val pendingAsk: ChatTurnAskCheckpoint? = null,
|
||||
val queuedMessages: List<ChatQueuedMessageCheckpoint> = emptyList(),
|
||||
val queuePaused: Boolean = false,
|
||||
/** Only pending local work remains; never reattach the completed/stopped turn. */
|
||||
val queueOnly: Boolean = false,
|
||||
val startedAt: Long,
|
||||
val updatedAt: Long,
|
||||
) {
|
||||
@@ -130,6 +136,9 @@ data class ChatTurnAskCheckpoint(
|
||||
val text: String,
|
||||
val choices: List<String>? = null,
|
||||
val multiSelect: Boolean = false,
|
||||
val questions: List<GatewayClarifyQuestion> = emptyList(),
|
||||
val answers: Map<String, String> = emptyMap(),
|
||||
val ownerId: String? = null,
|
||||
val smartDenied: Boolean = false,
|
||||
val envVar: String? = null,
|
||||
val timeoutSeconds: Int,
|
||||
|
||||
@@ -29,3 +29,26 @@ val Connection.capabilities: ConnectionCapabilities
|
||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Stable owner for an Auto chat before a conversation is opened.
|
||||
*
|
||||
* A legacy API-only record has no persisted Dashboard route; the conventional
|
||||
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
|
||||
* must not silently turn that compatibility record into a Gateway-owned chat.
|
||||
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
|
||||
* standard Chat belongs to Gateway even while that route is signed out or
|
||||
* temporarily unreachable.
|
||||
*/
|
||||
val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
// An empty first-setup placeholder is standard Gateway intent, not an
|
||||
// API-only conversation. Only an actual API endpoint selects legacy SSE.
|
||||
return if (dashboardPersisted || apiServerUrl.isBlank()) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
if (preference == "auto") automaticChatTransport
|
||||
else SessionTransport.forEndpoint(preference)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.net.Inet6Address
|
||||
import java.net.InetAddress
|
||||
import java.net.URI
|
||||
|
||||
@Serializable
|
||||
@@ -65,6 +67,16 @@ data class Connection(
|
||||
* "derive from [apiServerUrl] using the conventional same-host :9119".
|
||||
*/
|
||||
val dashboardUrl: String? = null,
|
||||
/** User-accepted cleartext origins. This does not assert or monitor VPN protection. */
|
||||
val dashboardHttpConsentOrigins: Set<String> = emptySet(),
|
||||
/**
|
||||
* Credential-free origin that most recently completed Dashboard
|
||||
* authentication for this connection. Public origins require HTTPS;
|
||||
* loopback/private-overlay HTTP retains upstream's trusted-network mode.
|
||||
* Dashboard/Gateway consumers prefer this origin, while [routeCandidates]
|
||||
* continue to own only network route selection for API and Relay.
|
||||
*/
|
||||
val authenticatedDashboardOrigin: String? = null,
|
||||
val dashboardAuthRequired: Boolean? = null,
|
||||
val dashboardAuthProviders: List<String> = emptyList(),
|
||||
val dashboardLastStatus: DashboardConnectionStatus? = null,
|
||||
@@ -77,6 +89,11 @@ data class Connection(
|
||||
val routeCandidates: List<EndpointCandidate> = emptyList(),
|
||||
/** Optional user preference such as "lan" or "tailscale"; null means Auto. */
|
||||
val preferredRouteRole: String? = null,
|
||||
/**
|
||||
* Explicit per-installation consent for Relay Git repository discovery.
|
||||
* Missing legacy values remain off; route/profile changes do not broaden it.
|
||||
*/
|
||||
val gitRepoScanningEnabled: Boolean = false,
|
||||
/** Epoch milliseconds. Pass `System.currentTimeMillis()`; do not pass seconds. */
|
||||
val pairedAt: Long? = null,
|
||||
/** Last time the user explicitly selected this connection. */
|
||||
@@ -86,21 +103,27 @@ data class Connection(
|
||||
/** Epoch milliseconds. The auth.ok `expires_at` field is seconds — multiply by 1000 at the call site. */
|
||||
val expiresAt: Long? = null,
|
||||
) {
|
||||
/**
|
||||
* Effective Dashboard/Gateway endpoint. Legacy records did not persist a
|
||||
* dashboard URL, so they retain the conventional same-host `:9119`
|
||||
* derivation from the API server. Dashboard-only records persist an
|
||||
* explicit URL and may leave [apiServerUrl] and [relayUrl] blank.
|
||||
*/
|
||||
val resolvedDashboardUrl: String
|
||||
/** Saved Dashboard/Gateway route before any authenticated-origin override. */
|
||||
val configuredDashboardUrl: String
|
||||
get() = dashboardUrl
|
||||
?.trim()
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: deriveDefaultDashboardUrl(apiServerUrl).orEmpty()
|
||||
|
||||
/**
|
||||
* Effective Dashboard/Gateway endpoint. A verified authenticated origin
|
||||
* wins without rewriting the saved network route. Legacy records retain
|
||||
* the conventional same-host `:9119` derivation through
|
||||
* [configuredDashboardUrl].
|
||||
*/
|
||||
val resolvedDashboardUrl: String
|
||||
get() = authenticatedDashboardOrigin
|
||||
?.let { normalizeCredentialFreeAuthenticatedDashboardOrigin(it, dashboardHttpConsentOrigins) }
|
||||
?: configuredDashboardUrl
|
||||
|
||||
/** Stable display/host identity that does not depend on the API surface. */
|
||||
val primaryEndpointUrl: String
|
||||
get() = resolvedDashboardUrl.takeIf { it.isNotBlank() }
|
||||
get() = configuredDashboardUrl.takeIf { it.isNotBlank() }
|
||||
?: apiServerUrl.trim().takeIf { it.isNotBlank() }
|
||||
?: relayUrl.trim()
|
||||
|
||||
@@ -506,6 +529,12 @@ data class Connection(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a hand-typed Dashboard/Gateway address. Bare private,
|
||||
* LAN, and Tailscale hosts use upstream's `http://…:9119` default;
|
||||
* bare public hosts use `https://` on the standard HTTPS port.
|
||||
* Explicit schemes and ports are preserved for precise validation.
|
||||
*/
|
||||
fun normalizeDashboardUrlInput(
|
||||
raw: String,
|
||||
defaultPort: Int = DEFAULT_DASHBOARD_PORT,
|
||||
@@ -513,7 +542,10 @@ data class Connection(
|
||||
val trimmed = raw.trim().trimEnd('/')
|
||||
if (trimmed.isEmpty()) return trimmed
|
||||
if (SCHEME_REGEX.containsMatchIn(trimmed)) return trimmed
|
||||
val withScheme = "http://$trimmed"
|
||||
val provisionalHttpUrl = "http://$trimmed"
|
||||
val publicAddress = inferRouteRole(provisionalHttpUrl) == "public"
|
||||
val withScheme = if (publicAddress) "https://$trimmed" else provisionalHttpUrl
|
||||
if (publicAddress) return withScheme
|
||||
val uri = runCatching { URI(withScheme) }.getOrNull()
|
||||
val canAppendPort = uri != null &&
|
||||
!uri.host.isNullOrBlank() &&
|
||||
@@ -528,16 +560,41 @@ data class Connection(
|
||||
.getOrNull()
|
||||
?.lowercase()
|
||||
?: return "custom"
|
||||
val normalizedHost = host.removePrefix("[").removeSuffix("]")
|
||||
if (normalizedHost.contains(':')) {
|
||||
val address = runCatching { InetAddress.getByName(normalizedHost) }
|
||||
.getOrNull() as? Inet6Address
|
||||
?: return "public"
|
||||
return when {
|
||||
isTailscaleIpv6(address) -> "tailscale"
|
||||
address.isAnyLocalAddress ||
|
||||
address.isLoopbackAddress ||
|
||||
address.isLinkLocalAddress ||
|
||||
isUniqueLocalIpv6(address) -> "lan"
|
||||
else -> "public"
|
||||
}
|
||||
}
|
||||
return when {
|
||||
host.endsWith(".ts.net") || isTailscaleIpv4(host) -> "tailscale"
|
||||
host == "localhost" ||
|
||||
host == "127.0.0.1" ||
|
||||
host == "::1" ||
|
||||
isPrivateLanIpv4(host) -> "lan"
|
||||
normalizedHost.endsWith(".ts.net") || isTailscaleIpv4(normalizedHost) -> "tailscale"
|
||||
normalizedHost == "localhost" ||
|
||||
normalizedHost == "127.0.0.1" ||
|
||||
normalizedHost.endsWith(".local") ||
|
||||
normalizedHost.endsWith(".lan") ||
|
||||
!normalizedHost.contains('.') ||
|
||||
isPrivateLanIpv4(normalizedHost) -> "lan"
|
||||
else -> "public"
|
||||
}
|
||||
}
|
||||
|
||||
private fun isTailscaleIpv6(address: Inet6Address): Boolean {
|
||||
val bytes = address.address
|
||||
val prefix = intArrayOf(0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0)
|
||||
return prefix.indices.all { index -> bytes[index].toInt() and 0xff == prefix[index] }
|
||||
}
|
||||
|
||||
private fun isUniqueLocalIpv6(address: Inet6Address): Boolean =
|
||||
address.address.first().toInt() and 0xfe == 0xfc
|
||||
|
||||
private fun isTailscaleIpv4(host: String): Boolean {
|
||||
val parts = host.split('.').mapNotNull { it.toIntOrNull() }
|
||||
if (parts.size != 4) return false
|
||||
@@ -557,3 +614,48 @@ data class Connection(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Normalize an absolute, credential-free HTTPS origin for authenticated Dashboard use. */
|
||||
internal fun normalizeCredentialFreeHttpsOrigin(raw: String): String? {
|
||||
val parsed = runCatching { URI(raw.trim()) }.getOrNull() ?: return null
|
||||
if (!parsed.scheme.equals("https", ignoreCase = true)) return null
|
||||
if (parsed.host.isNullOrBlank() || parsed.userInfo != null) return null
|
||||
if (parsed.query != null || parsed.fragment != null) return null
|
||||
if (parsed.port > 65_535) return null
|
||||
return parsed.normalize().toASCIIString().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a reviewed Dashboard credential owner. Public origins require
|
||||
* HTTPS; cleartext is accepted only for literal loopback, RFC1918/link-local,
|
||||
* or Tailscale CGNAT addresses.
|
||||
*/
|
||||
internal fun normalizeCredentialFreeAuthenticatedDashboardOrigin(
|
||||
raw: String,
|
||||
httpConsentOrigins: Set<String> = emptySet(),
|
||||
): String? {
|
||||
normalizeCredentialFreeHttpsOrigin(raw)?.let { return it }
|
||||
val parsed = runCatching { URI(raw.trim()) }.getOrNull() ?: return null
|
||||
if (!parsed.scheme.equals("http", ignoreCase = true)) return null
|
||||
val host = parsed.host
|
||||
?.lowercase()
|
||||
?.removePrefix("[")
|
||||
?.removeSuffix("]")
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: return null
|
||||
if (parsed.userInfo != null || parsed.query != null || parsed.fragment != null) return null
|
||||
if (parsed.port > 65_535) return null
|
||||
val trustedHost = host == "localhost" || host == "127.0.0.1" || host == "::1" ||
|
||||
host.split('.').mapNotNull(String::toIntOrNull).let { octets ->
|
||||
octets.size == 4 && octets.all { it in 0..255 } && when {
|
||||
octets[0] == 10 -> true
|
||||
octets[0] == 172 && octets[1] in 16..31 -> true
|
||||
octets[0] == 192 && octets[1] == 168 -> true
|
||||
octets[0] == 169 && octets[1] == 254 -> true
|
||||
octets[0] == 100 && octets[1] in 64..127 -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
if (!trustedHost && !dashboardHttpConsentMatches(raw, httpConsentOrigins)) return null
|
||||
return parsed.normalize().toASCIIString().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ package com.hermesandroid.relay.data
|
||||
*/
|
||||
enum class SurfaceSecurityKind { Tls, Overlay, Plain }
|
||||
|
||||
/** Whether a configured surface currently contributes traffic to the connection. */
|
||||
enum class SurfaceUseState { InUse, Available, Unavailable }
|
||||
|
||||
/** Connection-level rollup across the surfaces actually in use. */
|
||||
enum class ConnectionSecurityLevel { Tls, Overlay, Mixed, Plain, Unknown }
|
||||
|
||||
@@ -28,6 +31,7 @@ data class SurfaceSecurity(
|
||||
/** Human mechanism: "TLS", "Tailscale", "WireGuard", "Proxy", "Plain". */
|
||||
val mechanism: String,
|
||||
val url: String,
|
||||
val useState: SurfaceUseState = SurfaceUseState.InUse,
|
||||
)
|
||||
|
||||
data class ConnectionSecurity(
|
||||
@@ -86,6 +90,7 @@ fun classifySurfaceSecurity(
|
||||
url: String,
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
useState: SurfaceUseState = SurfaceUseState.InUse,
|
||||
): SurfaceSecurity {
|
||||
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
|
||||
val (kind, mechanism) = when {
|
||||
@@ -96,7 +101,13 @@ fun classifySurfaceSecurity(
|
||||
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
|
||||
else -> SurfaceSecurityKind.Plain to "Plain"
|
||||
}
|
||||
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
|
||||
return SurfaceSecurity(
|
||||
label = label,
|
||||
kind = kind,
|
||||
mechanism = mechanism,
|
||||
url = url,
|
||||
useState = useState,
|
||||
)
|
||||
}
|
||||
|
||||
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
|
||||
@@ -112,8 +123,8 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
} ?: return false
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage" -> "dashboard"
|
||||
"API / sessions" -> "api"
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -137,23 +148,67 @@ fun computeConnectionSecurity(
|
||||
relayConfigured: Boolean,
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
dashboardInUse: Boolean = true,
|
||||
apiInUse: Boolean = true,
|
||||
apiAvailable: Boolean = apiInUse,
|
||||
relayInUse: Boolean = relayConfigured,
|
||||
apiEndpoint: EndpointCandidate? = activeEndpoint,
|
||||
relayEndpoint: EndpointCandidate? = activeEndpoint,
|
||||
): ConnectionSecurity {
|
||||
val surfaces = buildList {
|
||||
dashboardUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("Chat & Manage", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "Dashboard & Gateway",
|
||||
url = it,
|
||||
activeEndpoint = activeEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = if (dashboardInUse) SurfaceUseState.InUse else SurfaceUseState.Unavailable,
|
||||
)
|
||||
)
|
||||
}
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("API / sessions", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "Direct API",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = when {
|
||||
apiInUse -> SurfaceUseState.InUse
|
||||
apiAvailable -> SurfaceUseState.Available
|
||||
else -> SurfaceUseState.Unavailable
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
if (relayConfigured) {
|
||||
relayUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("Relay tools", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "Relay tools",
|
||||
url = it,
|
||||
activeEndpoint = relayEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = if (relayInUse) SurfaceUseState.InUse else SurfaceUseState.Unavailable,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (surfaces.isEmpty()) return ConnectionSecurity.UNKNOWN
|
||||
|
||||
val kinds = surfaces.map { it.kind }.toSet()
|
||||
// Configured-but-unavailable fallbacks remain visible in the breakdown,
|
||||
// but do not make the active transport look insecure.
|
||||
val activeSurfaces = surfaces.filter { it.useState == SurfaceUseState.InUse }
|
||||
if (activeSurfaces.isEmpty()) {
|
||||
return ConnectionSecurity(
|
||||
level = ConnectionSecurityLevel.Unknown,
|
||||
mechanism = "",
|
||||
surfaces = surfaces,
|
||||
)
|
||||
}
|
||||
val kinds = activeSurfaces.map { it.kind }.toSet()
|
||||
val hasPlain = SurfaceSecurityKind.Plain in kinds
|
||||
val hasSecure = kinds.any { it != SurfaceSecurityKind.Plain }
|
||||
|
||||
@@ -167,7 +222,7 @@ fun computeConnectionSecurity(
|
||||
val mechanism = when (level) {
|
||||
ConnectionSecurityLevel.Tls -> "TLS"
|
||||
ConnectionSecurityLevel.Overlay ->
|
||||
surfaces.firstOrNull { it.kind == SurfaceSecurityKind.Overlay }?.mechanism ?: "Encrypted"
|
||||
activeSurfaces.firstOrNull { it.kind == SurfaceSecurityKind.Overlay }?.mechanism ?: "Encrypted"
|
||||
ConnectionSecurityLevel.Mixed -> "Mixed"
|
||||
ConnectionSecurityLevel.Plain -> when (activeEndpoint?.role?.lowercase()) {
|
||||
"lan" -> "LAN"
|
||||
|
||||
@@ -149,15 +149,15 @@ class ConnectionStore private constructor(
|
||||
// between the two names — `{"id": ..., "label": ..., ...}` —
|
||||
// so no per-record migration is needed.
|
||||
if (newJson == null && oldJson != null) {
|
||||
val restored = decodeConnections(oldJson)
|
||||
dataStore.edit { p ->
|
||||
p[KEY_CONNECTIONS] = oldJson
|
||||
p[KEY_CONNECTIONS] = encodeConnections(restored)
|
||||
p.remove(KEY_LEGACY_PROFILES)
|
||||
if (activeNew == null && activeOld != null) {
|
||||
p[KEY_ACTIVE_CONNECTION_ID] = activeOld
|
||||
p.remove(KEY_LEGACY_ACTIVE_PROFILE_ID)
|
||||
}
|
||||
}
|
||||
val restored = decodeConnections(oldJson)
|
||||
val validStartupId = startupId?.takeIf { id -> restored.any { it.id == id } }
|
||||
_connections.value = restored
|
||||
_startupConnectionId.value = validStartupId
|
||||
@@ -168,6 +168,12 @@ class ConnectionStore private constructor(
|
||||
)
|
||||
} else {
|
||||
val restored = decodeConnections(newJson)
|
||||
if (newJson != null) {
|
||||
val normalizedJson = encodeConnections(restored)
|
||||
if (normalizedJson != newJson) {
|
||||
dataStore.edit { p -> p[KEY_CONNECTIONS] = normalizedJson }
|
||||
}
|
||||
}
|
||||
val validStartupId = startupId?.takeIf { id -> restored.any { it.id == id } }
|
||||
_connections.value = restored
|
||||
_startupConnectionId.value = validStartupId
|
||||
@@ -571,7 +577,17 @@ class ConnectionStore private constructor(
|
||||
internal fun Connection.withDashboardDefaults(): Connection {
|
||||
val derivedDashboardUrl = Connection.deriveDefaultDashboardUrl(apiServerUrl)
|
||||
val effectiveDashboardUrl = dashboardUrl?.takeIf { it.isNotBlank() } ?: derivedDashboardUrl
|
||||
val storedOrDefaultRoutes = routeCandidates.ifEmpty {
|
||||
val legacyAuthenticatedRoute = routeCandidates.firstOrNull {
|
||||
it.role.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true)
|
||||
}
|
||||
val migratedAuthenticatedOrigin = authenticatedDashboardOrigin
|
||||
?.let { normalizeCredentialFreeAuthenticatedDashboardOrigin(it, dashboardHttpConsentOrigins) }
|
||||
?: legacyAuthenticatedRoute?.dashboard?.url
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
val routesWithoutLegacyAuthentication = routeCandidates.filterNot {
|
||||
it.role.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true)
|
||||
}
|
||||
val storedOrDefaultRoutes = routesWithoutLegacyAuthentication.ifEmpty {
|
||||
Connection.buildRouteCandidates(
|
||||
apiServerUrl = apiServerUrl,
|
||||
relayUrl = relayUrl,
|
||||
@@ -582,16 +598,18 @@ internal fun Connection.withDashboardDefaults(): Connection {
|
||||
dashboardUrl = effectiveDashboardUrl,
|
||||
candidates = storedOrDefaultRoutes,
|
||||
)
|
||||
val normalizedPreferredRouteRole = preferredRouteRole?.takeIf { preferred ->
|
||||
normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) }
|
||||
}
|
||||
val normalizedPreferredRouteRole = preferredRouteRole
|
||||
?.takeUnless { it.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true) }
|
||||
?.takeIf { preferred -> normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) } }
|
||||
return if (
|
||||
dashboardUrl != effectiveDashboardUrl ||
|
||||
authenticatedDashboardOrigin != migratedAuthenticatedOrigin ||
|
||||
normalizedRoutes != routeCandidates ||
|
||||
normalizedPreferredRouteRole != preferredRouteRole
|
||||
) {
|
||||
copy(
|
||||
dashboardUrl = effectiveDashboardUrl,
|
||||
authenticatedDashboardOrigin = migratedAuthenticatedOrigin,
|
||||
routeCandidates = normalizedRoutes,
|
||||
preferredRouteRole = normalizedPreferredRouteRole,
|
||||
)
|
||||
@@ -599,3 +617,5 @@ internal fun Connection.withDashboardDefaults(): Connection {
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
internal const val LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE = "authenticated_dashboard"
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
|
||||
/** An explicit HTTP exception is scoped to a connection and exact origin, never a VPN claim. */
|
||||
fun dashboardHttpOrigin(address: String): String? {
|
||||
val url = address.trim().toHttpUrlOrNull() ?: return null
|
||||
if (url.scheme != "http" || url.username.isNotEmpty() || url.password.isNotEmpty() ||
|
||||
url.query != null || url.fragment != null
|
||||
) return null
|
||||
return url.newBuilder().encodedPath("/").build().toString().trimEnd('/')
|
||||
}
|
||||
|
||||
fun dashboardHttpConsentRequired(address: String): Boolean =
|
||||
dashboardHttpOrigin(address) != null && Connection.inferRouteRole(address) == "public"
|
||||
|
||||
fun dashboardHttpConsentMatches(address: String, approvedOrigins: Set<String>): Boolean =
|
||||
dashboardHttpOrigin(address)?.let { it in approvedOrigins } == true
|
||||
|
||||
/** Editing an origin retires its old exception; another address requires its own confirmation. */
|
||||
fun updatedDashboardHttpConsents(
|
||||
previous: Set<String>,
|
||||
oldAddress: String?,
|
||||
newAddress: String,
|
||||
confirmedOrigin: String?,
|
||||
): Set<String> {
|
||||
val oldOrigin = oldAddress?.let(::dashboardHttpOrigin)
|
||||
val newOrigin = dashboardHttpOrigin(newAddress)
|
||||
val retained = if (oldOrigin != newOrigin) previous - setOfNotNull(oldOrigin) else previous
|
||||
return if (newOrigin != null && confirmedOrigin == newOrigin) retained + newOrigin else retained
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import java.net.URI
|
||||
*
|
||||
* **Semantics (locked by ADR 24):**
|
||||
* - [role] is an open string. Known values `lan` / `tailscale` / `public`
|
||||
* get styled labels; anything else renders generically (`Custom VPN (<role>)`).
|
||||
* get styled labels; anything else renders generically (`Custom route (<role>)`).
|
||||
* No enum, no normalization — the raw role string must round-trip exactly
|
||||
* so HMAC canonicalization holds.
|
||||
* - [priority] is strict, `0 = highest`. Reachability never promotes a lower
|
||||
@@ -145,18 +145,19 @@ data class BrokerEndpoint(
|
||||
*
|
||||
* Unknown roles (`"wireguard"`, `"zerotier"`, `"netbird-eu"`, operator-defined
|
||||
* labels) return false so the UI can fall back to [displayLabel]'s generic
|
||||
* "Custom VPN" treatment.
|
||||
* "Custom route" treatment.
|
||||
*/
|
||||
fun EndpointCandidate.isKnownRole(): Boolean {
|
||||
return when (role.lowercase()) {
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https",
|
||||
"dashboard", "authenticated_dashboard" -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable label for the UI. Known roles get fixed-case styled labels;
|
||||
* unknown roles render as `"Custom VPN (<role>)"` with the raw role preserved
|
||||
* unknown roles render as `"Custom route (<role>)"` with the raw role preserved
|
||||
* so an operator can see exactly what they labeled it.
|
||||
*
|
||||
* The raw [role] on the [EndpointCandidate] is NOT modified — it stays in its
|
||||
@@ -172,19 +173,58 @@ fun EndpointCandidate.displayLabel(): String {
|
||||
"Public"
|
||||
}
|
||||
"https" -> "HTTPS"
|
||||
"dashboard", "authenticated_dashboard" -> if (
|
||||
primaryRouteUrl()?.startsWith("https://", ignoreCase = true) == true
|
||||
) {
|
||||
"HTTPS Dashboard"
|
||||
} else {
|
||||
"Dashboard"
|
||||
}
|
||||
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
|
||||
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
|
||||
else -> "Custom VPN ($role)"
|
||||
else -> displayName?.trim()?.takeIf { it.isNotBlank() } ?: "Custom route ($role)"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a route created only to keep Dashboard/Gateway authentication on
|
||||
* its canonical origin. It is a service address, not another selectable
|
||||
* whole-connection or VPN route.
|
||||
*/
|
||||
fun EndpointCandidate.isDashboardOnlyRoute(): Boolean =
|
||||
api == null && relay == null && proxy == null && broker == null && dashboard != null
|
||||
|
||||
/** Dashboard-first URL identity for routing, diagnostics, and UI labels. */
|
||||
fun EndpointCandidate.primaryRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxyDashboardBaseUrlOrNull()
|
||||
?: api?.url
|
||||
?: relay?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxy?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
|
||||
/**
|
||||
* Dashboard/Gateway identity only; Relay and broker transports are extensions.
|
||||
*
|
||||
* Hermes Secure Link stores the dashboard surface under [ProxyEndpoint.surfaces]
|
||||
* (`…/dashboard`), not [DashboardEndpoint.url]. Without that hop, Routes/Access
|
||||
* fall back to the saved plain `:9119` URL while Overview already rides the
|
||||
* live Secure Link origin.
|
||||
*/
|
||||
fun EndpointCandidate.gatewayRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxyDashboardBaseUrlOrNull()
|
||||
?: api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
|
||||
/** Secure Link dashboard base when the proxy advertises a dashboard surface. */
|
||||
internal fun EndpointCandidate.proxyDashboardBaseUrlOrNull(): String? {
|
||||
val proxy = proxy ?: return null
|
||||
if (!proxy.isValidPinnedProxy()) return null
|
||||
val surfaces = proxy.surfaces.map { it.trim().lowercase() }.toSet()
|
||||
if ("dashboard" !in surfaces) return null
|
||||
val base = proxy.url.trim().trimEnd('/').takeIf { it.isNotBlank() } ?: return null
|
||||
return "$base/dashboard"
|
||||
}
|
||||
|
||||
/** Stable host/port identity without assuming that an API surface exists. */
|
||||
fun EndpointCandidate.routeAuthority(): String? {
|
||||
val rawUrl = primaryRouteUrl() ?: return null
|
||||
|
||||
@@ -96,7 +96,8 @@ object FeatureFlags {
|
||||
* flavor ships AccessibilityService-backed Device Control. The `googlePlay`
|
||||
* flavor is Bridge Core: relay pairing, chat, voice, terminal, notification
|
||||
* companion, media, and session-grant surfaces without screen reading, taps,
|
||||
* typing, screenshots, overlays, or unattended control.
|
||||
* typing, MediaProjection screenshots, or unattended control. Voice-only overlay
|
||||
* presentation is a separate capability shared by both flavors.
|
||||
*
|
||||
* Device Control tier definitions (see `Phase 3 — Bridge Channel.md`):
|
||||
* 1. baseline — sideload only (app open, tap, navigate within app)
|
||||
@@ -126,6 +127,9 @@ object BuildFlavor {
|
||||
*/
|
||||
val isSideload: Boolean get() = current == SIDELOAD
|
||||
|
||||
/** Voice presentation does not grant Device Control. Unknown distributions fail closed. */
|
||||
val voiceSystemOverlay: Boolean get() = current == GOOGLE_PLAY || current == SIDELOAD
|
||||
|
||||
val bridgeTier1: Boolean get() = current == SIDELOAD // baseline device control
|
||||
val bridgeTier2: Boolean get() = current == SIDELOAD // screen context
|
||||
val bridgeTier3: Boolean get() = current == SIDELOAD // voice-first
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardHttpException
|
||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
||||
import java.io.IOException
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
private fun pathsArray(paths: List<String>) = buildJsonArray { paths.forEach { add(JsonPrimitive(it)) } }
|
||||
|
||||
/**
|
||||
* Uses official Dashboard `/api/git/…` reads for the active session repository.
|
||||
* Relay remains the discovery source and owns stronger write/preview extensions.
|
||||
* Operational upstream failures are never hidden by a Relay retry; only a 404
|
||||
* can fall back to a matching Relay-discovered repository.
|
||||
*/
|
||||
class GitStateApiClient(
|
||||
private val dashboard: DashboardApiClient,
|
||||
) {
|
||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val reposById = linkedMapOf<String, GitRepo>()
|
||||
private val relayRepoIdsByRoot = linkedMapOf<String, String>()
|
||||
|
||||
suspend fun repos(
|
||||
sessionRepoPath: String? = null,
|
||||
includeRelayDiscovery: Boolean = true,
|
||||
): Result<List<GitRepo>> {
|
||||
reposById.clear()
|
||||
relayRepoIdsByRoot.clear()
|
||||
val path = sessionRepoPath?.trim().orEmpty()
|
||||
if (path.isBlank()) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
val upstream = upstreamStatus(path)
|
||||
if (upstream.isFailure) {
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.failure(error)
|
||||
}
|
||||
val status = upstream.getOrNull()
|
||||
if (status == null) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
val standardRepo = GitRepo(
|
||||
id = UPSTREAM_SESSION_REPO_ID,
|
||||
name = path.replace('\\', '/').trimEnd('/').substringAfterLast('/').ifBlank { path },
|
||||
root = path,
|
||||
currentBranch = status.branch,
|
||||
dirty = status.changed > 0,
|
||||
route = GitRepositoryRoute.UPSTREAM,
|
||||
)
|
||||
|
||||
// Plugin discovery is an enhancement. Once upstream answered, plugin
|
||||
// absence or breakage cannot take the standard session repository down.
|
||||
val relay = if (includeRelayDiscovery) relayRepos().getOrDefault(emptyList()) else emptyList()
|
||||
val merged = buildList {
|
||||
add(standardRepo)
|
||||
addAll(relay.filterNot { sameRoot(it.root, standardRepo.root) })
|
||||
}
|
||||
rememberRepos(merged)
|
||||
rememberRelayRepos(relay)
|
||||
return Result.success(merged)
|
||||
}
|
||||
|
||||
suspend fun status(repo: String): Result<GitStatus> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayStatus(repo)
|
||||
return fallbackOnUnsupported(target, upstreamStatusWithFiles(target.root), ::relayStatus)
|
||||
}
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayBranches(repo)
|
||||
return fallbackOnUnsupported(target, upstreamBranches(target.root), ::relayBranches)
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayDiff(repo, path, kind)
|
||||
val upstream = dashboard.getJsonElement(
|
||||
upstreamPath(
|
||||
"/api/git/review/diff",
|
||||
mapOf(
|
||||
"path" to target.root,
|
||||
"file" to path,
|
||||
"scope" to "uncommitted",
|
||||
"staged" to (kind == "staged").toString(),
|
||||
),
|
||||
),
|
||||
).mapCatching { element ->
|
||||
GitDiff(
|
||||
path = path,
|
||||
kind = kind,
|
||||
diff = json.decodeFromJsonElement<UpstreamDiffResponse>(element).diff,
|
||||
)
|
||||
}
|
||||
return fallbackOnUnsupported(target, upstream) { relay -> relayDiff(relay, path, kind) }
|
||||
}
|
||||
|
||||
/** Clean tracked-file preview is a Relay enhancement; file-diff is not equivalent. */
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("Tracked-file preview requires the Relay plugin"))
|
||||
return relayFile(relay, path)
|
||||
}
|
||||
|
||||
// Writes intentionally stay on Relay. The upstream Desktop mutation shape
|
||||
// does not carry plugin.api.write or the server-enforced confirmation echoes
|
||||
// used by this mobile surface, so it is not an equivalent safety contract.
|
||||
|
||||
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun discard(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
put("confirmation", confirmation)
|
||||
put("delete_untracked", deleteUntracked)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commitSelected(
|
||||
repo: String,
|
||||
message: String,
|
||||
paths: List<String>,
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
put("paths", pathsArray(paths))
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun push(
|
||||
repo: String,
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/push", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
put("confirmation", confirmation)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun checkout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (confirmation != null) put("confirmation", confirmation)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> = relayWrite(repo) { relay ->
|
||||
scoped.post("git/commit_message", buildJsonObject { put("repo", relay) })
|
||||
.mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
}
|
||||
|
||||
suspend fun commitMessageSelected(repo: String, paths: List<String>): Result<GitCommitMessage> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) } }
|
||||
|
||||
suspend fun stashCheckout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitStashCheckoutResult> = relayWrite(repo) { relay -> scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) } }
|
||||
|
||||
private suspend fun relayRepos(): Result<List<GitRepo>> = scoped.get("git/repos").mapCatching {
|
||||
json.decodeFromJsonElement<ReposResponse>(it).repos
|
||||
}
|
||||
|
||||
private suspend fun relayStatus(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<GitStatus>(it) }
|
||||
|
||||
private suspend fun relayBranches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<BranchesResponse>(it).branches }
|
||||
|
||||
private suspend fun relayDiff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { json.decodeFromJsonElement<GitDiff>(it) }
|
||||
|
||||
private suspend fun relayFile(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { json.decodeFromJsonElement<GitFile>(it) }
|
||||
|
||||
private suspend fun upstreamStatus(path: String): Result<UpstreamStatus?> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/status", mapOf("path" to path)))
|
||||
.mapCatching { json.decodeFromJsonElement<UpstreamStatus?>(it) }
|
||||
|
||||
private suspend fun upstreamStatusWithFiles(path: String): Result<GitStatus> {
|
||||
val status = upstreamStatus(path).mapCatching {
|
||||
it ?: throw IOException("The active session path is not a Git repository")
|
||||
}.getOrElse { return Result.failure(it) }
|
||||
val review = dashboard.getJsonElement(
|
||||
upstreamPath("/api/git/review/list", mapOf("path" to path, "scope" to "uncommitted")),
|
||||
).mapCatching { json.decodeFromJsonElement<UpstreamReviewList>(it) }
|
||||
.getOrElse { return Result.failure(it) }
|
||||
val statusByPath = status.files.associateBy { it.path }
|
||||
val staged = mutableListOf<GitStatusEntry>()
|
||||
val modified = mutableListOf<GitStatusEntry>()
|
||||
val untracked = mutableListOf<GitStatusEntry>()
|
||||
review.files.forEach { file ->
|
||||
val entry = GitStatusEntry(file.path, file.added, file.removed)
|
||||
val fileStatus = statusByPath[file.path]
|
||||
if (fileStatus?.untracked == true) {
|
||||
untracked += entry
|
||||
} else {
|
||||
if (file.staged || fileStatus?.staged == true) staged += entry
|
||||
if (fileStatus?.unstaged == true || (!file.staged && fileStatus == null)) {
|
||||
modified += entry
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result.success(
|
||||
GitStatus(
|
||||
counts = GitStatusCounts(
|
||||
staged = status.staged,
|
||||
modified = status.unstaged,
|
||||
untracked = status.untracked,
|
||||
changes = status.changed,
|
||||
additions = status.added,
|
||||
deletions = status.removed,
|
||||
),
|
||||
staged = staged,
|
||||
modified = modified,
|
||||
untracked = untracked,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun upstreamBranches(path: String): Result<List<GitBranch>> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/branches", mapOf("path" to path)))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<UpstreamBranches>(element).branches.map {
|
||||
GitBranch(name = it.name, isCurrent = it.checkedOut)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> fallbackOnUnsupported(
|
||||
target: GitRepo,
|
||||
upstream: Result<T>,
|
||||
relayCall: suspend (String) -> Result<T>,
|
||||
): Result<T> {
|
||||
if (upstream.isSuccess) return upstream
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
val relay = relayRepoIdsByRoot[normalizedRoot(target.root)] ?: return Result.failure(error)
|
||||
return relayCall(relay)
|
||||
}
|
||||
|
||||
private suspend fun <T> relayWrite(repo: String, block: suspend (String) -> Result<T>): Result<T> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("This Git action requires the Relay plugin enhancement"))
|
||||
return block(relay)
|
||||
}
|
||||
|
||||
private fun relayRepoId(repo: String): String? {
|
||||
val target = reposById[repo] ?: return repo.takeUnless { it == UPSTREAM_SESSION_REPO_ID }
|
||||
return if (target.route == GitRepositoryRoute.RELAY) target.id
|
||||
else relayRepoIdsByRoot[normalizedRoot(target.root)]
|
||||
}
|
||||
|
||||
private fun rememberRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { reposById[it.id] = it }
|
||||
rememberRelayRepos(repos.filter { it.route == GitRepositoryRoute.RELAY })
|
||||
}
|
||||
|
||||
private fun rememberRelayRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { relayRepoIdsByRoot[normalizedRoot(it.root)] = it.id }
|
||||
}
|
||||
|
||||
private fun upstreamPath(path: String, query: Map<String, String>): String = buildString {
|
||||
append(path)
|
||||
if (query.isNotEmpty()) {
|
||||
append('?')
|
||||
append(query.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" })
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String =
|
||||
URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
|
||||
|
||||
private fun normalizedRoot(path: String): String {
|
||||
val normalized = path.trim().replace('\\', '/').trimEnd('/')
|
||||
return if (WINDOWS_ROOT.containsMatchIn(normalized) || normalized.startsWith("//")) {
|
||||
normalized.lowercase(Locale.ROOT)
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
private fun sameRoot(first: String, second: String): Boolean =
|
||||
normalizedRoot(first) == normalizedRoot(second)
|
||||
|
||||
private fun Result<kotlinx.serialization.json.JsonObject>.decodeMutation(): Result<GitMutationResult> =
|
||||
mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
private fun Throwable.isUnsupportedGitRoute(): Boolean =
|
||||
this is DashboardHttpException && statusCode == 404
|
||||
|
||||
private companion object {
|
||||
const val UPSTREAM_SESSION_REPO_ID = "__upstream_session__"
|
||||
val WINDOWS_ROOT = Regex("^[A-Za-z]:/")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatus(
|
||||
val branch: String? = null,
|
||||
val staged: Int = 0,
|
||||
val unstaged: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
val changed: Int = 0,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val files: List<UpstreamStatusFile> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatusFile(
|
||||
val path: String,
|
||||
val staged: Boolean = false,
|
||||
val unstaged: Boolean = false,
|
||||
val untracked: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewList(val files: List<UpstreamReviewFile> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewFile(
|
||||
val path: String,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val staged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranches(val branches: List<UpstreamBranch> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranch(
|
||||
val name: String,
|
||||
@SerialName("checkedOut") val checkedOut: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamDiffResponse(val diff: String = "")
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** A current-session upstream repository or a Relay-discovered repository. */
|
||||
@Serializable
|
||||
data class GitRepo(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val root: String,
|
||||
@SerialName("current_branch") val currentBranch: String? = null,
|
||||
val dirty: Boolean = false,
|
||||
val route: GitRepositoryRoute = GitRepositoryRoute.RELAY,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
enum class GitRepositoryRoute {
|
||||
@SerialName("relay")
|
||||
RELAY,
|
||||
|
||||
@SerialName("upstream")
|
||||
UPSTREAM,
|
||||
}
|
||||
|
||||
/** Normalized working-tree status from upstream or Relay Git routes. */
|
||||
@Serializable
|
||||
data class GitStatus(
|
||||
val counts: GitStatusCounts = GitStatusCounts(),
|
||||
val staged: List<GitStatusEntry> = emptyList(),
|
||||
val modified: List<GitStatusEntry> = emptyList(),
|
||||
val untracked: List<GitStatusEntry> = emptyList(),
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class GitStatusCounts(
|
||||
val staged: Int = 0,
|
||||
val modified: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
/** Unique changed paths. -1 means an older plugin did not provide it. */
|
||||
val changes: Int = -1,
|
||||
val additions: Int = 0,
|
||||
val deletions: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class GitStatusEntry(
|
||||
val path: String,
|
||||
val additions: Int? = null,
|
||||
val deletions: Int? = null,
|
||||
)
|
||||
|
||||
/** A branch from /git/branches. */
|
||||
@Serializable
|
||||
data class GitBranch(
|
||||
val name: String,
|
||||
val upstream: String? = null,
|
||||
val ahead: Int = 0,
|
||||
val behind: Int = 0,
|
||||
@SerialName("is_current") val isCurrent: Boolean = false,
|
||||
)
|
||||
|
||||
/** A per-file diff from /git/diff. */
|
||||
@Serializable
|
||||
data class GitDiff(
|
||||
val path: String,
|
||||
val kind: String,
|
||||
val diff: String,
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
/** A tracked-file read from /git/file. */
|
||||
@Serializable
|
||||
data class GitFile(
|
||||
val path: String,
|
||||
val content: String,
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
/** Wrapper for /git/repos response. */
|
||||
@Serializable
|
||||
internal data class ReposResponse(
|
||||
val repos: List<GitRepo> = emptyList(),
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
/** Wrapper for /git/branches response. */
|
||||
@Serializable
|
||||
internal data class BranchesResponse(
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
)
|
||||
|
||||
/** A mutation response: fresh HEAD oid + working-tree status (+ branches). */
|
||||
@Serializable
|
||||
data class GitMutationResult(
|
||||
val head: String = "",
|
||||
val status: GitStatus = GitStatus(),
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
)
|
||||
|
||||
/** A /git/commit_message suggestion: generated message + optional notice. */
|
||||
@Serializable
|
||||
data class GitCommitMessage(
|
||||
val message: String = "",
|
||||
val notice: String = "",
|
||||
)
|
||||
|
||||
/** A /git/stash_checkout result: standard mutation shape + stash flag/message. */
|
||||
@Serializable
|
||||
data class GitStashCheckoutResult(
|
||||
val head: String = "",
|
||||
val status: GitStatus = GitStatus(),
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
val stashed: Boolean = false,
|
||||
@SerialName("stash_message") val stashMessage: String = "",
|
||||
)
|
||||
@@ -71,6 +71,8 @@ data class HermesCard(
|
||||
* actions.
|
||||
*/
|
||||
val input: HermesCardInput? = null,
|
||||
/** Local Gateway batch; never an ordinary chat-message answer protocol. */
|
||||
val clarifyBatch: HermesCardClarifyBatch? = null,
|
||||
) {
|
||||
object BuiltInTypes {
|
||||
const val SKILL_RESULT = "skill_result"
|
||||
@@ -96,6 +98,25 @@ data class HermesCard(
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class HermesCardClarifyBatch(
|
||||
val questions: List<HermesCardClarifyQuestion>,
|
||||
val expiresAtMillis: Long? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class HermesCardClarifyQuestion(
|
||||
val key: String,
|
||||
val question: String,
|
||||
val input: HermesCardInput,
|
||||
val answer: String? = null,
|
||||
val submitting: Boolean = false,
|
||||
)
|
||||
|
||||
/** Local callback identity. The RPC always uses the original qid, never this UI key. */
|
||||
fun clarifyQuestionCardKey(cardKey: String, qid: String): String =
|
||||
Json.encodeToString(listOf(cardKey, qid))
|
||||
|
||||
/**
|
||||
* Interactive input slot on a [HermesCard]. The flags compose rather than
|
||||
* branch — a sudo ask can be `masked + holdToConfirm` (password field whose
|
||||
|
||||
@@ -38,6 +38,8 @@ data class ProactiveInboxEntry(
|
||||
val connectionId: String? = null,
|
||||
/** Relay proved this row came from its bounded offline queue. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
/** Exact Android notification slot, when recorded by the receiving build. */
|
||||
val notificationId: Int? = null,
|
||||
)
|
||||
|
||||
private val Context.proactiveInboxStore: DataStore<Preferences> by
|
||||
@@ -58,15 +60,19 @@ private const val MAX_ENTRIES = 100
|
||||
* 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) {
|
||||
class ProactiveInboxRepository internal constructor(
|
||||
private val store: DataStore<Preferences>,
|
||||
) {
|
||||
|
||||
constructor(context: Context) : this(context.proactiveInboxStore)
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
val entries: Flow<List<ProactiveInboxEntry>> =
|
||||
context.proactiveInboxStore.data.map { prefs -> decode(prefs[INBOX_JSON]) }
|
||||
store.data.map { prefs -> decode(prefs[INBOX_JSON]) }
|
||||
|
||||
suspend fun add(entry: ProactiveInboxEntry) {
|
||||
context.proactiveInboxStore.edit { prefs ->
|
||||
store.edit { prefs ->
|
||||
val current = decode(prefs[INBOX_JSON]).toMutableList()
|
||||
current.removeAll { it.id == entry.id }
|
||||
current.add(0, entry)
|
||||
@@ -76,7 +82,40 @@ class ProactiveInboxRepository(private val context: Context) {
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
context.proactiveInboxStore.edit { it.remove(INBOX_JSON) }
|
||||
store.edit { it.remove(INBOX_JSON) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one provisional Thread owned by one saved connection.
|
||||
*
|
||||
* This only edits the bounded local inbox. A promoted Thread is server
|
||||
* history and is deliberately outside this repository, so this operation
|
||||
* can never delete it. Legacy entries without a connection owner are
|
||||
* removed with the active row because they are rendered in that row; rows
|
||||
* explicitly owned by another connection remain isolated.
|
||||
*/
|
||||
suspend fun removeThread(
|
||||
chatId: String,
|
||||
connectionId: String,
|
||||
): List<ProactiveInboxEntry> {
|
||||
val normalizedChatId = chatId.ifBlank { "phone" }
|
||||
var removed = emptyList<ProactiveInboxEntry>()
|
||||
store.edit { prefs ->
|
||||
val current = decode(prefs[INBOX_JSON])
|
||||
removed = current.filter {
|
||||
(it.connectionId == null || it.connectionId == connectionId) &&
|
||||
(it.chatId ?: "phone") == normalizedChatId
|
||||
}
|
||||
if (removed.isNotEmpty()) {
|
||||
val retained = current.filterNot { it in removed }
|
||||
if (retained.isEmpty()) {
|
||||
prefs.remove(INBOX_JSON)
|
||||
} else {
|
||||
prefs[INBOX_JSON] = json.encodeToString(retained)
|
||||
}
|
||||
}
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): List<ProactiveInboxEntry> {
|
||||
|
||||
@@ -111,6 +111,8 @@ data class Profile(
|
||||
val hasAvatar: Boolean = false,
|
||||
@SerialName("ui_meta")
|
||||
val uiMeta: JsonObject = JsonObject(emptyMap()),
|
||||
@SerialName("display_name")
|
||||
val displayName: String = "",
|
||||
) {
|
||||
val hasIsolatedApi: Boolean
|
||||
get() = !apiServerUrl.isNullOrBlank()
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
enum class ProviderUsageLandingMode(val storedValue: String) {
|
||||
Summary("summary"),
|
||||
Expanded("expanded"),
|
||||
Hidden("hidden"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): ProviderUsageLandingMode =
|
||||
entries.firstOrNull { it.storedValue == value } ?: Summary
|
||||
}
|
||||
}
|
||||
|
||||
data class ProviderUsagePreferences(
|
||||
val landingMode: ProviderUsageLandingMode = ProviderUsageLandingMode.Summary,
|
||||
val visibleProviders: Set<String> = DEFAULT_VISIBLE_PROVIDERS,
|
||||
) {
|
||||
companion object {
|
||||
val DEFAULT_VISIBLE_PROVIDERS = setOf("openai-codex", "nous", "opencode-go", "supergrok")
|
||||
}
|
||||
}
|
||||
|
||||
class ProviderUsagePreferencesRepository(private val dataStore: DataStore<Preferences>) {
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
companion object {
|
||||
internal val KEY_LANDING_MODE = stringPreferencesKey("provider_usage_landing_mode")
|
||||
internal val KEY_VISIBLE_PROVIDERS = stringSetPreferencesKey("provider_usage_visible_providers")
|
||||
}
|
||||
|
||||
val preferences: Flow<ProviderUsagePreferences> = dataStore.data
|
||||
.map { prefs ->
|
||||
ProviderUsagePreferences(
|
||||
landingMode = ProviderUsageLandingMode.fromStoredValue(prefs[KEY_LANDING_MODE]),
|
||||
visibleProviders = prefs[KEY_VISIBLE_PROVIDERS]
|
||||
?: ProviderUsagePreferences.DEFAULT_VISIBLE_PROVIDERS,
|
||||
)
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setLandingMode(mode: ProviderUsageLandingMode) {
|
||||
dataStore.edit { it[KEY_LANDING_MODE] = mode.storedValue }
|
||||
}
|
||||
|
||||
suspend fun setProviderVisible(providerId: String, visible: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
val current = prefs[KEY_VISIBLE_PROVIDERS]
|
||||
?: ProviderUsagePreferences.DEFAULT_VISIBLE_PROVIDERS
|
||||
prefs[KEY_VISIBLE_PROVIDERS] = if (visible) current + providerId else current - providerId
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,29 @@ data class RelayEndpoints(
|
||||
val healthUrl: String,
|
||||
)
|
||||
|
||||
/** Dashboard plugin namespace used when Relay rides the Dashboard origin. */
|
||||
const val DASHBOARD_RELAY_INGRESS_PATH: String =
|
||||
"/api/plugins/hermes-relay/transport"
|
||||
|
||||
/**
|
||||
* True when [raw] points at the Dashboard-mounted Relay transport rather than
|
||||
* a directly exposed Relay listener. The distinction is authentication
|
||||
* relevant: the outer Dashboard request keeps its cookie/bearer credential,
|
||||
* while Relay's independently scoped session travels in
|
||||
* `X-Hermes-Relay-Session`.
|
||||
*/
|
||||
fun isDashboardRelayIngressUrl(raw: String?): Boolean {
|
||||
val endpoints = RelayEndpointContract.parseOrNull(raw) ?: return false
|
||||
val path = runCatching { URI(endpoints.httpBaseUrl).rawPath.orEmpty() }
|
||||
.getOrDefault("")
|
||||
.trimEnd('/')
|
||||
val marker = path.indexOf(DASHBOARD_RELAY_INGRESS_PATH)
|
||||
if (marker < 0) return false
|
||||
val markerEndsAt = marker + DASHBOARD_RELAY_INGRESS_PATH.length
|
||||
val suffixBoundary = markerEndsAt == path.length || path[markerEndsAt] == '/'
|
||||
return suffixBoundary
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the accepted Relay URL forms and derives every route from one base.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/** Stable ownership boundary for live activity. Runtime ids are aliases, never owners. */
|
||||
@ConsistentCopyVisibility
|
||||
data class SessionActivityOwner private constructor(
|
||||
val connectionId: String,
|
||||
val profile: String,
|
||||
val storedSessionId: String,
|
||||
) {
|
||||
companion object {
|
||||
fun of(connectionId: String, profile: String, storedSessionId: String) =
|
||||
SessionActivityOwner(
|
||||
connectionId = connectionId.trim(),
|
||||
profile = profile.trim().lowercase(Locale.ROOT),
|
||||
storedSessionId = storedSessionId.trim(),
|
||||
).also {
|
||||
require(it.connectionId.isNotEmpty()) { "connectionId must not be blank" }
|
||||
require(it.profile.isNotEmpty()) { "profile must not be blank" }
|
||||
require(it.storedSessionId.isNotEmpty()) { "storedSessionId must not be blank" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ConsistentCopyVisibility
|
||||
data class SessionActivityScope private constructor(
|
||||
val connectionId: String,
|
||||
val profile: String,
|
||||
) {
|
||||
companion object {
|
||||
fun of(connectionId: String, profile: String) = SessionActivityScope(
|
||||
connectionId = connectionId.trim(),
|
||||
profile = profile.trim().lowercase(Locale.ROOT),
|
||||
).also {
|
||||
require(it.connectionId.isNotEmpty()) { "connectionId must not be blank" }
|
||||
require(it.profile.isNotEmpty()) { "profile must not be blank" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class SessionActivityPhase {
|
||||
Starting,
|
||||
Working,
|
||||
NeedsInput,
|
||||
BackgroundWork,
|
||||
Idle,
|
||||
}
|
||||
|
||||
enum class SessionActivityFreshness {
|
||||
Confirmed,
|
||||
Revalidating,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
enum class SessionActivityEvidenceSource {
|
||||
Directory,
|
||||
LocalSend,
|
||||
ActiveList,
|
||||
SessionEvent,
|
||||
PendingInput,
|
||||
Terminal,
|
||||
Checkpoint,
|
||||
Process,
|
||||
}
|
||||
|
||||
data class SessionActivityEvidence(
|
||||
val source: SessionActivityEvidenceSource,
|
||||
val generation: Long,
|
||||
val observedAtMillis: Long,
|
||||
)
|
||||
|
||||
data class SessionActivityRecord(
|
||||
val owner: SessionActivityOwner,
|
||||
/** Authoritative turn state before exact pending-input and background-process overlays. */
|
||||
val turnPhase: SessionActivityPhase,
|
||||
val freshness: SessionActivityFreshness,
|
||||
val evidence: SessionActivityEvidence,
|
||||
val runtimeId: String? = null,
|
||||
val pendingInputs: Map<String, Long?> = emptyMap(),
|
||||
val backgroundProcessIds: Set<String> = emptySet(),
|
||||
) {
|
||||
fun phase(nowMillis: Long = Long.MIN_VALUE): SessionActivityPhase {
|
||||
val hasPendingInput = pendingInputs.any { (_, expiresAt) -> expiresAt == null || expiresAt > nowMillis }
|
||||
return when {
|
||||
hasPendingInput -> SessionActivityPhase.NeedsInput
|
||||
turnPhase != SessionActivityPhase.Idle -> turnPhase
|
||||
backgroundProcessIds.isNotEmpty() -> SessionActivityPhase.BackgroundWork
|
||||
else -> SessionActivityPhase.Idle
|
||||
}
|
||||
}
|
||||
|
||||
/** Presentation projection that never labels missing optional runtime data as session state. */
|
||||
fun presentationState(nowMillis: Long = Long.MIN_VALUE): SessionActivityState? = when (freshness) {
|
||||
SessionActivityFreshness.Revalidating -> null
|
||||
SessionActivityFreshness.Unavailable -> null
|
||||
SessionActivityFreshness.Confirmed -> when (phase(nowMillis)) {
|
||||
SessionActivityPhase.Starting -> SessionActivityState.Starting
|
||||
SessionActivityPhase.Working -> SessionActivityState.Working
|
||||
SessionActivityPhase.NeedsInput -> SessionActivityState.NeedsInput
|
||||
SessionActivityPhase.BackgroundWork -> SessionActivityState.BackgroundWork
|
||||
SessionActivityPhase.Idle -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class SessionLiveStatus {
|
||||
Starting,
|
||||
Working,
|
||||
Waiting,
|
||||
Idle,
|
||||
}
|
||||
|
||||
data class SessionLiveRuntime(
|
||||
/** Null when transport data cannot be resolved uniquely to a stored session owner. */
|
||||
val owner: SessionActivityOwner?,
|
||||
val runtimeId: String,
|
||||
val status: SessionLiveStatus,
|
||||
)
|
||||
|
||||
sealed interface SessionActivityUpdate {
|
||||
val generation: Long
|
||||
val observedAtMillis: Long
|
||||
|
||||
data class BeginGeneration(
|
||||
val scope: SessionActivityScope,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class ObserveOwner(
|
||||
val owner: SessionActivityOwner,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class LocalSend(
|
||||
val owner: SessionActivityOwner,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class LiveState(
|
||||
val owner: SessionActivityOwner,
|
||||
val runtimeId: String?,
|
||||
val status: SessionLiveStatus,
|
||||
val source: SessionActivityEvidenceSource = SessionActivityEvidenceSource.SessionEvent,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class RuntimeState(
|
||||
val scope: SessionActivityScope,
|
||||
val runtimeId: String,
|
||||
val status: SessionLiveStatus,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class ActiveList(
|
||||
val scope: SessionActivityScope,
|
||||
val runtimes: List<SessionLiveRuntime>,
|
||||
/** True only when every upstream row was safely attributable for this scope. */
|
||||
val isCompleteForScope: Boolean,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class StatusUnavailable(
|
||||
val scope: SessionActivityScope,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class Terminal(
|
||||
val owner: SessionActivityOwner,
|
||||
val runtimeId: String? = null,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class RestoreCheckpoint(
|
||||
val owner: SessionActivityOwner,
|
||||
val runtimeId: String?,
|
||||
val phase: SessionActivityPhase,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class PendingInputOpened(
|
||||
val owner: SessionActivityOwner,
|
||||
val requestId: String,
|
||||
val expiresAtMillis: Long? = null,
|
||||
val confirmed: Boolean = true,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class PendingInputClosed(
|
||||
val owner: SessionActivityOwner,
|
||||
val requestId: String,
|
||||
val confirmed: Boolean = true,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class ProcessState(
|
||||
val owner: SessionActivityOwner,
|
||||
val processId: String,
|
||||
val running: Boolean,
|
||||
override val generation: Long,
|
||||
override val observedAtMillis: Long,
|
||||
) : SessionActivityUpdate
|
||||
|
||||
data class Tick(
|
||||
val nowMillis: Long,
|
||||
override val generation: Long = Long.MAX_VALUE,
|
||||
override val observedAtMillis: Long = nowMillis,
|
||||
) : SessionActivityUpdate
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure reducer for session activity. Every update is generation-gated per connection/profile.
|
||||
* An unsuccessful/unsupported refresh never manufactures an idle result.
|
||||
*/
|
||||
data class SessionActivityRegistry(
|
||||
val records: Map<SessionActivityOwner, SessionActivityRecord> = emptyMap(),
|
||||
private val runtimeAliases: Map<RuntimeAlias, SessionActivityOwner> = emptyMap(),
|
||||
private val generations: Map<SessionActivityScope, Long> = emptyMap(),
|
||||
) {
|
||||
fun record(owner: SessionActivityOwner): SessionActivityRecord? = records[owner]
|
||||
|
||||
fun ownerForRuntime(scope: SessionActivityScope, runtimeId: String): SessionActivityOwner? =
|
||||
runtimeAliases[RuntimeAlias(scope, runtimeId.trim(), generations[scope] ?: return null)]
|
||||
|
||||
fun presentationStates(nowMillis: Long = Long.MIN_VALUE): Map<SessionActivityOwner, SessionActivityState> =
|
||||
records.mapNotNull { (owner, record) -> record.presentationState(nowMillis)?.let { owner to it } }.toMap()
|
||||
|
||||
fun reduce(update: SessionActivityUpdate): SessionActivityRegistry {
|
||||
if (update is SessionActivityUpdate.Tick) return expirePendingInputs(update.nowMillis)
|
||||
val scope = update.scope()
|
||||
val currentGeneration = generations[scope]
|
||||
if (currentGeneration != null && update.generation < currentGeneration) return this
|
||||
|
||||
var state = this
|
||||
if (currentGeneration == null || update.generation > currentGeneration) {
|
||||
state = state.beginGeneration(scope, update.generation)
|
||||
}
|
||||
|
||||
return when (update) {
|
||||
is SessionActivityUpdate.BeginGeneration -> state
|
||||
is SessionActivityUpdate.ObserveOwner -> state.observeOwner(update)
|
||||
is SessionActivityUpdate.LocalSend -> state.putTurn(
|
||||
update.owner, null, SessionActivityPhase.Starting, SessionActivityFreshness.Confirmed,
|
||||
SessionActivityEvidenceSource.LocalSend, update.generation, update.observedAtMillis,
|
||||
)
|
||||
is SessionActivityUpdate.LiveState -> state.putLiveState(update)
|
||||
is SessionActivityUpdate.RuntimeState -> {
|
||||
val owner = state.ownerForRuntime(update.scope, update.runtimeId) ?: return state
|
||||
state.putTurn(
|
||||
owner, update.runtimeId, update.status.phase(), SessionActivityFreshness.Confirmed,
|
||||
SessionActivityEvidenceSource.SessionEvent, update.generation, update.observedAtMillis,
|
||||
)
|
||||
}
|
||||
is SessionActivityUpdate.ActiveList -> state.applyActiveList(update)
|
||||
is SessionActivityUpdate.StatusUnavailable -> state.markUnavailable(update.scope)
|
||||
is SessionActivityUpdate.Terminal -> state.settleTerminal(update)
|
||||
is SessionActivityUpdate.RestoreCheckpoint -> state.restoreCheckpoint(update)
|
||||
is SessionActivityUpdate.PendingInputOpened -> state.updatePendingInput(
|
||||
update.owner, update.requestId, update.expiresAtMillis, true,
|
||||
update.confirmed, update.generation, update.observedAtMillis,
|
||||
)
|
||||
is SessionActivityUpdate.PendingInputClosed -> state.updatePendingInput(
|
||||
update.owner, update.requestId, null, false,
|
||||
update.confirmed, update.generation, update.observedAtMillis,
|
||||
)
|
||||
is SessionActivityUpdate.ProcessState -> state.updateProcess(update)
|
||||
is SessionActivityUpdate.Tick -> state
|
||||
}
|
||||
}
|
||||
|
||||
private fun beginGeneration(scope: SessionActivityScope, generation: Long): SessionActivityRegistry {
|
||||
val refreshedRecords = records.mapValues { (owner, record) ->
|
||||
if (owner.scope() == scope) {
|
||||
record.copy(freshness = SessionActivityFreshness.Revalidating)
|
||||
} else record
|
||||
}
|
||||
return copy(
|
||||
records = refreshedRecords,
|
||||
runtimeAliases = runtimeAliases.filterKeys { it.scope != scope },
|
||||
generations = generations + (scope to generation),
|
||||
)
|
||||
}
|
||||
|
||||
private fun observeOwner(update: SessionActivityUpdate.ObserveOwner): SessionActivityRegistry {
|
||||
val existing = records[update.owner]
|
||||
// Directory rows establish ownership only. They are not live evidence and must not
|
||||
// turn an unsupported/failed active-list probe back into a permanent Checking row.
|
||||
if (existing != null) return this
|
||||
val observed = SessionActivityRecord(
|
||||
owner = update.owner,
|
||||
turnPhase = SessionActivityPhase.Idle,
|
||||
freshness = SessionActivityFreshness.Revalidating,
|
||||
evidence = SessionActivityEvidence(
|
||||
SessionActivityEvidenceSource.Directory,
|
||||
update.generation,
|
||||
update.observedAtMillis,
|
||||
),
|
||||
)
|
||||
return copy(records = records + (update.owner to observed))
|
||||
}
|
||||
|
||||
private fun putLiveState(update: SessionActivityUpdate.LiveState): SessionActivityRegistry = putTurn(
|
||||
owner = update.owner,
|
||||
runtimeId = update.runtimeId,
|
||||
phase = update.status.phase(),
|
||||
freshness = SessionActivityFreshness.Confirmed,
|
||||
source = update.source,
|
||||
generation = update.generation,
|
||||
observedAtMillis = update.observedAtMillis,
|
||||
)
|
||||
|
||||
private fun putTurn(
|
||||
owner: SessionActivityOwner,
|
||||
runtimeId: String?,
|
||||
phase: SessionActivityPhase,
|
||||
freshness: SessionActivityFreshness,
|
||||
source: SessionActivityEvidenceSource,
|
||||
generation: Long,
|
||||
observedAtMillis: Long,
|
||||
): SessionActivityRegistry {
|
||||
val previous = records[owner]
|
||||
val record = SessionActivityRecord(
|
||||
owner = owner,
|
||||
turnPhase = phase,
|
||||
freshness = freshness,
|
||||
evidence = SessionActivityEvidence(source, generation, observedAtMillis),
|
||||
runtimeId = runtimeId ?: previous?.runtimeId,
|
||||
pendingInputs = previous?.pendingInputs.orEmpty(),
|
||||
backgroundProcessIds = previous?.backgroundProcessIds.orEmpty(),
|
||||
)
|
||||
val alias = runtimeId?.trim()?.takeIf { it.isNotEmpty() }
|
||||
return copy(
|
||||
records = records + (owner to record),
|
||||
runtimeAliases = if (alias == null) runtimeAliases else {
|
||||
runtimeAliases + (RuntimeAlias(owner.scope(), alias, generation) to owner)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyActiveList(update: SessionActivityUpdate.ActiveList): SessionActivityRegistry {
|
||||
require(update.runtimes.all { it.owner == null || it.owner.scope() == update.scope }) {
|
||||
"Active-list rows must belong to the snapshot scope"
|
||||
}
|
||||
var state = copy(runtimeAliases = runtimeAliases.filterKeys { it.scope != update.scope })
|
||||
val resolvedRuntimes = update.runtimes.filter { it.owner != null }
|
||||
val observedOwners = resolvedRuntimes.mapTo(mutableSetOf()) { requireNotNull(it.owner) }
|
||||
resolvedRuntimes.forEach { runtime ->
|
||||
val resolvedOwner = requireNotNull(runtime.owner)
|
||||
state = state.putTurn(
|
||||
resolvedOwner, runtime.runtimeId, runtime.status.phase(), SessionActivityFreshness.Confirmed,
|
||||
SessionActivityEvidenceSource.ActiveList, update.generation, update.observedAtMillis,
|
||||
)
|
||||
if (runtime.status == SessionLiveStatus.Idle) {
|
||||
val idleRecord = requireNotNull(state.records[resolvedOwner]).copy(pendingInputs = emptyMap())
|
||||
state = state.copy(records = state.records + (resolvedOwner to idleRecord))
|
||||
}
|
||||
}
|
||||
val snapshotCanSettle = update.isCompleteForScope && resolvedRuntimes.size == update.runtimes.size
|
||||
if (!snapshotCanSettle) return state
|
||||
val settled = state.records.mapValues { (owner, record) ->
|
||||
if (
|
||||
owner.scope() == update.scope && owner !in observedOwners &&
|
||||
record.shouldSettleWhenAbsent()
|
||||
) {
|
||||
record.copy(
|
||||
turnPhase = SessionActivityPhase.Idle,
|
||||
freshness = SessionActivityFreshness.Confirmed,
|
||||
runtimeId = null,
|
||||
pendingInputs = emptyMap(),
|
||||
evidence = SessionActivityEvidence(
|
||||
SessionActivityEvidenceSource.ActiveList,
|
||||
update.generation,
|
||||
update.observedAtMillis,
|
||||
),
|
||||
)
|
||||
} else record
|
||||
}
|
||||
return state.copy(records = settled)
|
||||
}
|
||||
|
||||
private fun markUnavailable(scope: SessionActivityScope): SessionActivityRegistry = copy(
|
||||
records = records.mapValues { (owner, record) ->
|
||||
if (
|
||||
owner.scope() == scope && record.evidence.source in setOf(
|
||||
SessionActivityEvidenceSource.ActiveList,
|
||||
SessionActivityEvidenceSource.Directory,
|
||||
SessionActivityEvidenceSource.Checkpoint,
|
||||
)
|
||||
) {
|
||||
record.copy(freshness = SessionActivityFreshness.Unavailable)
|
||||
} else record
|
||||
},
|
||||
)
|
||||
|
||||
private fun settleTerminal(update: SessionActivityUpdate.Terminal): SessionActivityRegistry {
|
||||
val settled = putTurn(
|
||||
update.owner,
|
||||
runtimeId = null,
|
||||
phase = SessionActivityPhase.Idle,
|
||||
freshness = SessionActivityFreshness.Confirmed,
|
||||
source = SessionActivityEvidenceSource.Terminal,
|
||||
generation = update.generation,
|
||||
observedAtMillis = update.observedAtMillis,
|
||||
)
|
||||
val record = requireNotNull(settled.records[update.owner]).copy(
|
||||
runtimeId = null,
|
||||
pendingInputs = emptyMap(),
|
||||
)
|
||||
return settled.copy(
|
||||
records = settled.records + (update.owner to record),
|
||||
runtimeAliases = settled.runtimeAliases.filterNot { (alias, owner) ->
|
||||
alias.scope == update.owner.scope() && owner == update.owner &&
|
||||
(update.runtimeId == null || alias.runtimeId == update.runtimeId)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun restoreCheckpoint(update: SessionActivityUpdate.RestoreCheckpoint): SessionActivityRegistry {
|
||||
val existing = records[update.owner]
|
||||
if (existing?.freshness == SessionActivityFreshness.Confirmed) return this
|
||||
return putTurn(
|
||||
update.owner, update.runtimeId, update.phase, SessionActivityFreshness.Revalidating,
|
||||
SessionActivityEvidenceSource.Checkpoint, update.generation, update.observedAtMillis,
|
||||
)
|
||||
}
|
||||
|
||||
private fun updatePendingInput(
|
||||
owner: SessionActivityOwner,
|
||||
requestId: String,
|
||||
expiresAtMillis: Long?,
|
||||
opened: Boolean,
|
||||
confirmed: Boolean,
|
||||
generation: Long,
|
||||
observedAtMillis: Long,
|
||||
): SessionActivityRegistry {
|
||||
val previous = records[owner] ?: SessionActivityRecord(
|
||||
owner = owner,
|
||||
turnPhase = SessionActivityPhase.Idle,
|
||||
freshness = if (confirmed) {
|
||||
SessionActivityFreshness.Confirmed
|
||||
} else {
|
||||
SessionActivityFreshness.Revalidating
|
||||
},
|
||||
evidence = SessionActivityEvidence(
|
||||
if (confirmed) {
|
||||
SessionActivityEvidenceSource.PendingInput
|
||||
} else {
|
||||
SessionActivityEvidenceSource.Checkpoint
|
||||
},
|
||||
generation,
|
||||
observedAtMillis,
|
||||
),
|
||||
)
|
||||
val pending = if (opened) {
|
||||
previous.pendingInputs + (requestId to expiresAtMillis)
|
||||
} else {
|
||||
previous.pendingInputs - requestId
|
||||
}
|
||||
return copy(records = records + (owner to previous.copy(
|
||||
pendingInputs = pending,
|
||||
freshness = if (confirmed) SessionActivityFreshness.Confirmed else previous.freshness,
|
||||
evidence = if (confirmed) {
|
||||
SessionActivityEvidence(
|
||||
SessionActivityEvidenceSource.PendingInput,
|
||||
generation,
|
||||
observedAtMillis,
|
||||
)
|
||||
} else previous.evidence,
|
||||
)))
|
||||
}
|
||||
|
||||
private fun updateProcess(update: SessionActivityUpdate.ProcessState): SessionActivityRegistry {
|
||||
val previous = records[update.owner] ?: SessionActivityRecord(
|
||||
owner = update.owner,
|
||||
turnPhase = SessionActivityPhase.Idle,
|
||||
freshness = SessionActivityFreshness.Confirmed,
|
||||
evidence = SessionActivityEvidence(
|
||||
SessionActivityEvidenceSource.Process,
|
||||
update.generation,
|
||||
update.observedAtMillis,
|
||||
),
|
||||
)
|
||||
val processes = if (update.running) {
|
||||
previous.backgroundProcessIds + update.processId
|
||||
} else {
|
||||
previous.backgroundProcessIds - update.processId
|
||||
}
|
||||
return copy(records = records + (update.owner to previous.copy(
|
||||
backgroundProcessIds = processes,
|
||||
evidence = SessionActivityEvidence(
|
||||
SessionActivityEvidenceSource.Process,
|
||||
update.generation,
|
||||
update.observedAtMillis,
|
||||
),
|
||||
)))
|
||||
}
|
||||
|
||||
private fun expirePendingInputs(nowMillis: Long): SessionActivityRegistry = copy(
|
||||
records = records.mapValues { (_, record) ->
|
||||
record.copy(pendingInputs = record.pendingInputs.filterValues { it == null || it > nowMillis })
|
||||
},
|
||||
)
|
||||
|
||||
private fun SessionActivityRecord.shouldSettleWhenAbsent(): Boolean =
|
||||
runtimeId != null || evidence.source in setOf(
|
||||
SessionActivityEvidenceSource.ActiveList,
|
||||
SessionActivityEvidenceSource.Checkpoint,
|
||||
SessionActivityEvidenceSource.Directory,
|
||||
)
|
||||
|
||||
private fun SessionActivityUpdate.scope(): SessionActivityScope = when (this) {
|
||||
is SessionActivityUpdate.BeginGeneration -> scope
|
||||
is SessionActivityUpdate.ObserveOwner -> owner.scope()
|
||||
is SessionActivityUpdate.RuntimeState -> scope
|
||||
is SessionActivityUpdate.ActiveList -> scope
|
||||
is SessionActivityUpdate.StatusUnavailable -> scope
|
||||
is SessionActivityUpdate.Terminal -> owner.scope()
|
||||
is SessionActivityUpdate.LocalSend -> owner.scope()
|
||||
is SessionActivityUpdate.LiveState -> owner.scope()
|
||||
is SessionActivityUpdate.RestoreCheckpoint -> owner.scope()
|
||||
is SessionActivityUpdate.PendingInputOpened -> owner.scope()
|
||||
is SessionActivityUpdate.PendingInputClosed -> owner.scope()
|
||||
is SessionActivityUpdate.ProcessState -> owner.scope()
|
||||
is SessionActivityUpdate.Tick -> error("Tick has no scope")
|
||||
}
|
||||
|
||||
private fun SessionActivityOwner.scope() = SessionActivityScope.of(connectionId, profile)
|
||||
|
||||
private fun SessionLiveStatus.phase(): SessionActivityPhase = when (this) {
|
||||
SessionLiveStatus.Starting -> SessionActivityPhase.Starting
|
||||
SessionLiveStatus.Working -> SessionActivityPhase.Working
|
||||
SessionLiveStatus.Waiting -> SessionActivityPhase.NeedsInput
|
||||
SessionLiveStatus.Idle -> SessionActivityPhase.Idle
|
||||
}
|
||||
|
||||
data class RuntimeAlias(
|
||||
val scope: SessionActivityScope,
|
||||
val runtimeId: String,
|
||||
val generation: Long,
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,10 @@ package com.hermesandroid.relay.data
|
||||
|
||||
/** Live activity surfaced beside a session without conflating it with selection. */
|
||||
enum class SessionActivityState {
|
||||
Starting,
|
||||
Working,
|
||||
NeedsInput,
|
||||
BackgroundWork,
|
||||
Checking,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import com.hermesandroid.relay.ui.theme.AppThemes
|
||||
|
||||
/**
|
||||
* Parent-configured restrictions for the official Android client.
|
||||
*
|
||||
* This policy deliberately describes a client presentation mode, not a server
|
||||
* authorization boundary. The pinned profile is expected to have already been
|
||||
* configured with the appropriate server-side tool and content restrictions.
|
||||
*/
|
||||
@Serializable
|
||||
data class SupervisedModePolicy(
|
||||
val enabled: Boolean = false,
|
||||
val pinnedProfileName: String? = null,
|
||||
val capabilities: SupervisedCapabilities = SupervisedCapabilities(),
|
||||
val appearance: SupervisedAppearance = SupervisedAppearance(),
|
||||
val visibility: SupervisedVisibility = SupervisedVisibility(),
|
||||
val parentAccess: SupervisedParentAccess = SupervisedParentAccess(),
|
||||
) {
|
||||
/** A saved policy is usable only when it names a concrete Hermes profile. */
|
||||
val isConfigured: Boolean
|
||||
get() = !pinnedProfileName.isNullOrBlank()
|
||||
|
||||
/** Consumers should use this instead of treating [enabled] alone as sufficient. */
|
||||
val isActive: Boolean
|
||||
get() = enabled && isConfigured
|
||||
|
||||
internal fun normalized(): SupervisedModePolicy = copy(
|
||||
pinnedProfileName = pinnedProfileName?.trim()?.takeIf { it.isNotEmpty() },
|
||||
capabilities = capabilities.normalized(),
|
||||
appearance = appearance.normalized(),
|
||||
parentAccess = parentAccess.normalized(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Actions and content types the supervised chat surface may expose. */
|
||||
@Serializable
|
||||
data class SupervisedCapabilities(
|
||||
val attachments: Boolean = false,
|
||||
val voice: Boolean = false,
|
||||
val generatedImages: Boolean = true,
|
||||
val conversationHistory: Boolean = false,
|
||||
val newChat: Boolean = true,
|
||||
val cancelResponse: Boolean = true,
|
||||
val steerResponse: Boolean = true,
|
||||
val retryResponse: Boolean = true,
|
||||
val copyResponses: Boolean = true,
|
||||
val quoteReplies: Boolean = true,
|
||||
val editAndResend: Boolean = false,
|
||||
val shareGeneratedImages: Boolean = false,
|
||||
val sessionActions: SupervisedSessionActions = SupervisedSessionActions(),
|
||||
val attachmentMaxCount: Int = DEFAULT_ATTACHMENT_MAX_COUNT,
|
||||
val attachmentMaxFileMb: Int = DEFAULT_ATTACHMENT_MAX_FILE_MB,
|
||||
val attachmentCategories: Set<SupervisedAttachmentCategory> = setOf(
|
||||
SupervisedAttachmentCategory.Images,
|
||||
),
|
||||
) {
|
||||
internal fun normalized(): SupervisedCapabilities = copy(
|
||||
attachmentMaxCount = attachmentMaxCount.coerceIn(1, MAX_ATTACHMENT_COUNT),
|
||||
attachmentMaxFileMb = attachmentMaxFileMb.coerceIn(1, MAX_ATTACHMENT_FILE_MB),
|
||||
attachmentCategories = attachmentCategories.ifEmpty {
|
||||
setOf(SupervisedAttachmentCategory.Images)
|
||||
},
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_ATTACHMENT_MAX_COUNT = 4
|
||||
const val DEFAULT_ATTACHMENT_MAX_FILE_MB = 10
|
||||
const val MAX_ATTACHMENT_COUNT = 10
|
||||
const val MAX_ATTACHMENT_FILE_MB = 100
|
||||
}
|
||||
}
|
||||
|
||||
/** Appearance applied only while the supervised root is locked. */
|
||||
@Serializable
|
||||
data class SupervisedAppearance(
|
||||
val appThemeId: String = AppThemes.DEFAULT_ID,
|
||||
val themePreference: String = "auto",
|
||||
val showPet: Boolean = false,
|
||||
val allowProfileIconChanges: Boolean = false,
|
||||
val allowBackgroundChanges: Boolean = false,
|
||||
) {
|
||||
internal fun normalized(): SupervisedAppearance = copy(
|
||||
appThemeId = AppThemes.byId(appThemeId).id,
|
||||
themePreference = themePreference.takeIf { it in VALID_THEME_PREFERENCES } ?: "auto",
|
||||
)
|
||||
|
||||
private companion object {
|
||||
val VALID_THEME_PREFERENCES = setOf("auto", "light", "dark")
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutable operations available from a supervised conversation-history row. */
|
||||
@Serializable
|
||||
data class SupervisedSessionActions(
|
||||
val pin: Boolean = false,
|
||||
val rename: Boolean = false,
|
||||
val archive: Boolean = false,
|
||||
val delete: Boolean = false,
|
||||
val shareTranscript: Boolean = false,
|
||||
) {
|
||||
val enabledCount: Int
|
||||
get() = listOf(pin, rename, archive, delete, shareTranscript).count { it }
|
||||
|
||||
val allEnabled: Boolean
|
||||
get() = enabledCount == TOTAL
|
||||
|
||||
val noneEnabled: Boolean
|
||||
get() = enabledCount == 0
|
||||
|
||||
fun withAll(enabled: Boolean): SupervisedSessionActions = SupervisedSessionActions(
|
||||
pin = enabled,
|
||||
rename = enabled,
|
||||
archive = enabled,
|
||||
delete = enabled,
|
||||
shareTranscript = enabled,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val TOTAL = 5
|
||||
}
|
||||
}
|
||||
|
||||
enum class SupervisedSessionAction {
|
||||
Pin,
|
||||
Rename,
|
||||
Archive,
|
||||
Delete,
|
||||
ShareTranscript,
|
||||
}
|
||||
|
||||
fun SupervisedModePolicy.allowsSessionAction(action: SupervisedSessionAction): Boolean {
|
||||
if (!enabled) return true
|
||||
if (!capabilities.conversationHistory) return false
|
||||
return when (action) {
|
||||
SupervisedSessionAction.Pin -> capabilities.sessionActions.pin
|
||||
SupervisedSessionAction.Rename -> capabilities.sessionActions.rename
|
||||
SupervisedSessionAction.Archive -> capabilities.sessionActions.archive
|
||||
SupervisedSessionAction.Delete -> capabilities.sessionActions.delete
|
||||
SupervisedSessionAction.ShareTranscript -> capabilities.sessionActions.shareTranscript
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
enum class SupervisedAttachmentCategory {
|
||||
@SerialName("images")
|
||||
Images,
|
||||
|
||||
@SerialName("documents")
|
||||
Documents,
|
||||
|
||||
@SerialName("audio")
|
||||
Audio,
|
||||
|
||||
@SerialName("video")
|
||||
Video,
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls which metadata and conversation affordances are rendered.
|
||||
*
|
||||
* [Simple] is the quiet default. [Transparent] is a useful preset for older or
|
||||
* technical users, while [Custom] tells the UI to honor every stored toggle.
|
||||
*/
|
||||
@Serializable
|
||||
data class SupervisedVisibility(
|
||||
val preset: SupervisedVisibilityPreset = SupervisedVisibilityPreset.Simple,
|
||||
val showAgentIdentity: Boolean = true,
|
||||
val showModelName: Boolean = false,
|
||||
val showProfileName: Boolean = false,
|
||||
val showConnectionStatus: Boolean = true,
|
||||
val showTechnicalRoute: Boolean = false,
|
||||
val showTimestamps: Boolean = true,
|
||||
val showToolNames: Boolean = false,
|
||||
val showToolDetails: Boolean = false,
|
||||
val showWorkingStatus: Boolean = true,
|
||||
val showReasoning: Boolean = false,
|
||||
val showUsage: Boolean = false,
|
||||
) {
|
||||
/** Resolve presets to the concrete flags consumed by chat presentation. */
|
||||
fun resolved(): SupervisedVisibility = when (preset) {
|
||||
SupervisedVisibilityPreset.Simple -> SIMPLE
|
||||
SupervisedVisibilityPreset.Transparent -> TRANSPARENT
|
||||
SupervisedVisibilityPreset.Custom -> this
|
||||
}
|
||||
|
||||
companion object {
|
||||
val SIMPLE = SupervisedVisibility(preset = SupervisedVisibilityPreset.Simple)
|
||||
|
||||
val TRANSPARENT = SupervisedVisibility(
|
||||
preset = SupervisedVisibilityPreset.Transparent,
|
||||
showModelName = true,
|
||||
showProfileName = true,
|
||||
showTechnicalRoute = true,
|
||||
showToolNames = true,
|
||||
showUsage = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
enum class SupervisedVisibilityPreset {
|
||||
@SerialName("simple")
|
||||
Simple,
|
||||
|
||||
@SerialName("transparent")
|
||||
Transparent,
|
||||
|
||||
@SerialName("custom")
|
||||
Custom,
|
||||
}
|
||||
|
||||
/** Device-authentication and automatic relock behavior for parent access. */
|
||||
@Serializable
|
||||
data class SupervisedParentAccess(
|
||||
/** Reserved for forward-compatible persistence; normalization never permits an auth bypass. */
|
||||
val requireDeviceAuthentication: Boolean = true,
|
||||
val relockOnBackground: Boolean = true,
|
||||
val timeoutMinutes: Int = DEFAULT_TIMEOUT_MINUTES,
|
||||
) {
|
||||
internal fun normalized(): SupervisedParentAccess = copy(
|
||||
requireDeviceAuthentication = true,
|
||||
timeoutMinutes = timeoutMinutes.coerceIn(MIN_TIMEOUT_MINUTES, MAX_TIMEOUT_MINUTES),
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_TIMEOUT_MINUTES = 5
|
||||
const val MIN_TIMEOUT_MINUTES = 1
|
||||
const val MAX_TIMEOUT_MINUTES = 60
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.builtins.MapSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Persists one independent [SupervisedModePolicy] per Hermes connection. */
|
||||
class SupervisedModeStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
private val json = Json {
|
||||
encodeDefaults = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
private val serializer = MapSerializer(String.serializer(), SupervisedModePolicy.serializer())
|
||||
|
||||
fun policyFlow(connectionId: String): Flow<SupervisedModePolicy> =
|
||||
dataStore.data.map { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt) {
|
||||
// A malformed persisted policy must never silently reopen the
|
||||
// unrestricted app. Enabled + unconfigured renders the
|
||||
// supervised recovery surface until an authenticated user
|
||||
// repairs or clears the policy.
|
||||
SupervisedModePolicy(enabled = true)
|
||||
} else {
|
||||
decoded.policies[connectionId]?.normalized() ?: SupervisedModePolicy()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setPolicy(connectionId: String, policy: SupervisedModePolicy) {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
policies[connectionId] = policy.normalized()
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun updatePolicy(
|
||||
connectionId: String,
|
||||
transform: (SupervisedModePolicy) -> SupervisedModePolicy,
|
||||
) {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
val current = policies[connectionId]?.normalized() ?: SupervisedModePolicy()
|
||||
policies[connectionId] = transform(current).normalized()
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setEnabled(connectionId: String, enabled: Boolean) {
|
||||
updatePolicy(connectionId) { it.copy(enabled = enabled) }
|
||||
}
|
||||
|
||||
suspend fun clear(connectionId: String) {
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
policies.remove(connectionId)
|
||||
if (policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear supervised policies without disturbing unrelated app settings. */
|
||||
suspend fun clearAll() {
|
||||
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
|
||||
}
|
||||
|
||||
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
|
||||
internal suspend fun disableAllAndRemoveCredential(
|
||||
parentCredentialKey: Preferences.Key<String>,
|
||||
) {
|
||||
dataStore.edit { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt || decoded.policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
val disabled = decoded.policies.mapValues { (_, policy) ->
|
||||
policy.copy(enabled = false).normalized()
|
||||
}
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
|
||||
}
|
||||
preferences.remove(parentCredentialKey)
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodeResult {
|
||||
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
|
||||
return try {
|
||||
DecodeResult(json.decodeFromString(serializer, raw), corrupt = false)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to decode supervised-mode policies; failing closed", error)
|
||||
DecodeResult(emptyMap(), corrupt = true)
|
||||
}
|
||||
}
|
||||
|
||||
private data class DecodeResult(
|
||||
val policies: Map<String, SupervisedModePolicy>,
|
||||
val corrupt: Boolean,
|
||||
)
|
||||
|
||||
internal companion object {
|
||||
private const val TAG = "SupervisedModeStore"
|
||||
private val KEY_POLICIES = stringPreferencesKey("supervised_mode_policies_v1")
|
||||
|
||||
fun forTesting(dataStore: DataStore<Preferences>): SupervisedModeStore =
|
||||
SupervisedModeStore(dataStore)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Availability of the app-specific parent credential. */
|
||||
enum class SupervisedParentAuthStatus {
|
||||
Missing,
|
||||
Configured,
|
||||
Corrupt,
|
||||
}
|
||||
|
||||
/** Input method selected for the app-specific parent credential. */
|
||||
@Serializable
|
||||
enum class SupervisedParentCredentialType {
|
||||
Legacy,
|
||||
Pin,
|
||||
Password,
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private enum class SupervisedRecoveryFormat {
|
||||
LegacyCode,
|
||||
WordPhrase,
|
||||
}
|
||||
|
||||
/** Result of a parent-secret or recovery-phrase verification attempt. */
|
||||
sealed interface SupervisedParentAuthResult {
|
||||
data object Success : SupervisedParentAuthResult
|
||||
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
|
||||
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
|
||||
data object Missing : SupervisedParentAuthResult
|
||||
data object Corrupt : SupervisedParentAuthResult
|
||||
}
|
||||
|
||||
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
|
||||
data class SupervisedParentEnrollment(val recoveryPhrase: String)
|
||||
|
||||
/** Validation result for a new parent PIN or password. */
|
||||
data class SupervisedParentSecretValidation(
|
||||
val valid: Boolean,
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
|
||||
interface SupervisedParentAuthenticator {
|
||||
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
|
||||
suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
|
||||
suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
}
|
||||
|
||||
/**
|
||||
* App-specific parent authentication for Supervised Mode.
|
||||
*
|
||||
* This store deliberately does not delegate to Android's device credential: a
|
||||
* child can legitimately own the PIN or biometrics on their Android profile.
|
||||
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
|
||||
* secret and recovery phrase are never persisted.
|
||||
*/
|
||||
class SupervisedParentAuthStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
private val iterations: Int,
|
||||
private val minimumAcceptedIterations: Int,
|
||||
private val random: SecureRandom,
|
||||
private val nowMillis: () -> Long,
|
||||
) : SupervisedParentAuthenticator {
|
||||
constructor(context: Context) : this(
|
||||
dataStore = context.applicationContext.relayDataStore,
|
||||
iterations = DEFAULT_PBKDF2_ITERATIONS,
|
||||
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
|
||||
random = SecureRandom(),
|
||||
nowMillis = System::currentTimeMillis,
|
||||
)
|
||||
|
||||
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
|
||||
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).status
|
||||
}
|
||||
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).record?.credentialType
|
||||
}
|
||||
|
||||
override suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
|
||||
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
|
||||
}
|
||||
runCatching { enrollLocked(newSecret, credentialType) }
|
||||
}
|
||||
|
||||
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
|
||||
verifyLocked(secret, AuthTarget.ParentSecret)
|
||||
}
|
||||
|
||||
override suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
val record = decode(dataStore.data.first()[KEY_RECORD]).record
|
||||
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
|
||||
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
|
||||
try {
|
||||
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
} finally {
|
||||
normalizedRecovery.fill('\u0000')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated escape hatch used by the parent controls.
|
||||
*
|
||||
* The app-global credential cannot be removed while leaving any supervised
|
||||
* policy enabled. Every policy is disabled, but its configuration is retained,
|
||||
* in the same transaction that removes the credential.
|
||||
*/
|
||||
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
|
||||
runCatching {
|
||||
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun enrollLocked(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentEnrollment {
|
||||
require(credentialType != SupervisedParentCredentialType.Legacy)
|
||||
val recoveryChars = generateRecoveryPhrase().toCharArray()
|
||||
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
var parentVerifier = ByteArray(0)
|
||||
var recoveryVerifier = ByteArray(0)
|
||||
try {
|
||||
parentVerifier = derive(secret, parentSalt, iterations)
|
||||
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
|
||||
val record = PersistedParentAuth(
|
||||
iterations = iterations,
|
||||
parentSalt = encode(parentSalt),
|
||||
parentVerifier = encode(parentVerifier),
|
||||
recoverySalt = encode(recoverySalt),
|
||||
recoveryVerifier = encode(recoveryVerifier),
|
||||
credentialType = credentialType,
|
||||
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
|
||||
)
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
return SupervisedParentEnrollment(recoveryChars.concatToString())
|
||||
} finally {
|
||||
recoveryChars.fill('\u0000')
|
||||
parentSalt.fill(0)
|
||||
recoverySalt.fill(0)
|
||||
parentVerifier.fill(0)
|
||||
recoveryVerifier.fill(0)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun verifyLocked(
|
||||
candidate: CharArray,
|
||||
target: AuthTarget,
|
||||
): SupervisedParentAuthResult {
|
||||
val decoded = decode(dataStore.data.first()[KEY_RECORD])
|
||||
val record = decoded.record ?: return when (decoded.status) {
|
||||
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
|
||||
else -> SupervisedParentAuthResult.Corrupt
|
||||
}
|
||||
val now = nowMillis()
|
||||
if (record.blockedUntilEpochMillis > now) {
|
||||
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
|
||||
}
|
||||
|
||||
val saltText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentSalt
|
||||
AuthTarget.RecoveryCode -> record.recoverySalt
|
||||
}
|
||||
val verifierText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentVerifier
|
||||
AuthTarget.RecoveryCode -> record.recoveryVerifier
|
||||
}
|
||||
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val actual = try {
|
||||
derive(candidate, salt, record.iterations)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to derive supervised parent verifier", error)
|
||||
return SupervisedParentAuthResult.Corrupt
|
||||
} finally {
|
||||
salt.fill(0)
|
||||
}
|
||||
val matches = try {
|
||||
MessageDigest.isEqual(expected, actual)
|
||||
} finally {
|
||||
expected.fill(0)
|
||||
actual.fill(0)
|
||||
}
|
||||
|
||||
if (matches) {
|
||||
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
|
||||
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
|
||||
}
|
||||
return SupervisedParentAuthResult.Success
|
||||
}
|
||||
|
||||
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
|
||||
val delayMillis = backoffMillis(failures)
|
||||
save(
|
||||
record.copy(
|
||||
failedAttempts = failures,
|
||||
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
|
||||
),
|
||||
)
|
||||
return if (delayMillis == 0L) {
|
||||
SupervisedParentAuthResult.Invalid(
|
||||
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
|
||||
)
|
||||
} else {
|
||||
SupervisedParentAuthResult.Throttled(delayMillis)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun save(record: PersistedParentAuth) {
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
}
|
||||
|
||||
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
|
||||
withContext(Dispatchers.Default) {
|
||||
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
|
||||
try {
|
||||
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodedRecord {
|
||||
if (raw.isNullOrBlank()) {
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
|
||||
}
|
||||
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
|
||||
.getOrElse {
|
||||
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
val valid = record.version == RECORD_VERSION &&
|
||||
record.algorithm == KDF_ALGORITHM &&
|
||||
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
|
||||
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
|
||||
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
|
||||
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
|
||||
record.blockedUntilEpochMillis >= 0
|
||||
return if (valid) {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
|
||||
} else {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateRecoveryPhrase(): String {
|
||||
val available = RECOVERY_WORDS.toMutableList()
|
||||
val selected = buildList(RECOVERY_WORD_COUNT) {
|
||||
repeat(RECOVERY_WORD_COUNT) {
|
||||
add(available.removeAt(random.nextInt(available.size)))
|
||||
}
|
||||
}
|
||||
return selected.joinToString("-")
|
||||
}
|
||||
|
||||
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
|
||||
private fun decodeBytes(value: String): ByteArray? =
|
||||
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
|
||||
|
||||
private fun backoffMillis(failures: Int): Long = when (failures) {
|
||||
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
|
||||
FAILURES_BEFORE_BACKOFF -> 30_000L
|
||||
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
|
||||
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
|
||||
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
|
||||
else -> MAX_BACKOFF_MILLIS
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedParentAuth(
|
||||
val version: Int = RECORD_VERSION,
|
||||
val algorithm: String = KDF_ALGORITHM,
|
||||
val iterations: Int,
|
||||
val parentSalt: String,
|
||||
val parentVerifier: String,
|
||||
val recoverySalt: String,
|
||||
val recoveryVerifier: String,
|
||||
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
|
||||
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
|
||||
val failedAttempts: Int = 0,
|
||||
val blockedUntilEpochMillis: Long = 0L,
|
||||
)
|
||||
|
||||
private data class DecodedRecord(
|
||||
val status: SupervisedParentAuthStatus,
|
||||
val record: PersistedParentAuth?,
|
||||
)
|
||||
|
||||
private enum class AuthTarget { ParentSecret, RecoveryCode }
|
||||
|
||||
class ParentAuthenticationException(
|
||||
val authResult: SupervisedParentAuthResult,
|
||||
) : IllegalStateException("Parent authentication failed: $authResult")
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SupervisedParentAuth"
|
||||
private const val RECORD_VERSION = 1
|
||||
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
|
||||
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
|
||||
private const val MIN_ACCEPTED_ITERATIONS = 100_000
|
||||
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
|
||||
private const val SALT_BYTES = 16
|
||||
private const val KEY_BITS = 256
|
||||
private const val FAILURES_BEFORE_BACKOFF = 5
|
||||
private const val MAX_TRACKED_FAILURES = 9
|
||||
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
|
||||
private const val RECOVERY_WORD_COUNT = 6
|
||||
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
|
||||
private val processMutex = Mutex()
|
||||
|
||||
fun validateNewSecret(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentSecretValidation {
|
||||
if (secret.size > 64) {
|
||||
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
|
||||
}
|
||||
if (credentialType == SupervisedParentCredentialType.Pin) {
|
||||
return if (secret.size == 6 && secret.all(Char::isDigit)) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
|
||||
}
|
||||
}
|
||||
return if (
|
||||
credentialType == SupervisedParentCredentialType.Password &&
|
||||
secret.size >= 8 && secret.any { !it.isWhitespace() }
|
||||
) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeRecoveryPhrase(
|
||||
value: CharArray,
|
||||
format: SupervisedRecoveryFormat,
|
||||
): CharArray = when (format) {
|
||||
SupervisedRecoveryFormat.LegacyCode -> value
|
||||
.filterNot { it == '-' || it.isWhitespace() }
|
||||
.joinToString("")
|
||||
.uppercase()
|
||||
.toCharArray()
|
||||
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
|
||||
.trim()
|
||||
.lowercase()
|
||||
.split(Regex("[-\\s]+"))
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("-")
|
||||
.toCharArray()
|
||||
}
|
||||
|
||||
private val RECOVERY_WORDS = listOf(
|
||||
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
|
||||
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
|
||||
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
|
||||
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
|
||||
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
|
||||
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
|
||||
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
|
||||
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
|
||||
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
|
||||
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
|
||||
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
|
||||
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
|
||||
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
|
||||
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
|
||||
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
|
||||
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
|
||||
)
|
||||
|
||||
internal fun forTesting(
|
||||
dataStore: DataStore<Preferences>,
|
||||
iterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
random: SecureRandom = SecureRandom(),
|
||||
nowMillis: () -> Long = System::currentTimeMillis,
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore(
|
||||
dataStore = dataStore,
|
||||
iterations = iterations,
|
||||
minimumAcceptedIterations = minimumAcceptedIterations,
|
||||
random = random,
|
||||
nowMillis = nowMillis,
|
||||
)
|
||||
|
||||
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
|
||||
}
|
||||
}
|
||||
@@ -344,6 +344,46 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
|
||||
dataStore.edit { it[key] = route.storageValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Relay-only selections after Relay has been explicitly removed from
|
||||
* the active connection. A temporarily unreachable configured Relay must
|
||||
* not call this: preserving the selection lets the richer route resume
|
||||
* when connectivity returns.
|
||||
*
|
||||
* [expectedScope] fences profile/connection changes that can race the
|
||||
* DataStore edit. Values are re-read inside the transaction instead of
|
||||
* trusting an earlier settings snapshot, so a newer user choice wins.
|
||||
* The legacy default-profile keys are global (their storage names predate
|
||||
* connection scoping), so they are never rewritten here: runtime fallback
|
||||
* handles an unpaired default profile without changing another
|
||||
* connection's selection.
|
||||
*/
|
||||
suspend fun reconcileRelayRemoval(expectedScope: VoiceProfileScope): Boolean {
|
||||
if (_scope.value != expectedScope || expectedScope.profileName == null) return false
|
||||
var changed = false
|
||||
dataStore.edit { prefs ->
|
||||
if (_scope.value != expectedScope) return@edit
|
||||
|
||||
val engine = VoiceEngineMode.fromStorage(
|
||||
resolveString(prefs, KEY_ENGINE_MODE, expectedScope, DEFAULT_ENGINE_MODE),
|
||||
)
|
||||
val route = VoiceAudioRoute.fromStorage(
|
||||
resolveString(prefs, KEY_AUDIO_ROUTE, expectedScope, DEFAULT_AUDIO_ROUTE),
|
||||
)
|
||||
if (engine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_ENGINE_MODE, expectedScope))] =
|
||||
VoiceEngineMode.HermesVoiceOutput.storageValue
|
||||
changed = true
|
||||
}
|
||||
if (route == VoiceAudioRoute.Relay) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_AUDIO_ROUTE, expectedScope))] =
|
||||
VoiceAudioRoute.Auto.storageValue
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/** "" clears the override (relay falls back to the server's saved voice). */
|
||||
suspend fun setEnhancedVoice(voice: String) {
|
||||
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
||||
|
||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import com.hermesandroid.relay.reliability.ReliabilityCenter
|
||||
import com.hermesandroid.relay.reliability.ReliabilityRedactor
|
||||
import java.time.Instant
|
||||
|
||||
enum class DiagnosticCategory(val label: String) {
|
||||
Api("API"),
|
||||
@@ -83,6 +84,8 @@ data class StatusCheck(
|
||||
object DiagnosticsLog {
|
||||
private const val MAX_ENTRIES = 200
|
||||
private const val MAX_TEXT_LENGTH = 180
|
||||
const val SUPPORT_ENTRY_LIMIT = 80
|
||||
private const val MAX_SUPPORT_TEXT_LENGTH = 32_000
|
||||
|
||||
/** Cap for the full stacktrace kept on an error entry — a few KB is plenty. */
|
||||
private const val MAX_TRACE_LENGTH = 8000
|
||||
@@ -204,6 +207,46 @@ object DiagnosticsLog {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact, bounded diagnostics section used by the review-before-sharing
|
||||
* support export. Entries were already sanitized at record time; the final
|
||||
* redaction pass protects legacy entries and keeps this safe to compose with
|
||||
* persistent reliability reports.
|
||||
*/
|
||||
fun supportText(entries: List<DiagnosticLogEntry>): String {
|
||||
val selected = entries.takeLast(SUPPORT_ENTRY_LIMIT)
|
||||
if (selected.isEmpty()) return ""
|
||||
return ReliabilityRedactor.redact(
|
||||
buildString {
|
||||
appendLine("Recent in-app diagnostics")
|
||||
appendLine("Diagnostics: ${selected.size}")
|
||||
selected.forEachIndexed { index, entry ->
|
||||
appendLine()
|
||||
appendLine("===== Diagnostic ${index + 1} =====")
|
||||
appendLine("Time: ${Instant.ofEpochMilli(entry.timestampMs)}")
|
||||
appendLine("Category: ${entry.category.label}")
|
||||
appendLine("Severity: ${entry.severity.name}")
|
||||
appendLine("Title: ${entry.title}")
|
||||
entry.operation?.let { appendLine("Operation: $it") }
|
||||
entry.endpointRole?.let { appendLine("Route: $it") }
|
||||
entry.configuredUrl?.let { appendLine("Configured URL: $it") }
|
||||
entry.requestUrl?.let { appendLine("Request: $it") }
|
||||
if (entry.configuredUrl == null && entry.requestUrl == null) {
|
||||
entry.url?.let { appendLine("URL: $it") }
|
||||
}
|
||||
entry.elapsedMs?.let { appendLine("Elapsed: ${it}ms") }
|
||||
entry.detail?.let { appendLine("Detail: $it") }
|
||||
entry.suggestion?.let { appendLine("Next: $it") }
|
||||
entry.stacktrace?.let {
|
||||
appendLine("Technical detail (redacted)")
|
||||
appendLine(it)
|
||||
}
|
||||
}
|
||||
},
|
||||
MAX_SUPPORT_TEXT_LENGTH,
|
||||
)
|
||||
}
|
||||
|
||||
fun sanitizeUrl(value: String?): String? {
|
||||
val trimmed = value?.trim()?.takeIf { it.isNotBlank() } ?: return null
|
||||
val noQuery = trimmed.substringBefore('?').substringBefore('#')
|
||||
|
||||
@@ -348,7 +348,7 @@ class BridgeCommandHandler(
|
||||
* the multiplexer. The two paths are fully independent.
|
||||
*
|
||||
* Caught by Bailey's on-device test 2026-04-14 — see the v0.4.1
|
||||
* "voice intent local dispatch loop" entry in ROADMAP.md.
|
||||
* "voice intent local dispatch loop" entry in docs/project/ROADMAP.md.
|
||||
*/
|
||||
suspend fun handleLocalCommand(envelope: Envelope): LocalDispatchResult {
|
||||
if (envelope.type != "bridge.command") {
|
||||
|
||||
@@ -153,7 +153,7 @@ class ChannelMultiplexer {
|
||||
)
|
||||
send(pong)
|
||||
}
|
||||
"auth.ok", "auth.fail" -> {
|
||||
"auth.ok", "auth.fail", "supervised.updated", "error" -> {
|
||||
// Delegate to system handler if registered
|
||||
handlers["system"]?.onMessage(envelope)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ 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.isDashboardRelayIngressUrl
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.PairingPreferences
|
||||
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
|
||||
@@ -43,6 +44,7 @@ import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
enum class ConnectionState {
|
||||
Disconnected,
|
||||
@@ -138,6 +140,12 @@ class ConnectionManager(
|
||||
* back to the legacy per-device PairingPreferences source below.
|
||||
*/
|
||||
private val endpointCandidatesProvider: (suspend () -> List<EndpointCandidate>)? = null,
|
||||
/**
|
||||
* Dynamic ownership fence for Relay-only resolution. Production uses it
|
||||
* to keep Dashboard ingress on the exact origin that owns Dashboard auth,
|
||||
* while direct Relay and proxy routes remain independently eligible.
|
||||
*/
|
||||
private val relayCandidateEligibility: (EndpointCandidate) -> Boolean = { true },
|
||||
/**
|
||||
* Suspending supplier for the active device id. Used to key into
|
||||
* [PairingPreferences.getDeviceEndpoints] during resolution. `null`
|
||||
@@ -151,6 +159,14 @@ class ConnectionManager(
|
||||
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Test seam for observing lifecycle teardown without opening a socket. */
|
||||
private val okHttpClientFactory: (() -> OkHttpClient)? = null,
|
||||
/**
|
||||
* Builds a Dashboard-authorized WebSocket request for plugin ingress.
|
||||
* Implementations mint a fresh single-use Dashboard WS ticket on every
|
||||
* invocation. Direct Relay listeners never call this provider.
|
||||
*/
|
||||
private val dashboardRelayRequestProvider: (suspend (String) -> Request?)? = null,
|
||||
/** Deterministic race seam immediately before an ingress failure may poison route state. */
|
||||
private val beforeIngressFailureCommit: suspend () -> Unit = {},
|
||||
) {
|
||||
private val supervisorJob = SupervisorJob()
|
||||
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
|
||||
@@ -191,6 +207,9 @@ class ConnectionManager(
|
||||
|
||||
@Volatile
|
||||
private var webSocket: WebSocket? = null
|
||||
private val socketGeneration = AtomicLong(0L)
|
||||
@Volatile
|
||||
private var activeSocketGeneration: Long = 0L
|
||||
|
||||
@Volatile
|
||||
private var serverUrl: String? = null
|
||||
@@ -273,6 +292,11 @@ class ConnectionManager(
|
||||
@Volatile
|
||||
private var networkResolveJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
/** Optional API discovery is never part of Dashboard/Gateway readiness. */
|
||||
@Volatile
|
||||
private var apiResolveJob: Job? = null
|
||||
private var apiResolveRevision: Long = 0L
|
||||
|
||||
/** Deferred reaction to a network loss — cancelled if a network returns within the grace. */
|
||||
private var networkLossJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
@@ -363,13 +387,12 @@ class ConnectionManager(
|
||||
// the synthesized list just collapses to the same URL anyway.
|
||||
scope.launch {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
|
||||
_activeRelayEndpoint.value = relayResolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (resolved != null) {
|
||||
_activeEndpoint.value = resolved
|
||||
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
|
||||
@@ -407,6 +430,18 @@ class ConnectionManager(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the exact QR-advertised socket for a fresh pair. Relay health probes
|
||||
* require an established Relay session, so running the normal resolver
|
||||
* before `auth.ok` is circular and can consume the entire pairing window.
|
||||
* Post-pair reconnects continue to use [connect] and full route resolution.
|
||||
*/
|
||||
fun connectPairing(url: String) {
|
||||
ensureNetworkCallbackRegistered()
|
||||
_activeRelayEndpoint.value = null
|
||||
connectToUrlOnMainPath(url, replaceReason = "Fresh Relay pairing")
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an ordinary scheduled reconnect with an immediate attempt.
|
||||
*
|
||||
@@ -442,6 +477,35 @@ class ConnectionManager(
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopen the current authenticated Relay socket without discarding pair
|
||||
* state. Used only as a compatibility fallback when an older Relay does
|
||||
* not acknowledge a post-auth metadata update; the replacement socket's
|
||||
* normal `system/auth` frame carries the latest metadata.
|
||||
*/
|
||||
fun reconnectForAuthenticatedMetadataUpdate(): Boolean {
|
||||
val targetUrl = serverUrl?.takeIf { it.isNotBlank() } ?: return false
|
||||
if (isRelayRateLimitBackoffActive(
|
||||
rateLimitBackoffUntilMs,
|
||||
SystemClock.elapsedRealtime(),
|
||||
)
|
||||
) {
|
||||
Log.i(TAG, "metadata reconnect: preserving active rate-limit backoff")
|
||||
return false
|
||||
}
|
||||
val previousSocket = webSocket
|
||||
if (previousSocket == null) {
|
||||
connect(targetUrl)
|
||||
} else {
|
||||
doConnect(
|
||||
targetUrl,
|
||||
previousSocketToClose = previousSocket,
|
||||
replaceReason = "Relay metadata compatibility refresh",
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as [connect] but bypasses the resolver — used by the network-
|
||||
* change callback when we've already picked a winner and just want to
|
||||
@@ -548,10 +612,17 @@ class ConnectionManager(
|
||||
*/
|
||||
suspend fun resolveBestEndpoint(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
|
||||
private suspend fun resolveLegacyStandardFallbackSafe(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(EndpointSurface.Standard) { candidate ->
|
||||
candidate.dashboard?.url.isNullOrBlank() &&
|
||||
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl == null
|
||||
}
|
||||
|
||||
private suspend fun resolveBestEndpointSafe(
|
||||
surface: EndpointSurface,
|
||||
candidateFilter: (EndpointCandidate) -> Boolean = { true },
|
||||
): EndpointCandidate? {
|
||||
val resolver = endpointResolver ?: return null
|
||||
val ctx = context ?: return null
|
||||
@@ -580,13 +651,14 @@ class ConnectionManager(
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
if (endpoints.isEmpty()) return null
|
||||
val eligibleEndpoints = endpoints.filter(candidateFilter)
|
||||
if (eligibleEndpoints.isEmpty()) return null
|
||||
|
||||
// Manual override: if the user pinned a role in the Endpoints card,
|
||||
// try that one first; fall through to the strict-priority algorithm
|
||||
// if it isn't reachable.
|
||||
_manualRoleOverride.value?.let { preferredRole ->
|
||||
val preferred = endpoints.firstOrNull {
|
||||
val preferred = eligibleEndpoints.firstOrNull {
|
||||
it.role.equals(preferredRole, ignoreCase = true)
|
||||
}
|
||||
if (preferred != null) {
|
||||
@@ -598,7 +670,54 @@ class ConnectionManager(
|
||||
}
|
||||
}
|
||||
|
||||
return resolver.resolve(endpoints, surface)
|
||||
return resolver.resolve(eligibleEndpoints, surface)
|
||||
}
|
||||
|
||||
/** Every Relay selection path must apply the same live ownership fence. */
|
||||
private suspend fun resolveBestRelayEndpointSafe(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(
|
||||
surface = EndpointSurface.Relay,
|
||||
candidateFilter = relayCandidateEligibility,
|
||||
)
|
||||
|
||||
/**
|
||||
* Discover the optional API fallback without holding up the standard
|
||||
* Dashboard/Gateway route. A single manager-level job coalesces lifecycle
|
||||
* callers; [EndpointResolver] additionally shares an in-flight request per
|
||||
* route/surface. The negative cache keeps ordinary profile changes cheap,
|
||||
* while network callbacks and explicit probes still invalidate it.
|
||||
*/
|
||||
private fun scheduleApiResolution() {
|
||||
synchronized(this) {
|
||||
apiResolveRevision += 1L
|
||||
if (apiResolveJob?.isActive != true) {
|
||||
startApiResolutionLocked(apiResolveRevision)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Caller must hold this manager's monitor. */
|
||||
private fun startApiResolutionLocked(revision: Long) {
|
||||
apiResolveJob = scope.launch {
|
||||
try {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
synchronized(this@ConnectionManager) {
|
||||
// A route/connection refresh may have arrived while this
|
||||
// optional probe was waiting. Never publish its stale
|
||||
// winner over the newer connection's API ownership.
|
||||
if (revision == apiResolveRevision) {
|
||||
_activeApiEndpoint.value = resolved
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized(this@ConnectionManager) {
|
||||
apiResolveJob = null
|
||||
if (revision != apiResolveRevision && supervisorJob.isActive) {
|
||||
startApiResolutionLocked(apiResolveRevision)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -627,9 +746,9 @@ class ConnectionManager(
|
||||
endpointResolver?.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
|
||||
// Transient probe miss while the relay socket is demonstrably up
|
||||
// — keep the live route published rather than downgrading every
|
||||
@@ -637,7 +756,6 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
|
||||
val normalizedTarget = normalizeRelayUrl(targetUrl)
|
||||
@@ -677,8 +795,8 @@ class ConnectionManager(
|
||||
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
|
||||
if (clearProbeCache) endpointResolver?.clearCache()
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
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
|
||||
@@ -687,7 +805,6 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -709,6 +826,46 @@ class ConnectionManager(
|
||||
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
|
||||
}
|
||||
|
||||
/** Admission is stronger evidence than `/transport/health`: reject this ingress and retain direct fallback. */
|
||||
private suspend fun fallbackFromBrokenDashboardIngress(
|
||||
url: String,
|
||||
reason: String,
|
||||
failingSocket: WebSocket? = null,
|
||||
failingGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (!isDashboardRelayIngressUrl(url)) return false
|
||||
if (failingGeneration != null) {
|
||||
beforeIngressFailureCommit()
|
||||
if (activeSocketGeneration != failingGeneration || webSocket !== failingSocket) {
|
||||
Log.i(TAG, "Ignoring stale Dashboard ingress failure ($reason)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
val failed = _activeRelayEndpoint.value ?: return false
|
||||
val failedUrl = failed.relayWebSocketUrl()?.let(::normalizeRelayUrl)
|
||||
if (failedUrl != normalizeRelayUrl(url)) return false
|
||||
endpointResolver?.markUnreachable(failed, EndpointSurface.Relay) ?: return false
|
||||
val replacement = resolveBestRelayEndpointSafe() ?: return false
|
||||
val replacementUrl = replacement.relayWebSocketUrl()?.takeIf(String::isNotBlank) ?: return false
|
||||
if (normalizeRelayUrl(replacementUrl) == normalizeRelayUrl(url)) return false
|
||||
_activeRelayEndpoint.value = replacement
|
||||
Log.i(TAG, "Dashboard Relay ingress rejected; switching to ${replacement.role} ($reason)")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = "Relay ingress unavailable",
|
||||
detail = "Dashboard admission failed; using retained direct Relay route.",
|
||||
operation = "Select Relay transport after admission failure",
|
||||
endpointRole = failed.role,
|
||||
requestUrl = url,
|
||||
)
|
||||
connectToUrlOnMainPath(
|
||||
replacementUrl,
|
||||
replaceReason = "Dashboard Relay ingress admission failed",
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Debounced network-change re-resolution, shared by both NetworkCallback
|
||||
* events. Re-runs the resolver and publishes the winner to
|
||||
@@ -731,8 +888,8 @@ class ConnectionManager(
|
||||
if (wipeCache) endpointResolver.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
if (resolved == null) {
|
||||
// Hysteresis for the AUTOMATIC (network-callback) path. A
|
||||
// transient cold-route probe miss must NOT null the published
|
||||
@@ -769,7 +926,6 @@ 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
|
||||
@@ -778,7 +934,7 @@ class ConnectionManager(
|
||||
// (connectToUrlOnMainPath force-sets shouldReconnect = true, so
|
||||
// the swap path never re-checked it.)
|
||||
if (!shouldReconnect) return@launch
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
?: return@launch
|
||||
@@ -945,7 +1101,8 @@ class ConnectionManager(
|
||||
webSocket?.send(text)
|
||||
}
|
||||
|
||||
private fun isActiveSocket(socket: WebSocket): Boolean = webSocket === socket
|
||||
private fun isActiveSocket(socket: WebSocket, generation: Long): Boolean =
|
||||
webSocket === socket && activeSocketGeneration == generation
|
||||
|
||||
private fun doConnect(
|
||||
url: String,
|
||||
@@ -981,7 +1138,7 @@ class ConnectionManager(
|
||||
scope.launch { doConnectInternal(url, previousSocketToClose, replaceReason) }
|
||||
}
|
||||
|
||||
private fun doConnectInternal(
|
||||
private suspend fun doConnectInternal(
|
||||
url: String,
|
||||
previousSocketToClose: WebSocket? = null,
|
||||
replaceReason: String = "Relay socket replaced",
|
||||
@@ -1006,22 +1163,49 @@ class ConnectionManager(
|
||||
buildClient(url)
|
||||
}
|
||||
|
||||
val request = buildRelayRequestOrNull(url)
|
||||
val request = if (isDashboardRelayIngressUrl(url)) {
|
||||
dashboardRelayRequestProvider?.invoke(url)
|
||||
} else {
|
||||
buildRelayRequestOrNull(url)
|
||||
}
|
||||
if (request == null) {
|
||||
// A malformed relay URL (an invalid/empty host from a corrupt or
|
||||
// hand-edited pairing payload) can't be built into a request. This
|
||||
// runs on a background coroutine, so letting OkHttp's url() throw
|
||||
// would crash the app — the #131 "Invalid URL host" class, relay-
|
||||
// socket half. Route it through the same path onFailure uses.
|
||||
Log.e(TAG, "doConnect: malformed relay URL '$url' — not connecting")
|
||||
Log.e(
|
||||
TAG,
|
||||
if (isDashboardRelayIngressUrl(url)) {
|
||||
"doConnect: Dashboard Relay ticket/request unavailable for '$url'"
|
||||
} else {
|
||||
"doConnect: malformed relay URL '$url' — not connecting"
|
||||
},
|
||||
)
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = "Invalid relay URL",
|
||||
detail = "The relay address could not be parsed; re-pair to refresh it.",
|
||||
operation = "Build Relay WebSocket request",
|
||||
title = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Dashboard Relay authorization unavailable"
|
||||
} else {
|
||||
"Invalid relay URL"
|
||||
},
|
||||
detail = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Dashboard authorization could not prepare the Relay WebSocket request."
|
||||
} else {
|
||||
"The relay address could not be parsed; re-pair to refresh it."
|
||||
},
|
||||
operation = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Mint Dashboard Relay WebSocket ticket"
|
||||
} else {
|
||||
"Build Relay WebSocket request"
|
||||
},
|
||||
configuredUrl = url,
|
||||
suggestion = "Edit or re-pair the Relay route to replace the invalid address.",
|
||||
suggestion = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Sign in to the matching Dashboard route, then recheck Relay routes."
|
||||
} else {
|
||||
"Edit or re-pair the Relay route to replace the invalid address."
|
||||
},
|
||||
)
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
@@ -1029,14 +1213,18 @@ class ConnectionManager(
|
||||
runCatching { stale.close(1000, replaceReason) }
|
||||
stale.cancel()
|
||||
}
|
||||
scheduleReconnect()
|
||||
if (!fallbackFromBrokenDashboardIngress(url, "request provider or ticket unavailable")) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Log.i(TAG, "doConnect: opening WSS to $url")
|
||||
val generation = socketGeneration.incrementAndGet()
|
||||
activeSocketGeneration = generation
|
||||
val newSocket = client.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onOpen: stale WSS handshake ignored ($url)")
|
||||
runCatching { webSocket.close(1000, "Stale relay socket") }
|
||||
webSocket.cancel()
|
||||
@@ -1079,7 +1267,7 @@ class ConnectionManager(
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onMessage: stale WSS envelope ignored ($url)")
|
||||
return
|
||||
}
|
||||
@@ -1106,7 +1294,7 @@ class ConnectionManager(
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onClosed: stale WSS close ignored ($url code=$code reason=$reason)")
|
||||
return
|
||||
}
|
||||
@@ -1120,13 +1308,28 @@ class ConnectionManager(
|
||||
requestUrl = url,
|
||||
suggestion = if (code == 1000) null else "Check the Relay server logs for the matching close code and reason.",
|
||||
)
|
||||
val admitted = authenticated
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
scheduleReconnect()
|
||||
if (isDashboardRelayIngressUrl(url) && !admitted && code != 1000) {
|
||||
scope.launch {
|
||||
if (!fallbackFromBrokenDashboardIngress(
|
||||
url,
|
||||
"pre-auth close $code",
|
||||
webSocket,
|
||||
generation,
|
||||
) && activeSocketGeneration == generation
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onFailure: stale WSS failure ignored ($url ${t.javaClass.simpleName}: ${t.message})")
|
||||
return
|
||||
}
|
||||
@@ -1148,6 +1351,22 @@ class ConnectionManager(
|
||||
} ?: NetworkDiagnosticGuidance.forThrowable(t, "Relay"),
|
||||
)
|
||||
lastUpgradeResponseCode = code
|
||||
if (isDashboardRelayIngressUrl(url) && response != null) {
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
scope.launch {
|
||||
if (!fallbackFromBrokenDashboardIngress(
|
||||
url,
|
||||
"HTTP admission ${response.code}",
|
||||
webSocket,
|
||||
generation,
|
||||
) && activeSocketGeneration == generation
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (response == null) {
|
||||
// Transport-level failure (no HTTP upgrade response): on a
|
||||
// remote (Tailscale) link the first handshake can fail cold.
|
||||
@@ -1261,7 +1480,7 @@ class ConnectionManager(
|
||||
// expires, auth state may have changed (e.g., user hit Revoke
|
||||
// during the retry window).
|
||||
if (shouldReconnect && reconnectGate()) {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val resolved = resolveBestRelayEndpointSafe()
|
||||
val targetUrl = resolved?.relayWebSocketUrl()
|
||||
if (resolved != null) {
|
||||
// Mirror scheduleNetworkReResolve: clear the sustained-loss
|
||||
|
||||
@@ -102,22 +102,18 @@ 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) {
|
||||
// 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()) {
|
||||
val notificationId = when (msg.surfacing?.lowercase()) {
|
||||
"inbox" -> {
|
||||
injectIntoThread?.invoke(msg)
|
||||
null
|
||||
}
|
||||
"session" -> {
|
||||
val delivered = injectIntoThread?.invoke(msg) == true ||
|
||||
toSession?.invoke(msg) == true
|
||||
if (!delivered) notify(msg)
|
||||
if (delivered) null else notify(msg)
|
||||
}
|
||||
// null / "default" / "notification" / anything unrecognized.
|
||||
else -> {
|
||||
@@ -125,17 +121,20 @@ class ProactiveMessageHandler(
|
||||
notify(msg)
|
||||
}
|
||||
}
|
||||
// Every message remains in the bounded local cache. Persist the exact
|
||||
// posted notification slot as part of that row so a later local Thread
|
||||
// removal can cancel only its own notification.
|
||||
toInbox?.invoke(msg.copy(notificationId = notificationId))
|
||||
}
|
||||
|
||||
private fun notify(msg: ProactiveMessage) {
|
||||
private fun notify(msg: ProactiveMessage): Int? =
|
||||
ProactiveMessageNotifier.notify(
|
||||
context = context,
|
||||
title = msg.title,
|
||||
text = msg.text,
|
||||
text = mediaFreeProactivePreview(msg.text),
|
||||
messageId = msg.messageId,
|
||||
chatId = msg.chatId,
|
||||
)
|
||||
}
|
||||
|
||||
private fun parse(payload: JsonObject): ProactiveMessage? {
|
||||
val text = payload["text"]?.jsonPrimitive?.contentOrNull
|
||||
@@ -157,6 +156,30 @@ class ProactiveMessageHandler(
|
||||
}
|
||||
}
|
||||
|
||||
/** Notification text is a preview; the Thread owns attachment rendering. */
|
||||
internal fun mediaFreeProactivePreview(text: String): String {
|
||||
var fence: String? = null
|
||||
val lines = mutableListOf<String>()
|
||||
for (line in text.lines()) {
|
||||
val trimmed = line.trim()
|
||||
val delimiter = when {
|
||||
trimmed.startsWith("```") -> "```"
|
||||
trimmed.startsWith("~~~") -> "~~~"
|
||||
else -> null
|
||||
}
|
||||
if (delimiter != null) {
|
||||
fence = if (fence == delimiter) null else if (fence == null) delimiter else fence
|
||||
}
|
||||
val markerOnly = fence == null && (
|
||||
trimmed.startsWith("MEDIA:hermes-relay://") ||
|
||||
trimmed.startsWith("MEDIA:/") ||
|
||||
Regex("^MEDIA:[A-Za-z]:\\\\").containsMatchIn(trimmed)
|
||||
)
|
||||
if (!markerOnly && trimmed.isNotEmpty()) lines += trimmed
|
||||
}
|
||||
return lines.joinToString(" ").ifBlank { "Attachment" }
|
||||
}
|
||||
|
||||
/**
|
||||
* A parsed agent-initiated message. `surfacing` is the optional route hint
|
||||
* (null = app default); Phase 2 keys inbox/session delivery off it.
|
||||
@@ -172,4 +195,6 @@ data class ProactiveMessage(
|
||||
val replyTo: String? = null,
|
||||
/** True only when Relay explicitly marked this as a reconnect queue flush. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
/** Exact Android notification slot when this delivery posted one. */
|
||||
val notificationId: Int? = null,
|
||||
)
|
||||
|
||||