Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee59149b41 | ||
|
|
23a6231b20 | ||
|
|
a4fac4550a | ||
|
|
88ab48cfc0 | ||
|
|
7c03f8554f | ||
|
|
367e5d271c | ||
|
|
47a395ab76 | ||
|
|
e7cbed3c8f | ||
|
|
b72ab5aef2 | ||
|
|
40fcb80a7d | ||
|
|
ff64548085 | ||
|
|
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 | ||
|
|
febc26fe35 | ||
|
|
28a906215d | ||
|
|
1617f75f1a | ||
|
|
dbf71a87f4 | ||
|
|
95ed8e6edb | ||
|
|
d26bf6c25b | ||
|
|
181e10f2ad | ||
|
|
c519502551 | ||
|
|
dafa6f3a18 | ||
|
|
857a1551f3 | ||
|
|
00052d20d9 | ||
|
|
246d9f1010 | ||
|
|
e9f32673be |
@@ -3,23 +3,14 @@ name: Android On-Demand
|
||||
run-name: Android ${{ inputs.preset }} · ${{ inputs.head_sha }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
head_sha:
|
||||
description: Exact pushed commit SHA to verify
|
||||
required: true
|
||||
type: string
|
||||
preset:
|
||||
description: Android verification lane
|
||||
required: true
|
||||
default: focused
|
||||
type: choice
|
||||
options:
|
||||
- focused
|
||||
- lint
|
||||
- assemble-debug
|
||||
- release-smoke
|
||||
- all-final
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -38,11 +29,19 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -101,6 +101,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -20,13 +20,25 @@ on:
|
||||
description: "Exact candidate commit to check"
|
||||
required: true
|
||||
type: string
|
||||
android_preset:
|
||||
description: "Optional Android-only compute lane"
|
||||
required: false
|
||||
default: auto
|
||||
type: choice
|
||||
options:
|
||||
- auto
|
||||
- focused
|
||||
- lint
|
||||
- assemble-debug
|
||||
- release-smoke
|
||||
- all-final
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: ci-required-${{ github.ref }}
|
||||
group: ci-required-${{ github.event_name == 'workflow_dispatch' && format('{0}-{1}', inputs.head_sha, inputs.android_preset) || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
@@ -113,33 +125,41 @@ jobs:
|
||||
|
||||
android:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.android == 'true'
|
||||
if: needs.changes.outputs.android == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
uses: ./.github/workflows/ci-android.yml
|
||||
|
||||
android_on_demand:
|
||||
needs: changes
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto'
|
||||
uses: ./.github/workflows/android-on-demand.yml
|
||||
with:
|
||||
head_sha: ${{ inputs.head_sha }}
|
||||
preset: ${{ inputs.android_preset }}
|
||||
|
||||
desktop:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.desktop == 'true'
|
||||
if: needs.changes.outputs.desktop == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
uses: ./.github/workflows/ci-desktop.yml
|
||||
|
||||
plugin:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugin == 'true'
|
||||
if: needs.changes.outputs.plugin == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
uses: ./.github/workflows/ci-plugin.yml
|
||||
|
||||
dashboard:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.dashboard == 'true'
|
||||
if: needs.changes.outputs.dashboard == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
uses: ./.github/workflows/ci-dashboard.yml
|
||||
|
||||
contract:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.contract == 'true'
|
||||
if: needs.changes.outputs.contract == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
uses: ./.github/workflows/ci-contract.yml
|
||||
|
||||
docs:
|
||||
name: Build public docs
|
||||
needs: changes
|
||||
if: needs.changes.outputs.docs == 'true'
|
||||
if: needs.changes.outputs.docs == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -161,11 +181,12 @@ jobs:
|
||||
guard:
|
||||
name: Required checks
|
||||
if: always()
|
||||
needs: [changes, android, desktop, plugin, dashboard, contract, docs]
|
||||
needs: [changes, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
ANDROID_RESULT: ${{ needs.android.result }}
|
||||
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
|
||||
DESKTOP_RESULT: ${{ needs.desktop.result }}
|
||||
PLUGIN_RESULT: ${{ needs.plugin.result }}
|
||||
DASHBOARD_RESULT: ${{ needs.dashboard.result }}
|
||||
@@ -176,7 +197,7 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
failed=0
|
||||
for check in CHANGES ANDROID DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
for check in CHANGES ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
result_var="${check}_RESULT"
|
||||
result="${!result_var}"
|
||||
echo "$check: $result"
|
||||
|
||||
@@ -85,6 +85,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -15,6 +15,7 @@ contract here and in `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)
|
||||
|
||||
@@ -64,8 +65,10 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
||||
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||
compatibility surface; Relay adds optional extensions. A Gateway-owned
|
||||
conversation never changes transport because Gateway auth or reachability
|
||||
changes. This
|
||||
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
|
||||
@@ -8,11 +8,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
### 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.
|
||||
- **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.
|
||||
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
|
||||
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
|
||||
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
|
||||
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
|
||||
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
|
||||
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
|
||||
- **Android Chat settles an owned Gateway turn when its terminal frame is lost.** An exact idle `session.active_list` snapshot now completes the matching local stream, reconciles durable history, and drains its queued follow-up without interrupting or claiming Desktop/TUI work.
|
||||
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
|
||||
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
|
||||
|
||||
|
||||
+5
-4
@@ -270,9 +270,10 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
|
||||
|
||||
## Testing
|
||||
|
||||
- **Android cloud verification (preferred for pushed work):** dispatch
|
||||
`.github/workflows/android-on-demand.yml` against the exact pushed SHA with
|
||||
`focused`, `lint`, `assemble-debug`, `release-smoke`, or `all-final`. Check for
|
||||
- **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
|
||||
@@ -287,7 +288,7 @@ Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/pl
|
||||
device lane is scheduled automatically.
|
||||
- **Python tests:** `python -m unittest plugin.tests.test_<name>` from the repo root with the hermes-agent venv active. `pytest` works too but the pre-existing `conftest.py` imports a module that isn't always installed — `unittest` avoids that entirely.
|
||||
|
||||
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched. `android-on-demand.yml` is the trusted manual compute lane for an exact pushed commit; it does not replace required PR checks.
|
||||
CI is split into path-filtered workflows: `.github/workflows/ci-android.yml` (lint + build + test on app/Gradle changes), `.github/workflows/ci-server.yml` (syntax check + focused server tests on plugin/Python changes), and `.github/workflows/ci-desktop.yml` (desktop type/build/smoke checks). They run on pushes to `main` and `dev` and on PRs targeting either when their paths are touched. The registered `ci-required.yml` dispatcher calls `android-on-demand.yml` as the trusted manual compute lane for an exact pushed commit; it does not replace required PR checks.
|
||||
Superseded Android runs on `dev` and PR refs are canceled automatically; `main`
|
||||
runs are never canceled because each release-branch commit must complete its
|
||||
independent validation.
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-08-31 — Android Gateway compaction watchdog lease
|
||||
|
||||
Gateway turns now recognize the upstream `status.update` payload kind
|
||||
`compacting` and arm a ten-minute idle lease instead of the ordinary
|
||||
three-minute watchdog. A single current-Gateway status protects silent
|
||||
compaction, while repeated status heartbeats from newer gateways refresh the
|
||||
same lease. Other status payloads retain the ordinary watchdog.
|
||||
|
||||
Focused Gateway client coverage uses shortened timeout seams to prove the
|
||||
single-status, repeated-heartbeat, ordinary-silence, and payload-fencing paths
|
||||
without waiting production minutes. The declarative vanilla-Gateway fixture
|
||||
also models repeated compaction status before terminal completion.
|
||||
|
||||
## 2026-08-31 — Complete, readable Android release notes
|
||||
|
||||
Android release metadata now keeps one overall title and summary plus a complete
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — your Hermes agent, in your pocket" width="800">
|
||||
<img src="assets/readme-hero-v2.jpg" alt="Hermes-Relay — Your Hermes agent. Wherever you are. Android, Voice, Desktop." width="1000">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -38,10 +38,10 @@ Hermes-Relay puts your [Hermes agent](https://github.com/NousResearch/hermes-age
|
||||
- **📱 Android app** — streaming chat, hands-free voice, native plugin pages, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. Add a floating Petdex companion or optionally make Hermes your Android assistant; sideload builds can also let the agent read and act on your screen.
|
||||
- **⌨️ Hermes-Relay CLI** *(beta)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
|
||||
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, media, desktop tools, enhanced voice, Relay sessions, page drafts, and optional Device Control. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, inbound files, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, desktop tools, enhanced voice, Relay sessions, page drafts, optional Device Control, and media compatibility or metadata. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/diagrams/architecture-homepage.png" alt="How Hermes-Relay connects — upstream Hermes owns Chat, Manage, and standard Voice; the encouraged Relay extension fills current gaps for Terminal, notifications, media, enhanced voice, sessions, desktop tools, and optional Device Control." width="900">
|
||||
<img src="assets/readme-connection-map-v2.png" alt="How Hermes-Relay connects — Dashboard and Gateway own the standard Android path for Chat, Manage, Voice, and inbound files; the optional Relay plugin separately adds Android enhancements plus CLI and UI tools; sideload adds Device Control." width="1000">
|
||||
</p>
|
||||
|
||||
## Quick Start (Android)
|
||||
@@ -50,7 +50,7 @@ Install → connect → talk, in about two minutes.
|
||||
|
||||
### 1 · Install the app
|
||||
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, and Manage work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, media, notifications, and Relay sessions.
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, Manage, and inbound files work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, notifications, Relay sessions, and media enhancements.
|
||||
- **APK** *(full phone-control feature set)* — download the file ending in **`-sideload-release.apk`** from the newest `android-v*` release on [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases) and open it (allow your browser to install unknown apps the first time). Integrity verification, signing fingerprint, and per-build details are in the [Sideload guide](https://hermes-relay.dev/docs/guide/getting-started.html#sideload-apk).
|
||||
|
||||
Sideload builds check GitHub for updates and show a one-tap banner when you're behind; Play builds update through the Store. See [Release tracks](https://hermes-relay.dev/docs/guide/release-tracks) for the capability matrix.
|
||||
@@ -58,7 +58,7 @@ Sideload builds check GitHub for updates and show a one-tap banner when you're b
|
||||
### 2 · Have the Hermes Dashboard running
|
||||
|
||||
The normal Android connection uses the upstream Hermes Dashboard/Gateway for
|
||||
chat, sign-in, sessions, Manage, and voice. Installing Hermes and choosing a
|
||||
chat, sign-in, sessions, Manage, voice, and inbound files. Installing Hermes and choosing a
|
||||
provider is vanilla Hermes setup:
|
||||
|
||||
```bash
|
||||
@@ -77,16 +77,15 @@ the [remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
||||
|
||||
### 3 · Connect and talk
|
||||
|
||||
For a plugin-enabled host, open the Web Dashboard's **Relay** page, click
|
||||
**Connect mobile app**, and scan that tokenless QR from Android **Connect → Scan
|
||||
Hermes setup QR**. It contains only the Dashboard address and configures the
|
||||
upstream Chat, sessions, Manage, sign-in, and standard voice connection.
|
||||
|
||||
Without the Dashboard plugin, use **Find Hermes on LAN** or enter the Dashboard
|
||||
address manually (conventionally `http://<host>:9119`). Sign in through the
|
||||
Use **Find Hermes on LAN** or enter the Dashboard address manually
|
||||
(conventionally `http://<host>:9119`). Sign in through the
|
||||
Dashboard's configured provider when prompted. The app probes the available
|
||||
upstream capabilities and finishes with a connection summary.
|
||||
|
||||
If the Relay Dashboard page is already installed, **Connect mobile app** offers
|
||||
the same standard connection as a tokenless QR. It contains only the Dashboard
|
||||
address and does not install, enable, or pair Relay.
|
||||
|
||||
The separate API server can be discovered automatically or added later under
|
||||
**Advanced** as a chat fallback or for a headless compatibility setup. Its API
|
||||
key is requested only when that optional endpoint is configured. Existing
|
||||
@@ -99,7 +98,7 @@ The wizard probes everything and finishes with a capability card:
|
||||
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
||||
| **API fallback** | Optional API route available/unavailable |
|
||||
| **Direct API** | Optional API-only compatibility route available/unavailable |
|
||||
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
@@ -109,9 +108,9 @@ the whole Vanilla Hermes setup.
|
||||
|
||||
### 4 · Recommended: pair Relay for the complete experience
|
||||
|
||||
Install Relay for Terminal/TUI, notifications, media handoff, desktop tools,
|
||||
enhanced voice, Relay sessions, approval-gated page drafts, and optional Device
|
||||
Control:
|
||||
Install Relay for Terminal/TUI, notifications, desktop tools, enhanced voice,
|
||||
Relay sessions, approval-gated page drafts, optional Device Control, and media
|
||||
compatibility or sensitivity metadata:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
@@ -140,7 +139,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
|
||||
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
|
||||
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. The API fallback is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -161,7 +160,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/supplemental/15_git_workspace.png" alt="Native Git workspace showing repository changes, an inline diff, and staging controls" width="260"><br>
|
||||
<sub><b>Native Git workspace</b> — optional Hermes-Relay plugin</sub>
|
||||
<sub><b>Native Git workspace</b> — upstream session context with optional Relay discovery and operations</sub>
|
||||
</p>
|
||||
|
||||
### Simplified Chinese
|
||||
@@ -239,17 +238,17 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice, inbound files]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media enhancements, relay voice, sessions]
|
||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||
```
|
||||
|
||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
||||
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
|
||||
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
|
||||
install needs no plugin for either. The optional relay on `:8767` adds the power
|
||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
||||
install needs no plugin for those surfaces or ordinary inbound files. The optional relay on `:8767` adds
|
||||
terminal, bridge phone control, media compatibility/metadata, machine tools, and
|
||||
relay-side voice, which is preferred automatically when paired. One QR can
|
||||
configure API, dashboard, and relay routes without merging their auth models.
|
||||
|
||||
|
||||
@@ -6,6 +6,31 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Restore the plugin manifest v2 declaration after the Hermes installer fix ships
|
||||
|
||||
Hermes installers in affected stable releases reject `manifest_version: 2`
|
||||
before the v2-capable runtime loader can inspect the plugin. Track upstream
|
||||
[PR #85893](https://github.com/NousResearch/hermes-agent/pull/85893). Restore
|
||||
`plugin/plugin.yaml` to `manifest_version: 2` only after that fix ships in a
|
||||
stable Hermes release that Hermes-Relay can treat as its minimum supported
|
||||
version. Until then, keep the v1 compatibility declaration and the additive
|
||||
metadata consumed by newer hosts.
|
||||
|
||||
---
|
||||
|
||||
## Consider hosted Android emulator execution
|
||||
|
||||
The local API 36 Gradle Managed Device lanes are intentionally on demand and
|
||||
individually selected. The current Android On-Demand workflow covers hosted
|
||||
source, unit, lint, and build verification only; it does not run emulators. If
|
||||
local emulator capacity becomes a recurring constraint, evaluate a separately
|
||||
approved hosted-emulator design with explicit cost, concurrency, artifact
|
||||
retention, and trigger policy. Do not schedule the full form-factor matrix or
|
||||
add a device farm until that policy is approved; keep live-server mutation tests
|
||||
outside any automatic matrix.
|
||||
|
||||
---
|
||||
|
||||
## Upstream a public Dashboard plugin WebSocket admission seam
|
||||
|
||||
The same-origin Relay ingress follows current upstream's bundled Dashboard
|
||||
@@ -20,6 +45,32 @@ compatibility route.
|
||||
|
||||
---
|
||||
|
||||
## Upstream an Android Gateway platform hint
|
||||
|
||||
Android currently identifies its standard Gateway sessions with the legacy
|
||||
`webui` source because upstream has no stable Android/mobile session platform.
|
||||
Current upstream deliberately removed the unused `webui` prompt hint and only
|
||||
ships renderer-verified `desktop` and `tui` guidance. Do not relabel Android as
|
||||
Desktop: that would also advertise Desktop-only inline widgets and directives.
|
||||
Propose an upstream Android/mobile platform hint, or a bounded authenticated
|
||||
client-surface context contract, that accurately describes mobile Markdown,
|
||||
standard upstream media/file delivery, and concise-response expectations. Once
|
||||
that contract is available in the supported Hermes baseline, adopt it and add
|
||||
Gateway conformance coverage proving the exact prompt bytes and session source.
|
||||
|
||||
---
|
||||
|
||||
## Scope sensitive-media prompt guidance to capable clients
|
||||
|
||||
The Relay plugin's sensitive-media prompt section currently describes the
|
||||
Android `||||` and alt-text conventions profile-wide. Before
|
||||
expanding that behavior, make the section depend on an authoritative client
|
||||
capability or replace it with a portable convention verified against every
|
||||
renderer that receives the profile prompt. Do not make Desktop/TUI sessions
|
||||
emit Android-only spoiler syntax merely because the Relay plugin is installed.
|
||||
|
||||
---
|
||||
|
||||
## Certify Android session activity across lifecycle and profile boundaries
|
||||
|
||||
The contract fixture now covers every upstream live status, complete-snapshot
|
||||
@@ -28,8 +79,11 @@ and older Gateways without `session.active_list`. Before calling the status
|
||||
model device-certified:
|
||||
|
||||
- Exercise working, quiet tool-heavy work, each pending-input surface, normal
|
||||
completion, Stop, reconnect, app restart, and process recreation against
|
||||
current vanilla upstream.
|
||||
completion, a lost terminal followed by an exact active-list Idle row, Stop,
|
||||
reconnect, app restart, and process recreation against current vanilla
|
||||
upstream. Confirm the lost-terminal path preserves the partial transcript,
|
||||
settles composer/steering state, and drains or cancels queued corrections
|
||||
exactly once according to the owning turn outcome.
|
||||
- Verify All Profiles with duplicate session ids across two profiles and two
|
||||
saved connections; no late snapshot or old socket generation may mark the
|
||||
wrong row live.
|
||||
|
||||
@@ -249,6 +249,58 @@ android {
|
||||
it.systemProperty("roborazzi.test.record", "true")
|
||||
it.maxHeapSize = "2g"
|
||||
}
|
||||
|
||||
// On-demand only. Keep each form factor as an individually selected
|
||||
// Gradle-managed device; there is deliberately no aggregate matrix
|
||||
// task or scheduled emulator job. See docs/android-emulator-testing.md.
|
||||
managedDevices {
|
||||
localDevices {
|
||||
create("compactPhoneApi36") {
|
||||
device = "Pixel 2"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("standardPhoneApi36") {
|
||||
device = "Pixel 6"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("largePhoneApi36") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("foldableApi36") {
|
||||
device = "Pixel Fold"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("tabletApi36") {
|
||||
device = "Pixel Tablet"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("futureApi37Ps16k") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 37
|
||||
systemImageSource = "google_apis_playstore"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
pageAlignment =
|
||||
com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +442,12 @@ dependencies {
|
||||
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
|
||||
testImplementation(libs.konsist)
|
||||
androidTestImplementation(libs.compose.ui.test.junit4)
|
||||
// Compose UI Test still declares Espresso 3.5.0 transitively. API 37
|
||||
// removed the reflected InputManager.getInstance() seam; Espresso 3.7.0
|
||||
// uses Context.getSystemService and is the current stable AndroidX line.
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
androidTestImplementation("androidx.test:runner:1.7.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
// On-device vanilla-Gateway contract tests exercise the production
|
||||
// Dashboard ticket + WebSocket stack over real loopback sockets.
|
||||
androidTestImplementation(libs.okhttp.mockwebserver)
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
|
||||
+241
-7
@@ -4,6 +4,7 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -17,6 +18,11 @@ import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
@@ -27,6 +33,7 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
@@ -44,6 +51,7 @@ import okhttp3.mockwebserver.RecordedRequest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
@@ -74,10 +82,11 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
|
||||
@Volatile
|
||||
private var persistedHistory: List<MessageItem> = emptyList()
|
||||
private val historySignInRequired = MutableStateFlow(false)
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
fixture = AndroidGatewayContractFixture().also { it.profileName = PROFILE_NAME }
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
@@ -97,6 +106,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
handler,
|
||||
)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setSessionProfileNameProvider { PROFILE_NAME }
|
||||
it.setProfileMessageLoader { Result.success(persistedHistory) }
|
||||
it.updateGatewayClient(gatewayClient)
|
||||
it.setChatVisible(true)
|
||||
@@ -105,6 +115,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
compose.setContent {
|
||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("contract-transcript")) {
|
||||
Text(
|
||||
@@ -117,6 +128,14 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
modifier = Modifier.testTag("message-${message.id}"),
|
||||
)
|
||||
}
|
||||
if (signInRequired) {
|
||||
Button(
|
||||
onClick = {},
|
||||
modifier = Modifier.testTag("dashboard-sign-in-recovery"),
|
||||
) {
|
||||
Text("SIGN IN")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,6 +258,46 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActiveList_settlesExactOwnedTurnAndRendersAuthoritativeHistory() {
|
||||
viewModel.sendMessage("Run an Android-owned task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", PARTIAL_ANSWER) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.activeSessionStatus = "idle"
|
||||
runBlocking { gatewayClient.listActiveSessions() }
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gatewayClient.hasActiveTurn() &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
assertEquals(0, fixture.rpcCount("session.interrupt"))
|
||||
assertEquals(0, fixture.rpcCount("session.activate"))
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
@@ -252,9 +311,6 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
@@ -269,6 +325,17 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
assertTrue(runBlocking { gatewayClient.observeAwait() })
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
viewModel.updateSessionActivityDirectory(listOf(PROFILE_NAME to STORED_SESSION_ID))
|
||||
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
@@ -293,6 +360,141 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalCompletion_genericHistory401RetainsTranscriptAndRequiresProfileSignIn() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = "Unauthorized",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
|
||||
viewModel.sendMessage("Keep this local transcript")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value &&
|
||||
!handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == LOCAL_COMPLETION }
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local transcript" })
|
||||
assertTrue(handler.messages.value.any { it.content == LOCAL_COMPLETION })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveredCompletion_sessionExpiredHistoryRetainsSettledTranscript() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = """{"reason":"session_expired"}""",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
val now = System.currentTimeMillis()
|
||||
val contextKey = AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME)
|
||||
viewModel.setChatTurnCheckpointStore(
|
||||
MemoryCheckpointStore(
|
||||
ChatTurnCheckpoint(
|
||||
contextKey = contextKey,
|
||||
profileKey = PROFILE_NAME,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
liveSessionId = LIVE_SESSION_ID,
|
||||
transport = "gateway",
|
||||
user = ChatTurnUserCheckpoint("recovered-user", "Resume this turn", now - 2_000L),
|
||||
assistant = ChatTurnAssistantCheckpoint(
|
||||
id = "recovered-assistant",
|
||||
content = "Recovered partial",
|
||||
timestamp = now - 1_900L,
|
||||
),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
startedAt = now - 2_000L,
|
||||
updatedAt = now,
|
||||
),
|
||||
),
|
||||
)
|
||||
fixture.recoveryRunning = true
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
|
||||
fixture.awaitRpc("session.activate")
|
||||
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value && !handler.isStreaming.value
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(
|
||||
"recovered completion was not retained: ${handler.messages.value}",
|
||||
handler.messages.value.any { it.content.contains(RECOVERED_COMPLETION.trim()) },
|
||||
)
|
||||
assertFalse(handler.messages.value.any { it.isStreaming || it.isThinkingStreaming })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
private fun bindDashboardHistoryFailure(body: String, profileName: String) {
|
||||
fixture.profileName = profileName
|
||||
fixture.historyFailureBody = body
|
||||
val dashboard = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
)
|
||||
viewModel.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
|
||||
dashboard.getSessionMessages(sessionId, profile, mode)
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler {
|
||||
historySignInRequired.value = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertExactProfileHistoryOnly(profileName: String) {
|
||||
val historyRequests = fixture.historyRequestPaths()
|
||||
assertTrue("no Dashboard history request was observed", historyRequests.isNotEmpty())
|
||||
assertTrue(
|
||||
"history escaped the exact profile: $historyRequests",
|
||||
historyRequests.all { it.contains("profile=$profileName") },
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
@@ -301,6 +503,23 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
const val PARTIAL_ANSWER = "Partial foreground answer"
|
||||
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
|
||||
const val FOREIGN_ANSWER = "Wrong session content"
|
||||
const val PROFILE_NAME = "research"
|
||||
const val LOCAL_COMPLETION = "Completed before Dashboard auth expired."
|
||||
const val RECOVERED_COMPLETION = " and then recovered to completion."
|
||||
}
|
||||
}
|
||||
|
||||
private class MemoryCheckpointStore(
|
||||
private var checkpoint: ChatTurnCheckpoint?,
|
||||
) : ChatTurnCheckpointStore {
|
||||
override suspend fun read(): ChatTurnCheckpoint? = checkpoint
|
||||
|
||||
override suspend fun write(checkpoint: ChatTurnCheckpoint) {
|
||||
this.checkpoint = checkpoint
|
||||
}
|
||||
|
||||
override suspend fun clear() {
|
||||
checkpoint = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +539,12 @@ internal class AndroidGatewayContractFixture {
|
||||
@Volatile
|
||||
var activeSessionStatus: String? = null
|
||||
|
||||
@Volatile
|
||||
var historyFailureBody: String? = null
|
||||
|
||||
@Volatile
|
||||
var profileName: String = "default"
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
@@ -377,6 +602,11 @@ internal class AndroidGatewayContractFixture {
|
||||
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
|
||||
)
|
||||
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
|
||||
path.startsWith("/api/sessions/") && path.contains("/messages") &&
|
||||
historyFailureBody != null -> MockResponse()
|
||||
.setResponseCode(401)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(historyFailureBody.orEmpty())
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
@@ -388,7 +618,7 @@ internal class AndroidGatewayContractFixture {
|
||||
put("session_id", sessionId)
|
||||
put("running", recoveryRunning)
|
||||
put("status", if (recoveryRunning) "streaming" else "idle")
|
||||
put("info", buildJsonObject { put("profile_name", "default") })
|
||||
put("info", buildJsonObject { put("profile_name", profileName) })
|
||||
}
|
||||
|
||||
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
|
||||
@@ -406,7 +636,7 @@ internal class AndroidGatewayContractFixture {
|
||||
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
|
||||
|
||||
fun awaitRpc(method: String): JsonObject {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
|
||||
Thread.sleep(20)
|
||||
@@ -415,7 +645,7 @@ internal class AndroidGatewayContractFixture {
|
||||
}
|
||||
|
||||
fun awaitRpcCount(method: String, count: Int) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (rpcCount(method) >= count) return
|
||||
Thread.sleep(20)
|
||||
@@ -425,6 +655,10 @@ internal class AndroidGatewayContractFixture {
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun historyRequestPaths(): List<String> = requestPaths.filter {
|
||||
it.startsWith("/api/sessions/") && it.contains("/messages")
|
||||
}
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
|
||||
fun shutdown() {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 509 KiB |
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
|
||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Stable owner for an Auto chat before a conversation is opened.
|
||||
*
|
||||
* A legacy API-only record has no persisted Dashboard route; the conventional
|
||||
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
|
||||
* must not silently turn that compatibility record into a Gateway-owned chat.
|
||||
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
|
||||
* standard Chat belongs to Gateway even while that route is signed out or
|
||||
* temporarily unreachable.
|
||||
*/
|
||||
val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
if (preference == "auto") automaticChatTransport
|
||||
else SessionTransport.forEndpoint(preference)
|
||||
|
||||
@@ -124,7 +124,7 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback" -> "api"
|
||||
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "API fallback",
|
||||
label = "Direct API",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardHttpException
|
||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
||||
import java.io.IOException
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
@@ -9,113 +15,178 @@ import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
// Read + write client for the Hermes-Relay Git State endpoints.
|
||||
// All requests are confined to the ``hermes-relay`` plugin namespace and the
|
||||
// ``git/*`` sub-path via ScopedPluginApiClient, which rejects traversal and
|
||||
// encodes query values.
|
||||
|
||||
private fun pathsArray(paths: List<String>) = buildJsonArray { paths.forEach { add(JsonPrimitive(it)) } }
|
||||
|
||||
/**
|
||||
* Uses official Dashboard `/api/git/…` reads for the active session repository.
|
||||
* Relay remains the discovery source and owns stronger write/preview extensions.
|
||||
* Operational upstream failures are never hidden by a Relay retry; only a 404
|
||||
* can fall back to a matching Relay-discovered repository.
|
||||
*/
|
||||
class GitStateApiClient(
|
||||
dashboard: DashboardApiClient,
|
||||
private val dashboard: DashboardApiClient,
|
||||
) {
|
||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val reposById = linkedMapOf<String, GitRepo>()
|
||||
private val relayRepoIdsByRoot = linkedMapOf<String, String>()
|
||||
|
||||
suspend fun repos(): Result<List<GitRepo>> = scoped
|
||||
.get("git/repos")
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<ReposResponse>(element).repos
|
||||
suspend fun repos(
|
||||
sessionRepoPath: String? = null,
|
||||
includeRelayDiscovery: Boolean = true,
|
||||
): Result<List<GitRepo>> {
|
||||
reposById.clear()
|
||||
relayRepoIdsByRoot.clear()
|
||||
val path = sessionRepoPath?.trim().orEmpty()
|
||||
if (path.isBlank()) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
suspend fun status(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitStatus>(element) }
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<BranchesResponse>(element).branches
|
||||
val upstream = upstreamStatus(path)
|
||||
if (upstream.isFailure) {
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.failure(error)
|
||||
}
|
||||
val status = upstream.getOrNull()
|
||||
if (status == null) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitDiff>(element) }
|
||||
val standardRepo = GitRepo(
|
||||
id = UPSTREAM_SESSION_REPO_ID,
|
||||
name = path.replace('\\', '/').trimEnd('/').substringAfterLast('/').ifBlank { path },
|
||||
root = path,
|
||||
currentBranch = status.branch,
|
||||
dirty = status.changed > 0,
|
||||
route = GitRepositoryRoute.UPSTREAM,
|
||||
)
|
||||
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitFile>(element) }
|
||||
// Plugin discovery is an enhancement. Once upstream answered, plugin
|
||||
// absence or breakage cannot take the standard session repository down.
|
||||
val relay = if (includeRelayDiscovery) relayRepos().getOrDefault(emptyList()) else emptyList()
|
||||
val merged = buildList {
|
||||
add(standardRepo)
|
||||
addAll(relay.filterNot { sameRoot(it.root, standardRepo.root) })
|
||||
}
|
||||
rememberRepos(merged)
|
||||
rememberRelayRepos(relay)
|
||||
return Result.success(merged)
|
||||
}
|
||||
|
||||
// ── Write operations ───────────────────────────────────────────────────
|
||||
// Every write requires the plugin.api.write grant, which the app enforces
|
||||
// (see GitStateViewModel: a POST is never sent without the grant). The
|
||||
// server additionally enforces per-use confirmation strings for destructive
|
||||
// ops (discard/push/dirty-checkout) — the caller passes the echoed token.
|
||||
suspend fun status(repo: String): Result<GitStatus> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayStatus(repo)
|
||||
return fallbackOnUnsupported(target, upstreamStatusWithFiles(target.root), ::relayStatus)
|
||||
}
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayBranches(repo)
|
||||
return fallbackOnUnsupported(target, upstreamBranches(target.root), ::relayBranches)
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayDiff(repo, path, kind)
|
||||
val upstream = dashboard.getJsonElement(
|
||||
upstreamPath(
|
||||
"/api/git/review/diff",
|
||||
mapOf(
|
||||
"path" to target.root,
|
||||
"file" to path,
|
||||
"scope" to "uncommitted",
|
||||
"staged" to (kind == "staged").toString(),
|
||||
),
|
||||
),
|
||||
).mapCatching { element ->
|
||||
GitDiff(
|
||||
path = path,
|
||||
kind = kind,
|
||||
diff = json.decodeFromJsonElement<UpstreamDiffResponse>(element).diff,
|
||||
)
|
||||
}
|
||||
return fallbackOnUnsupported(target, upstream) { relay -> relayDiff(relay, path, kind) }
|
||||
}
|
||||
|
||||
/** Clean tracked-file preview is a Relay enhancement; file-diff is not equivalent. */
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("Tracked-file preview requires the Relay plugin"))
|
||||
return relayFile(relay, path)
|
||||
}
|
||||
|
||||
// Writes intentionally stay on Relay. The upstream Desktop mutation shape
|
||||
// does not carry plugin.api.write or the server-enforced confirmation echoes
|
||||
// used by this mobile surface, so it is not an equivalent safety contract.
|
||||
|
||||
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun discard(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
put("confirmation", confirmation)
|
||||
put("delete_untracked", deleteUntracked)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||
scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commitSelected(
|
||||
repo: String,
|
||||
message: String,
|
||||
paths: List<String>,
|
||||
): Result<GitMutationResult> = scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||
scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||
scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun push(
|
||||
repo: String,
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
): Result<GitMutationResult> = scoped.post("git/push", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/push", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
put("confirmation", confirmation)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun checkout(
|
||||
repo: String,
|
||||
@@ -123,41 +194,217 @@ class GitStateApiClient(
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (confirmation != null) put("confirmation", confirmation)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
// ── Phase 3 extras ─────────────────────────────────────────────────────
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> = relayWrite(repo) { relay ->
|
||||
scoped.post("git/commit_message", buildJsonObject { put("repo", relay) })
|
||||
.mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
}
|
||||
|
||||
/** Generate a commit-message suggestion from the staged diff. */
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> =
|
||||
scoped.post("git/commit_message", buildJsonObject {
|
||||
put("repo", repo)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
suspend fun commitMessageSelected(repo: String, paths: List<String>): Result<GitCommitMessage> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) } }
|
||||
|
||||
/** Generate a commit-message suggestion from the given paths' staged diff. */
|
||||
suspend fun commitMessageSelected(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
): Result<GitCommitMessage> = scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
|
||||
/** Checkout that auto-stashes a dirty tree first. */
|
||||
suspend fun stashCheckout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitStashCheckoutResult> = scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitStashCheckoutResult> = relayWrite(repo) { relay -> scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) }
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) } }
|
||||
|
||||
private suspend fun relayRepos(): Result<List<GitRepo>> = scoped.get("git/repos").mapCatching {
|
||||
json.decodeFromJsonElement<ReposResponse>(it).repos
|
||||
}
|
||||
|
||||
private suspend fun relayStatus(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<GitStatus>(it) }
|
||||
|
||||
private suspend fun relayBranches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<BranchesResponse>(it).branches }
|
||||
|
||||
private suspend fun relayDiff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { json.decodeFromJsonElement<GitDiff>(it) }
|
||||
|
||||
private suspend fun relayFile(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { json.decodeFromJsonElement<GitFile>(it) }
|
||||
|
||||
private suspend fun upstreamStatus(path: String): Result<UpstreamStatus?> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/status", mapOf("path" to path)))
|
||||
.mapCatching { json.decodeFromJsonElement<UpstreamStatus?>(it) }
|
||||
|
||||
private suspend fun upstreamStatusWithFiles(path: String): Result<GitStatus> {
|
||||
val status = upstreamStatus(path).mapCatching {
|
||||
it ?: throw IOException("The active session path is not a Git repository")
|
||||
}.getOrElse { return Result.failure(it) }
|
||||
val review = dashboard.getJsonElement(
|
||||
upstreamPath("/api/git/review/list", mapOf("path" to path, "scope" to "uncommitted")),
|
||||
).mapCatching { json.decodeFromJsonElement<UpstreamReviewList>(it) }
|
||||
.getOrElse { return Result.failure(it) }
|
||||
val statusByPath = status.files.associateBy { it.path }
|
||||
val staged = mutableListOf<GitStatusEntry>()
|
||||
val modified = mutableListOf<GitStatusEntry>()
|
||||
val untracked = mutableListOf<GitStatusEntry>()
|
||||
review.files.forEach { file ->
|
||||
val entry = GitStatusEntry(file.path, file.added, file.removed)
|
||||
val fileStatus = statusByPath[file.path]
|
||||
if (fileStatus?.untracked == true) {
|
||||
untracked += entry
|
||||
} else {
|
||||
if (file.staged || fileStatus?.staged == true) staged += entry
|
||||
if (fileStatus?.unstaged == true || (!file.staged && fileStatus == null)) {
|
||||
modified += entry
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result.success(
|
||||
GitStatus(
|
||||
counts = GitStatusCounts(
|
||||
staged = status.staged,
|
||||
modified = status.unstaged,
|
||||
untracked = status.untracked,
|
||||
changes = status.changed,
|
||||
additions = status.added,
|
||||
deletions = status.removed,
|
||||
),
|
||||
staged = staged,
|
||||
modified = modified,
|
||||
untracked = untracked,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun upstreamBranches(path: String): Result<List<GitBranch>> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/branches", mapOf("path" to path)))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<UpstreamBranches>(element).branches.map {
|
||||
GitBranch(name = it.name, isCurrent = it.checkedOut)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> fallbackOnUnsupported(
|
||||
target: GitRepo,
|
||||
upstream: Result<T>,
|
||||
relayCall: suspend (String) -> Result<T>,
|
||||
): Result<T> {
|
||||
if (upstream.isSuccess) return upstream
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
val relay = relayRepoIdsByRoot[normalizedRoot(target.root)] ?: return Result.failure(error)
|
||||
return relayCall(relay)
|
||||
}
|
||||
|
||||
private suspend fun <T> relayWrite(repo: String, block: suspend (String) -> Result<T>): Result<T> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("This Git action requires the Relay plugin enhancement"))
|
||||
return block(relay)
|
||||
}
|
||||
|
||||
private fun relayRepoId(repo: String): String? {
|
||||
val target = reposById[repo] ?: return repo.takeUnless { it == UPSTREAM_SESSION_REPO_ID }
|
||||
return if (target.route == GitRepositoryRoute.RELAY) target.id
|
||||
else relayRepoIdsByRoot[normalizedRoot(target.root)]
|
||||
}
|
||||
|
||||
private fun rememberRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { reposById[it.id] = it }
|
||||
rememberRelayRepos(repos.filter { it.route == GitRepositoryRoute.RELAY })
|
||||
}
|
||||
|
||||
private fun rememberRelayRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { relayRepoIdsByRoot[normalizedRoot(it.root)] = it.id }
|
||||
}
|
||||
|
||||
private fun upstreamPath(path: String, query: Map<String, String>): String = buildString {
|
||||
append(path)
|
||||
if (query.isNotEmpty()) {
|
||||
append('?')
|
||||
append(query.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" })
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String =
|
||||
URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
|
||||
|
||||
private fun normalizedRoot(path: String): String {
|
||||
val normalized = path.trim().replace('\\', '/').trimEnd('/')
|
||||
return if (WINDOWS_ROOT.containsMatchIn(normalized) || normalized.startsWith("//")) {
|
||||
normalized.lowercase(Locale.ROOT)
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
private fun sameRoot(first: String, second: String): Boolean =
|
||||
normalizedRoot(first) == normalizedRoot(second)
|
||||
|
||||
private fun Result<kotlinx.serialization.json.JsonObject>.decodeMutation(): Result<GitMutationResult> =
|
||||
mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
private fun Throwable.isUnsupportedGitRoute(): Boolean =
|
||||
this is DashboardHttpException && statusCode == 404
|
||||
|
||||
private companion object {
|
||||
const val UPSTREAM_SESSION_REPO_ID = "__upstream_session__"
|
||||
val WINDOWS_ROOT = Regex("^[A-Za-z]:/")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatus(
|
||||
val branch: String? = null,
|
||||
val staged: Int = 0,
|
||||
val unstaged: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
val changed: Int = 0,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val files: List<UpstreamStatusFile> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatusFile(
|
||||
val path: String,
|
||||
val staged: Boolean = false,
|
||||
val unstaged: Boolean = false,
|
||||
val untracked: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewList(val files: List<UpstreamReviewFile> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewFile(
|
||||
val path: String,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val staged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranches(val branches: List<UpstreamBranch> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranch(
|
||||
val name: String,
|
||||
@SerialName("checkedOut") val checkedOut: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamDiffResponse(val diff: String = "")
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.hermesandroid.relay.data
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** A repository discovered by the plugin's /git/repos endpoint. */
|
||||
/** A current-session upstream repository or a Relay-discovered repository. */
|
||||
@Serializable
|
||||
data class GitRepo(
|
||||
val id: String,
|
||||
@@ -11,9 +11,19 @@ data class GitRepo(
|
||||
val root: String,
|
||||
@SerialName("current_branch") val currentBranch: String? = null,
|
||||
val dirty: Boolean = false,
|
||||
val route: GitRepositoryRoute = GitRepositoryRoute.RELAY,
|
||||
)
|
||||
|
||||
/** Working-tree status from /git/status. */
|
||||
@Serializable
|
||||
enum class GitRepositoryRoute {
|
||||
@SerialName("relay")
|
||||
RELAY,
|
||||
|
||||
@SerialName("upstream")
|
||||
UPSTREAM,
|
||||
}
|
||||
|
||||
/** Normalized working-tree status from upstream or Relay Git routes. */
|
||||
@Serializable
|
||||
data class GitStatus(
|
||||
val counts: GitStatusCounts = GitStatusCounts(),
|
||||
|
||||
@@ -81,6 +81,24 @@ class SupervisedModeStore private constructor(
|
||||
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
|
||||
}
|
||||
|
||||
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
|
||||
internal suspend fun disableAllAndRemoveCredential(
|
||||
parentCredentialKey: Preferences.Key<String>,
|
||||
) {
|
||||
dataStore.edit { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt || decoded.policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
val disabled = decoded.policies.mapValues { (_, policy) ->
|
||||
policy.copy(enabled = false).normalized()
|
||||
}
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
|
||||
}
|
||||
preferences.remove(parentCredentialKey)
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodeResult {
|
||||
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
|
||||
return try {
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Availability of the app-specific parent credential. */
|
||||
enum class SupervisedParentAuthStatus {
|
||||
Missing,
|
||||
Configured,
|
||||
Corrupt,
|
||||
}
|
||||
|
||||
/** Input method selected for the app-specific parent credential. */
|
||||
@Serializable
|
||||
enum class SupervisedParentCredentialType {
|
||||
Legacy,
|
||||
Pin,
|
||||
Password,
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private enum class SupervisedRecoveryFormat {
|
||||
LegacyCode,
|
||||
WordPhrase,
|
||||
}
|
||||
|
||||
/** Result of a parent-secret or recovery-phrase verification attempt. */
|
||||
sealed interface SupervisedParentAuthResult {
|
||||
data object Success : SupervisedParentAuthResult
|
||||
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
|
||||
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
|
||||
data object Missing : SupervisedParentAuthResult
|
||||
data object Corrupt : SupervisedParentAuthResult
|
||||
}
|
||||
|
||||
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
|
||||
data class SupervisedParentEnrollment(val recoveryPhrase: String)
|
||||
|
||||
/** Validation result for a new parent PIN or password. */
|
||||
data class SupervisedParentSecretValidation(
|
||||
val valid: Boolean,
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
|
||||
interface SupervisedParentAuthenticator {
|
||||
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
|
||||
suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
|
||||
suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
}
|
||||
|
||||
/**
|
||||
* App-specific parent authentication for Supervised Mode.
|
||||
*
|
||||
* This store deliberately does not delegate to Android's device credential: a
|
||||
* child can legitimately own the PIN or biometrics on their Android profile.
|
||||
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
|
||||
* secret and recovery phrase are never persisted.
|
||||
*/
|
||||
class SupervisedParentAuthStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
private val iterations: Int,
|
||||
private val minimumAcceptedIterations: Int,
|
||||
private val random: SecureRandom,
|
||||
private val nowMillis: () -> Long,
|
||||
) : SupervisedParentAuthenticator {
|
||||
constructor(context: Context) : this(
|
||||
dataStore = context.applicationContext.relayDataStore,
|
||||
iterations = DEFAULT_PBKDF2_ITERATIONS,
|
||||
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
|
||||
random = SecureRandom(),
|
||||
nowMillis = System::currentTimeMillis,
|
||||
)
|
||||
|
||||
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
|
||||
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).status
|
||||
}
|
||||
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).record?.credentialType
|
||||
}
|
||||
|
||||
override suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
|
||||
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
|
||||
}
|
||||
runCatching { enrollLocked(newSecret, credentialType) }
|
||||
}
|
||||
|
||||
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
|
||||
verifyLocked(secret, AuthTarget.ParentSecret)
|
||||
}
|
||||
|
||||
override suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
val record = decode(dataStore.data.first()[KEY_RECORD]).record
|
||||
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
|
||||
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
|
||||
try {
|
||||
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
} finally {
|
||||
normalizedRecovery.fill('\u0000')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated escape hatch used by the parent controls.
|
||||
*
|
||||
* The app-global credential cannot be removed while leaving any supervised
|
||||
* policy enabled. Every policy is disabled, but its configuration is retained,
|
||||
* in the same transaction that removes the credential.
|
||||
*/
|
||||
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
|
||||
runCatching {
|
||||
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun enrollLocked(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentEnrollment {
|
||||
require(credentialType != SupervisedParentCredentialType.Legacy)
|
||||
val recoveryChars = generateRecoveryPhrase().toCharArray()
|
||||
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
var parentVerifier = ByteArray(0)
|
||||
var recoveryVerifier = ByteArray(0)
|
||||
try {
|
||||
parentVerifier = derive(secret, parentSalt, iterations)
|
||||
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
|
||||
val record = PersistedParentAuth(
|
||||
iterations = iterations,
|
||||
parentSalt = encode(parentSalt),
|
||||
parentVerifier = encode(parentVerifier),
|
||||
recoverySalt = encode(recoverySalt),
|
||||
recoveryVerifier = encode(recoveryVerifier),
|
||||
credentialType = credentialType,
|
||||
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
|
||||
)
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
return SupervisedParentEnrollment(recoveryChars.concatToString())
|
||||
} finally {
|
||||
recoveryChars.fill('\u0000')
|
||||
parentSalt.fill(0)
|
||||
recoverySalt.fill(0)
|
||||
parentVerifier.fill(0)
|
||||
recoveryVerifier.fill(0)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun verifyLocked(
|
||||
candidate: CharArray,
|
||||
target: AuthTarget,
|
||||
): SupervisedParentAuthResult {
|
||||
val decoded = decode(dataStore.data.first()[KEY_RECORD])
|
||||
val record = decoded.record ?: return when (decoded.status) {
|
||||
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
|
||||
else -> SupervisedParentAuthResult.Corrupt
|
||||
}
|
||||
val now = nowMillis()
|
||||
if (record.blockedUntilEpochMillis > now) {
|
||||
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
|
||||
}
|
||||
|
||||
val saltText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentSalt
|
||||
AuthTarget.RecoveryCode -> record.recoverySalt
|
||||
}
|
||||
val verifierText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentVerifier
|
||||
AuthTarget.RecoveryCode -> record.recoveryVerifier
|
||||
}
|
||||
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val actual = try {
|
||||
derive(candidate, salt, record.iterations)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to derive supervised parent verifier", error)
|
||||
return SupervisedParentAuthResult.Corrupt
|
||||
} finally {
|
||||
salt.fill(0)
|
||||
}
|
||||
val matches = try {
|
||||
MessageDigest.isEqual(expected, actual)
|
||||
} finally {
|
||||
expected.fill(0)
|
||||
actual.fill(0)
|
||||
}
|
||||
|
||||
if (matches) {
|
||||
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
|
||||
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
|
||||
}
|
||||
return SupervisedParentAuthResult.Success
|
||||
}
|
||||
|
||||
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
|
||||
val delayMillis = backoffMillis(failures)
|
||||
save(
|
||||
record.copy(
|
||||
failedAttempts = failures,
|
||||
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
|
||||
),
|
||||
)
|
||||
return if (delayMillis == 0L) {
|
||||
SupervisedParentAuthResult.Invalid(
|
||||
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
|
||||
)
|
||||
} else {
|
||||
SupervisedParentAuthResult.Throttled(delayMillis)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun save(record: PersistedParentAuth) {
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
}
|
||||
|
||||
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
|
||||
withContext(Dispatchers.Default) {
|
||||
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
|
||||
try {
|
||||
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodedRecord {
|
||||
if (raw.isNullOrBlank()) {
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
|
||||
}
|
||||
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
|
||||
.getOrElse {
|
||||
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
val valid = record.version == RECORD_VERSION &&
|
||||
record.algorithm == KDF_ALGORITHM &&
|
||||
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
|
||||
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
|
||||
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
|
||||
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
|
||||
record.blockedUntilEpochMillis >= 0
|
||||
return if (valid) {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
|
||||
} else {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateRecoveryPhrase(): String {
|
||||
val available = RECOVERY_WORDS.toMutableList()
|
||||
val selected = buildList(RECOVERY_WORD_COUNT) {
|
||||
repeat(RECOVERY_WORD_COUNT) {
|
||||
add(available.removeAt(random.nextInt(available.size)))
|
||||
}
|
||||
}
|
||||
return selected.joinToString("-")
|
||||
}
|
||||
|
||||
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
|
||||
private fun decodeBytes(value: String): ByteArray? =
|
||||
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
|
||||
|
||||
private fun backoffMillis(failures: Int): Long = when (failures) {
|
||||
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
|
||||
FAILURES_BEFORE_BACKOFF -> 30_000L
|
||||
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
|
||||
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
|
||||
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
|
||||
else -> MAX_BACKOFF_MILLIS
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedParentAuth(
|
||||
val version: Int = RECORD_VERSION,
|
||||
val algorithm: String = KDF_ALGORITHM,
|
||||
val iterations: Int,
|
||||
val parentSalt: String,
|
||||
val parentVerifier: String,
|
||||
val recoverySalt: String,
|
||||
val recoveryVerifier: String,
|
||||
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
|
||||
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
|
||||
val failedAttempts: Int = 0,
|
||||
val blockedUntilEpochMillis: Long = 0L,
|
||||
)
|
||||
|
||||
private data class DecodedRecord(
|
||||
val status: SupervisedParentAuthStatus,
|
||||
val record: PersistedParentAuth?,
|
||||
)
|
||||
|
||||
private enum class AuthTarget { ParentSecret, RecoveryCode }
|
||||
|
||||
class ParentAuthenticationException(
|
||||
val authResult: SupervisedParentAuthResult,
|
||||
) : IllegalStateException("Parent authentication failed: $authResult")
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SupervisedParentAuth"
|
||||
private const val RECORD_VERSION = 1
|
||||
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
|
||||
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
|
||||
private const val MIN_ACCEPTED_ITERATIONS = 100_000
|
||||
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
|
||||
private const val SALT_BYTES = 16
|
||||
private const val KEY_BITS = 256
|
||||
private const val FAILURES_BEFORE_BACKOFF = 5
|
||||
private const val MAX_TRACKED_FAILURES = 9
|
||||
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
|
||||
private const val RECOVERY_WORD_COUNT = 6
|
||||
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
|
||||
private val processMutex = Mutex()
|
||||
|
||||
fun validateNewSecret(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentSecretValidation {
|
||||
if (secret.size > 64) {
|
||||
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
|
||||
}
|
||||
if (credentialType == SupervisedParentCredentialType.Pin) {
|
||||
return if (secret.size == 6 && secret.all(Char::isDigit)) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
|
||||
}
|
||||
}
|
||||
return if (
|
||||
credentialType == SupervisedParentCredentialType.Password &&
|
||||
secret.size >= 8 && secret.any { !it.isWhitespace() }
|
||||
) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeRecoveryPhrase(
|
||||
value: CharArray,
|
||||
format: SupervisedRecoveryFormat,
|
||||
): CharArray = when (format) {
|
||||
SupervisedRecoveryFormat.LegacyCode -> value
|
||||
.filterNot { it == '-' || it.isWhitespace() }
|
||||
.joinToString("")
|
||||
.uppercase()
|
||||
.toCharArray()
|
||||
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
|
||||
.trim()
|
||||
.lowercase()
|
||||
.split(Regex("[-\\s]+"))
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("-")
|
||||
.toCharArray()
|
||||
}
|
||||
|
||||
private val RECOVERY_WORDS = listOf(
|
||||
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
|
||||
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
|
||||
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
|
||||
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
|
||||
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
|
||||
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
|
||||
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
|
||||
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
|
||||
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
|
||||
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
|
||||
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
|
||||
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
|
||||
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
|
||||
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
|
||||
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
|
||||
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
|
||||
)
|
||||
|
||||
internal fun forTesting(
|
||||
dataStore: DataStore<Preferences>,
|
||||
iterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
random: SecureRandom = SecureRandom(),
|
||||
nowMillis: () -> Long = System::currentTimeMillis,
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore(
|
||||
dataStore = dataStore,
|
||||
iterations = iterations,
|
||||
minimumAcceptedIterations = minimumAcceptedIterations,
|
||||
random = random,
|
||||
nowMillis = nowMillis,
|
||||
)
|
||||
|
||||
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
|
||||
}
|
||||
}
|
||||
@@ -344,6 +344,46 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
|
||||
dataStore.edit { it[key] = route.storageValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Relay-only selections after Relay has been explicitly removed from
|
||||
* the active connection. A temporarily unreachable configured Relay must
|
||||
* not call this: preserving the selection lets the richer route resume
|
||||
* when connectivity returns.
|
||||
*
|
||||
* [expectedScope] fences profile/connection changes that can race the
|
||||
* DataStore edit. Values are re-read inside the transaction instead of
|
||||
* trusting an earlier settings snapshot, so a newer user choice wins.
|
||||
* The legacy default-profile keys are global (their storage names predate
|
||||
* connection scoping), so they are never rewritten here: runtime fallback
|
||||
* handles an unpaired default profile without changing another
|
||||
* connection's selection.
|
||||
*/
|
||||
suspend fun reconcileRelayRemoval(expectedScope: VoiceProfileScope): Boolean {
|
||||
if (_scope.value != expectedScope || expectedScope.profileName == null) return false
|
||||
var changed = false
|
||||
dataStore.edit { prefs ->
|
||||
if (_scope.value != expectedScope) return@edit
|
||||
|
||||
val engine = VoiceEngineMode.fromStorage(
|
||||
resolveString(prefs, KEY_ENGINE_MODE, expectedScope, DEFAULT_ENGINE_MODE),
|
||||
)
|
||||
val route = VoiceAudioRoute.fromStorage(
|
||||
resolveString(prefs, KEY_AUDIO_ROUTE, expectedScope, DEFAULT_AUDIO_ROUTE),
|
||||
)
|
||||
if (engine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_ENGINE_MODE, expectedScope))] =
|
||||
VoiceEngineMode.HermesVoiceOutput.storageValue
|
||||
changed = true
|
||||
}
|
||||
if (route == VoiceAudioRoute.Relay) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_AUDIO_ROUTE, expectedScope))] =
|
||||
VoiceAudioRoute.Auto.storageValue
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/** "" clears the override (relay falls back to the server's saved voice). */
|
||||
suspend fun setEnhancedVoice(voice: String) {
|
||||
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
||||
|
||||
@@ -28,6 +28,7 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
||||
|
||||
@@ -88,6 +89,7 @@ class RelayHttpClient(
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayHttpClient"
|
||||
private const val DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES = 100L * 1024L * 1024L
|
||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
|
||||
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
|
||||
@@ -257,7 +259,10 @@ class RelayHttpClient(
|
||||
* underlying exception with a human-readable message suitable for
|
||||
* surfacing in the attachment's `errorMessage` field.
|
||||
*/
|
||||
suspend fun fetchMedia(token: String): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
suspend fun fetchMedia(
|
||||
token: String,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
return@withContext Result.failure(
|
||||
@@ -318,7 +323,7 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
@@ -352,6 +357,7 @@ class RelayHttpClient(
|
||||
suspend fun fetchMediaByPath(
|
||||
path: String,
|
||||
contentTypeHint: String? = null,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
@@ -427,12 +433,16 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMediaByPath failed for $path: ${e.message}")
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
if (e is RelayMediaLimitException) {
|
||||
Result.failure(e)
|
||||
} else {
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
||||
Result.failure(e)
|
||||
@@ -1456,6 +1466,33 @@ class RelayHttpClient(
|
||||
return match?.groupValues?.get(1)?.trim()?.ifBlank { null }
|
||||
}
|
||||
|
||||
private fun okhttp3.ResponseBody.readBytesBounded(maxBytes: Long): ByteArray {
|
||||
if (maxBytes <= 0L) throw RelayMediaLimitException()
|
||||
val declared = contentLength().takeIf { it >= 0L }
|
||||
if (declared != null && declared > maxBytes) throw RelayMediaLimitException()
|
||||
val output = ByteArrayOutputStream(
|
||||
declared?.coerceAtMost(Int.MAX_VALUE.toLong())?.toInt() ?: DEFAULT_BUFFER_SIZE,
|
||||
)
|
||||
byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
if (total > maxBytes) throw RelayMediaLimitException()
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
if (declared != null && total != declared) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
private class RelayMediaLimitException :
|
||||
IOException("File exceeds the configured download limit")
|
||||
|
||||
/**
|
||||
* Parse the relay's `X-Media-Sensitive` response header into a bool.
|
||||
*
|
||||
@@ -1468,7 +1505,7 @@ class RelayHttpClient(
|
||||
return value == "1" || value == "true"
|
||||
}
|
||||
|
||||
/** Provider-neutral compatibility fetch for gateways without `account.usage`. */
|
||||
/** Provider-neutral enhancement for pools and providers upstream does not expose. */
|
||||
suspend fun fetchProviderUsage(
|
||||
profile: String? = null,
|
||||
sessionId: String? = null,
|
||||
|
||||
@@ -1540,19 +1540,28 @@ class ChatHandler {
|
||||
val prior = priorById[messageId]
|
||||
// Outbound attachments: prefer an id-match (covers any future
|
||||
// user-message id reconciliation), else fall back to the
|
||||
// content-keyed queue. Inbound attachments normally come back via
|
||||
// marker re-dispatch. One narrow exception retains a completed
|
||||
// image_generate result when the immediate post-turn history read
|
||||
// still lacks its MEDIA marker; otherwise the rendered image
|
||||
// disappears during the persistence-lag window.
|
||||
// content-keyed queue. Exact inbound marker attachments are also
|
||||
// carried by id: a history refresh must not replace a successfully
|
||||
// loaded image/file with a fresh LOADING placeholder. A process
|
||||
// restart has no prior attachment, so the marker still dispatches
|
||||
// normally and rehydrates it. One additional narrow exception
|
||||
// retains a completed image_generate result when the immediate
|
||||
// post-turn history read still lacks its MEDIA marker.
|
||||
val carriedAttachments = run {
|
||||
val persistedImagePaths = persistedImages.paths.toHashSet()
|
||||
val persistedMediaKeys = messageMediaHits.mapTo(HashSet()) { (_, hit) ->
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> hit.token
|
||||
is MediaMarkerHit.BarePath -> hit.path
|
||||
}
|
||||
}
|
||||
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
|
||||
isImageGenerationToolName(tool.name) &&
|
||||
tool.isComplete && tool.success != false
|
||||
}
|
||||
val byId = prior?.attachments.orEmpty().filter { attachment ->
|
||||
attachment.relayToken == null ||
|
||||
attachment.relayToken in persistedMediaKeys ||
|
||||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
||||
(
|
||||
role == MessageRole.ASSISTANT &&
|
||||
@@ -1708,15 +1717,27 @@ class ChatHandler {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.token } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.path } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+132
-8
@@ -52,6 +52,7 @@ import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resume
|
||||
@@ -310,6 +311,19 @@ data class ElevenLabsVoices(
|
||||
val voices: List<ElevenLabsVoice>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Bytes fetched from upstream's authenticated managed-files surface.
|
||||
*
|
||||
* The Dashboard applies its own managed-root, sensitive-file, and maximum-size
|
||||
* policy before these bytes leave the Hermes host. Android applies the user's
|
||||
* stricter inbound-media cap while reading the response as a second boundary.
|
||||
*/
|
||||
data class DashboardFetchedFile(
|
||||
val bytes: ByteArray,
|
||||
val contentType: String,
|
||||
val fileName: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Native client for the Hermes dashboard/admin server (:9119).
|
||||
*
|
||||
@@ -381,6 +395,75 @@ class DashboardApiClient(
|
||||
executeJsonElement(request, normalized)
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a server-local artifact through current upstream Hermes.
|
||||
*
|
||||
* This is the same authenticated `/api/files/download` route official
|
||||
* Desktop uses for remote gateway files. The caller supplies its display
|
||||
* cap so a malicious or stale Content-Length cannot cause an unbounded
|
||||
* allocation. Audio/video are downloaded into Android's local media cache;
|
||||
* local playback supplies seeking, so `/api/files/stream` is unnecessary
|
||||
* on this path.
|
||||
*/
|
||||
suspend fun downloadManagedFile(
|
||||
serverPath: String,
|
||||
maxBytes: Long,
|
||||
): Result<DashboardFetchedFile> = withContext(Dispatchers.IO) {
|
||||
if (serverPath.isBlank()) {
|
||||
return@withContext Result.failure(IOException("Media path is empty"))
|
||||
}
|
||||
if (maxBytes <= 0L) {
|
||||
return@withContext Result.failure(IOException("Media download limit is invalid"))
|
||||
}
|
||||
val httpUrl = resolveUrl("/api/files/download")
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("path", serverPath)
|
||||
?.build()
|
||||
?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder().url(httpUrl).get().build()
|
||||
|
||||
executeCancellable(request, "Dashboard media download") { response ->
|
||||
val body = response.body
|
||||
val declaredLength = body.contentLength().takeIf { it >= 0L }
|
||||
if (declaredLength != null && declaredLength > maxBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
val initialSize = declaredLength
|
||||
?.coerceAtMost(Int.MAX_VALUE.toLong())
|
||||
?.toInt()
|
||||
?: DEFAULT_BUFFER_SIZE
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
body.byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var readTotal = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
readTotal += count
|
||||
if (readTotal > maxBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
if (declaredLength != null && readTotal != declaredLength) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
}
|
||||
DashboardFetchedFile(
|
||||
bytes = output.toByteArray(),
|
||||
contentType = response.header("Content-Type")
|
||||
?.substringBefore(';')
|
||||
?.trim()
|
||||
?.takeIf(String::isNotEmpty)
|
||||
?: "application/octet-stream",
|
||||
fileName = response.header("Content-Disposition")
|
||||
?.let(::contentDispositionFileName)
|
||||
?: serverPath.substringAfterLast('/').substringAfterLast('\\')
|
||||
.takeIf(String::isNotBlank),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun postJsonObject(
|
||||
path: String,
|
||||
payload: JsonObject = JsonObject(emptyMap()),
|
||||
@@ -2405,6 +2488,23 @@ private fun Response.readJsonElement(json: Json): JsonElement {
|
||||
return json.parseToJsonElement(raw)
|
||||
}
|
||||
|
||||
private fun contentDispositionFileName(header: String): String? {
|
||||
val encoded = Regex("""filename\*=UTF-8''([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.let { runCatching { java.net.URLDecoder.decode(it, "UTF-8") }.getOrNull() }
|
||||
val plain = Regex("""filename=\"([^\"]+)\"|filename=([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.let { it.groupValues[1].ifBlank { it.groupValues[2] } }
|
||||
?.trim()
|
||||
?.trim('"')
|
||||
return (encoded ?: plain)
|
||||
?.substringAfterLast('/')
|
||||
?.substringAfterLast('\\')
|
||||
?.takeIf(String::isNotBlank)
|
||||
}
|
||||
|
||||
internal class DashboardHttpException(
|
||||
val statusCode: Int,
|
||||
message: String,
|
||||
@@ -2436,14 +2536,11 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
if (
|
||||
current is DashboardHttpException &&
|
||||
current.statusCode == 401 &&
|
||||
(
|
||||
current.message.orEmpty().contains("no_cookie", ignoreCase = true) ||
|
||||
current.message.orEmpty().contains("unauthenticated", ignoreCase = true)
|
||||
)
|
||||
) {
|
||||
// Every 401 from an authenticated Dashboard route means the saved
|
||||
// browser/native session can no longer authorize this request. Older
|
||||
// gateways used `no_cookie`/`unauthenticated`; current builds may return
|
||||
// reason codes such as `session_expired`, or no structured body at all.
|
||||
if (current is DashboardHttpException && current.statusCode == 401) {
|
||||
return true
|
||||
}
|
||||
current = current.cause
|
||||
@@ -2451,6 +2548,33 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/** True only when the managed-file route itself is absent on this Hermes build. */
|
||||
internal fun Throwable.isDashboardManagedFilesUnsupported(): Boolean {
|
||||
var current: Throwable? = this
|
||||
val seen = java.util.Collections.newSetFromMap(
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
if (current is DashboardHttpException) {
|
||||
if (current.statusCode in setOf(405, 501)) return true
|
||||
if (current.statusCode == 404) {
|
||||
val detail = current.message.orEmpty()
|
||||
// FastAPI's missing-route response is the generic "Not Found".
|
||||
// A real managed-file miss says "File not found" and must not
|
||||
// silently escape to Relay's broader path policy.
|
||||
val isManagedFileMiss = detail.contains("File not found", ignoreCase = true) ||
|
||||
detail.contains("Path not found", ignoreCase = true)
|
||||
val isGenericRouteMiss = detail.trim().endsWith(": not found", ignoreCase = true) ||
|
||||
detail.contains("\"detail\":\"Not Found\"", ignoreCase = true) ||
|
||||
detail.contains("\"detail\": \"Not Found\"", ignoreCase = true)
|
||||
if (!isManagedFileMiss && isGenericRouteMiss) return true
|
||||
}
|
||||
}
|
||||
current = current.cause
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val bodyDetail = runCatching { response.body.string() }.getOrDefault("")
|
||||
val detail = bodyDetail.take(240).ifBlank { response.message }
|
||||
|
||||
+173
-17
@@ -119,6 +119,8 @@ class GatewayChatClient(
|
||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
|
||||
/** Test seam — compaction idle lease. Production keeps [COMPACTING_TIMEOUT_MS]. */
|
||||
private val compactingTimeoutMs: Long = COMPACTING_TIMEOUT_MS,
|
||||
/** Random source for ordinary reconnect full-jitter. */
|
||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||
) : GatewayProfileEditorClient {
|
||||
@@ -159,6 +161,19 @@ class GatewayChatClient(
|
||||
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
||||
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_000L
|
||||
|
||||
/**
|
||||
* Server-side context compaction summarizes the transcript through a
|
||||
* (possibly slow) model with NO deltas or tool events flowing until it
|
||||
* finishes — near the context ceiling that silence routinely exceeds
|
||||
* [TURN_TIMEOUT_MS], so the idle watchdog would `session.interrupt` a
|
||||
* healthy compression, roll back its work, and retrigger on the next
|
||||
* prompt forever. A `status.update` event with kind `compacting`
|
||||
* (emitted at compaction start, and periodically by newer gateways)
|
||||
* arms this longer leash instead; any regular event rearms
|
||||
* [TURN_TIMEOUT_MS].
|
||||
*/
|
||||
private const val COMPACTING_TIMEOUT_MS = 600_000L
|
||||
|
||||
private const val RPC_TIMEOUT_MS = 15_000L
|
||||
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
||||
|
||||
@@ -263,7 +278,7 @@ class GatewayChatClient(
|
||||
.newBuilder()
|
||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
||||
// the WS upgrade. A failed connect drops chat to the SSE fallback and a
|
||||
// the WS upgrade. A failed connect leaves Android on its Gateway owner and a
|
||||
// 5s cooldown, so give the first remote handshake room.
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.pingInterval(30, TimeUnit.SECONDS)
|
||||
@@ -384,6 +399,14 @@ class GatewayChatClient(
|
||||
private val _serverProject = MutableStateFlow<GatewaySessionProject?>(null)
|
||||
val serverProject: StateFlow<GatewaySessionProject?> = _serverProject.asStateFlow()
|
||||
|
||||
/**
|
||||
* Exact model-callable tool names from upstream `session.info.tools` for
|
||||
* the selected live session/profile. Null means the gateway has not
|
||||
* supplied a catalog; an empty set means it authoritatively supplied none.
|
||||
*/
|
||||
private val _serverTools = MutableStateFlow<Set<String>?>(null)
|
||||
val serverTools: StateFlow<Set<String>?> = _serverTools.asStateFlow()
|
||||
|
||||
/** Serializes connect / session-establish so concurrent sends share one socket. */
|
||||
private val connectMutex = Mutex()
|
||||
|
||||
@@ -548,6 +571,28 @@ class GatewayChatClient(
|
||||
val terminalRequired: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* One exact turn settled from authoritative session state may still receive
|
||||
* the terminal frame that was already in flight. Consume only that terminal
|
||||
* so it cannot be reported as a second unmatched completion. A subsequent
|
||||
* message.start clears the drain because it establishes the next turn on
|
||||
* the same live runtime.
|
||||
*/
|
||||
@Volatile
|
||||
private var settledTurnDrain: SettledTurnDrain? = null
|
||||
|
||||
private data class SettledTurnDrain(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
)
|
||||
|
||||
private data class ActiveTurnLivenessProbe(
|
||||
val turn: GatewayTurn,
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val progressGeneration: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates UI callbacks when the server starts a turn that has no matching
|
||||
* [sendTurn] call (for example a background-process completion). The
|
||||
@@ -677,6 +722,7 @@ class GatewayChatClient(
|
||||
): ActiveTurnHandle {
|
||||
val turn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
androidOwned = true,
|
||||
onTransportAccepted = onTransportAccepted,
|
||||
)
|
||||
// Warm = the connection-establish phases are skipped this turn (socket
|
||||
@@ -724,6 +770,10 @@ class GatewayChatClient(
|
||||
cleanupStagedAttachments(stagedImagePaths)
|
||||
return@launch
|
||||
}
|
||||
// A newly accepted Android send is a distinct generation on
|
||||
// this runtime. Its terminal must never be consumed by the
|
||||
// prior turn's optional late-terminal drain.
|
||||
settledTurnDrain = null
|
||||
activeTurn = turn
|
||||
turn.armWatchdog()
|
||||
// Generic `file.attach` uploads are staged artifacts, not
|
||||
@@ -758,7 +808,7 @@ class GatewayChatClient(
|
||||
// Once this turn's own events are flowing (or it already
|
||||
// finished), the prompt provably reached the server — a
|
||||
// slow, lost, or socket-severed ack must NOT preflight-fail
|
||||
// into the SSE fallback, which would resubmit the same
|
||||
// into a second transport, which would resubmit the same
|
||||
// prompt as a duplicate turn. Recovery belongs to the
|
||||
// stream: the watchdog and mid-turn rejoin own it.
|
||||
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
||||
@@ -850,6 +900,7 @@ class GatewayChatClient(
|
||||
storedSessionId = null
|
||||
liveSessionProfile = null
|
||||
cancelledTurnDrain = null
|
||||
_serverTools.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1363,6 +1414,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1486,6 +1538,7 @@ class GatewayChatClient(
|
||||
boundTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1519,6 +1572,7 @@ class GatewayChatClient(
|
||||
val queuedTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
// recoverTurn is resumed on its caller's coroutine context;
|
||||
// ChatViewModel calls it from Main, so this admission runs
|
||||
@@ -1765,18 +1819,17 @@ class GatewayChatClient(
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider-neutral account limits owned by upstream Hermes. Current hosts
|
||||
* may not expose this additive method yet; callers should treat JSON-RPC
|
||||
* method-not-found as capability absence and use the optional Relay
|
||||
* compatibility surface when paired.
|
||||
* Official upstream Nous usage bars. Current hosts may not expose this
|
||||
* additive method yet; callers should treat JSON-RPC method-not-found as
|
||||
* capability absence and use the optional Relay enhancement when paired.
|
||||
*/
|
||||
suspend fun providerUsage(): Result<JsonObject> {
|
||||
suspend fun usageBars(): Result<JsonObject> {
|
||||
try {
|
||||
connectMutex.withLock { ensureConnected() }
|
||||
} catch (e: Exception) {
|
||||
return Result.failure(e)
|
||||
}
|
||||
return rpc("account.usage", JsonObject(emptyMap()))
|
||||
return rpc("usage.bars", JsonObject(emptyMap()))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2414,6 +2467,7 @@ class GatewayChatClient(
|
||||
} catch (error: Exception) {
|
||||
return GatewayActiveSessionsResult.TransientFailure(error)
|
||||
}
|
||||
val livenessProbe = captureActiveTurnLivenessProbe()
|
||||
val result = rpc(
|
||||
"session.active_list",
|
||||
buildJsonObject {
|
||||
@@ -2433,12 +2487,58 @@ class GatewayChatClient(
|
||||
val payload = result.getOrThrow()
|
||||
val rows = payload["sessions"] as? JsonArray
|
||||
?: throw GatewayRpcException("session.active_list returned no sessions array")
|
||||
GatewayActiveSessionsResult.Success(rows.map(::parseGatewayActiveSession))
|
||||
val sessions = rows.map(::parseGatewayActiveSession)
|
||||
reconcileActiveTurnFromSnapshot(livenessProbe, sessions)
|
||||
GatewayActiveSessionsResult.Success(sessions)
|
||||
} catch (parseError: Exception) {
|
||||
GatewayActiveSessionsResult.TransientFailure(parseError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture only a locally submitted/recovered turn. Merely observing an
|
||||
* exact session through the shared Gateway socket never grants Android
|
||||
* authority to settle Desktop/TUI work.
|
||||
*/
|
||||
private fun captureActiveTurnLivenessProbe(): ActiveTurnLivenessProbe? {
|
||||
val turn = activeTurn ?: return null
|
||||
val generation = turn.captureLivenessGeneration() ?: return null
|
||||
val storedId = storedSessionId ?: return null
|
||||
val liveId = liveSessionId ?: return null
|
||||
return ActiveTurnLivenessProbe(turn, storedId, liveId, generation)
|
||||
}
|
||||
|
||||
/**
|
||||
* `session.active_list` is process-wide, but a row naming both identifiers
|
||||
* already owned by this client is authoritative for that exact runtime.
|
||||
* Fence the delayed snapshot by turn identity and progress generation so an
|
||||
* old idle result cannot settle a newer turn or race newer live events.
|
||||
*/
|
||||
private fun reconcileActiveTurnFromSnapshot(
|
||||
probe: ActiveTurnLivenessProbe?,
|
||||
sessions: List<GatewayActiveSession>,
|
||||
) {
|
||||
probe ?: return
|
||||
if (activeTurn !== probe.turn ||
|
||||
storedSessionId != probe.storedSessionId ||
|
||||
liveSessionId != probe.liveSessionId
|
||||
) return
|
||||
val exact = sessions.singleOrNull { row ->
|
||||
row.runtimeSessionId == probe.liveSessionId &&
|
||||
row.storedSessionId == probe.storedSessionId
|
||||
} ?: return
|
||||
if (exact.status != GatewayActiveSessionStatus.Idle) return
|
||||
if (probe.turn.settleFromAuthoritativeSessionState(
|
||||
running = false,
|
||||
source = "session.active_list",
|
||||
expectedProgressGeneration = probe.progressGeneration,
|
||||
)
|
||||
) {
|
||||
if (activeTurn === probe.turn) activeTurn = null
|
||||
if (!AppForegroundTracker.isForeground.value) scheduleBackgroundClose()
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop one process owned by the current live gateway session. */
|
||||
suspend fun killProcess(processId: String): Result<Unit> {
|
||||
if (processId.isBlank()) {
|
||||
@@ -2831,6 +2931,7 @@ class GatewayChatClient(
|
||||
activeTurn = null
|
||||
backgroundTurns.clear()
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
unsolicitedTurnProvider = null
|
||||
coldPrewarmSessionReadyListener = null
|
||||
unmatchedTurnCompleteListener = null
|
||||
@@ -3134,6 +3235,18 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (info.containsKey("tools")) {
|
||||
val groups = info["tools"] as? JsonObject
|
||||
_serverTools.value = groups
|
||||
?.values
|
||||
?.asSequence()
|
||||
?.mapNotNull { it as? JsonArray }
|
||||
?.flatMap { it.asSequence() }
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
|
||||
?.filter { it.isNotBlank() }
|
||||
?.toSet()
|
||||
?: emptySet()
|
||||
}
|
||||
// Context usage: require used > 0 — a COLD resume resets counters and
|
||||
// reports 0 until the first turn rebuilds the prompt; painting 0 would
|
||||
// mislead on a session that actually has history.
|
||||
@@ -3149,6 +3262,7 @@ class GatewayChatClient(
|
||||
/** Apply a session create/resume result without leaking metadata from the prior session. */
|
||||
private fun applySessionResultInfo(result: JsonObject) {
|
||||
_serverProject.value = null
|
||||
_serverTools.value = null
|
||||
(result["info"] as? JsonObject)?.let { applySessionInfo(it) }
|
||||
}
|
||||
|
||||
@@ -3267,6 +3381,7 @@ class GatewayChatClient(
|
||||
val requestedProfile = currentSessionProfile()
|
||||
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
}
|
||||
if (
|
||||
liveSessionId != null &&
|
||||
@@ -3336,6 +3451,7 @@ class GatewayChatClient(
|
||||
storedSessionId = stored
|
||||
liveSessionProfile = requestedProfile
|
||||
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
||||
if (settledTurnDrain?.storedSessionId != stored) settledTurnDrain = null
|
||||
turn.callbacks.onSessionId(stored)
|
||||
}
|
||||
|
||||
@@ -3713,6 +3829,7 @@ class GatewayChatClient(
|
||||
}
|
||||
dispatchProcessEvent(type, payload, eventSessionId)
|
||||
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
||||
if (consumeSettledTurnTerminal(type, eventSessionId)) return
|
||||
var turn = activeTurn
|
||||
if (turn == null && type == "message.start") {
|
||||
// Unsolicited turns are accepted only with an explicit exact live-
|
||||
@@ -4226,10 +4343,12 @@ class GatewayChatClient(
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
||||
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
|
||||
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
|
||||
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
eventType == "status.update" &&
|
||||
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
|
||||
else -> turnIdleTimeoutMs
|
||||
}
|
||||
|
||||
@@ -4237,6 +4356,7 @@ class GatewayChatClient(
|
||||
val callbacks: GatewayTurnCallbacks,
|
||||
dedupeAdjacentMessageStarts: Boolean = false,
|
||||
deferEvents: Boolean = false,
|
||||
private val androidOwned: Boolean = false,
|
||||
private val onTransportAccepted: () -> Unit = { },
|
||||
) : ActiveTurnHandle {
|
||||
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
||||
@@ -4263,6 +4383,7 @@ class GatewayChatClient(
|
||||
|
||||
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
private val transportAccepted = AtomicBoolean(false)
|
||||
private val progressGeneration = java.util.concurrent.atomic.AtomicLong(0L)
|
||||
|
||||
fun markTransportAccepted() {
|
||||
if (transportAccepted.compareAndSet(false, true)) {
|
||||
@@ -4339,6 +4460,7 @@ class GatewayChatClient(
|
||||
if (settledWithoutTerminalFrame) return
|
||||
if (type != "session.info") {
|
||||
started = true
|
||||
progressGeneration.incrementAndGet()
|
||||
markTransportAccepted()
|
||||
}
|
||||
tracer.mark("ttfe")
|
||||
@@ -4348,7 +4470,7 @@ class GatewayChatClient(
|
||||
// Reset on every event — long tool runs keep the turn alive.
|
||||
// Ask requests block with no further events, so they arm with
|
||||
// their own (longer) duration via watchdogTimeoutFor.
|
||||
armWatchdog(watchdogTimeoutFor(type))
|
||||
armWatchdog(watchdogTimeoutFor(type, payload))
|
||||
// Queue this immediately before the terminal callbacks. Both are
|
||||
// marshalled through the same dispatcher, preserving callback order
|
||||
// even when the WebSocket reader and reconnect coroutine differ.
|
||||
@@ -4368,10 +4490,20 @@ class GatewayChatClient(
|
||||
* exact turn has proved it went live. A pre-start `running=false`
|
||||
* heartbeat can race `prompt.submit` and is not a completion boundary.
|
||||
*/
|
||||
fun settleFromAuthoritativeSessionState(running: Boolean?, source: String): Boolean {
|
||||
fun captureLivenessGeneration(): Long? =
|
||||
if (androidOwned && started && !ended) progressGeneration.get() else null
|
||||
|
||||
fun settleFromAuthoritativeSessionState(
|
||||
running: Boolean?,
|
||||
source: String,
|
||||
expectedProgressGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (running != false || !started) return false
|
||||
val settled = synchronized(deferredEventLock) {
|
||||
if (ended) {
|
||||
if (ended ||
|
||||
(expectedProgressGeneration != null &&
|
||||
progressGeneration.get() != expectedProgressGeneration)
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
settledWithoutTerminalFrame = true
|
||||
@@ -4382,6 +4514,7 @@ class GatewayChatClient(
|
||||
if (!settled) return false
|
||||
|
||||
disarmWatchdog()
|
||||
armSettledTurnDrain()
|
||||
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
||||
callbacks.onReconcileRequired()
|
||||
callbacks.onComplete()
|
||||
@@ -4402,6 +4535,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4529,6 +4663,26 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
|
||||
private fun armSettledTurnDrain() {
|
||||
val storedId = storedSessionId ?: return
|
||||
val liveId = liveSessionId ?: return
|
||||
settledTurnDrain = SettledTurnDrain(storedId, liveId)
|
||||
}
|
||||
|
||||
/** Consume one late terminal from a turn already settled by session state. */
|
||||
private fun consumeSettledTurnTerminal(type: String, eventSessionId: String?): Boolean {
|
||||
val drain = settledTurnDrain ?: return false
|
||||
if (eventSessionId != drain.liveSessionId) return false
|
||||
if (type == "message.start") {
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
return false
|
||||
}
|
||||
if (type != "message.complete" && type != "error") return false
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
Log.d(TAG, "Ignored late terminal for gateway turn settled from session state")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun updateCancelledDrainLiveSession(storedId: String, liveId: String) {
|
||||
val drain = cancelledTurnDrain ?: return
|
||||
if (drain.storedSessionId == storedId) {
|
||||
@@ -4655,6 +4809,8 @@ class GatewayChatClient(
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
||||
},
|
||||
onStatusClear = { kind -> dispatchIfCurrent(stillCurrent) { callbacks.onStatusClear(kind) } },
|
||||
onNoticeShow = { notice -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeShow(notice) } },
|
||||
onNoticeClear = { key -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeClear(key) } },
|
||||
)
|
||||
|
||||
private fun dispatchIfCurrent(stillCurrent: () -> Boolean, callback: () -> Unit) {
|
||||
@@ -4707,7 +4863,7 @@ data class GatewayAttachment(
|
||||
val sizeBytes: Long? = null,
|
||||
)
|
||||
|
||||
/** Connect/auth/submit failed before the turn started — safe to fall back to SSE. */
|
||||
/** Connect/auth/submit failed before the turn started; the caller retains transport ownership. */
|
||||
internal class GatewayPreflightException(message: String) : Exception(message)
|
||||
|
||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
|
||||
/**
|
||||
@@ -397,8 +398,26 @@ class GatewayEventMapper(
|
||||
}
|
||||
}
|
||||
|
||||
// Known-but-unrendered (notification.show, …) and unknown types
|
||||
// alike: ignore.
|
||||
"notification.show" -> {
|
||||
val text = payload.string("text")?.trim().orEmpty()
|
||||
if (text.isNotEmpty()) {
|
||||
callbacks.onNoticeShow(
|
||||
GatewayAgentNotice(
|
||||
text = text,
|
||||
level = payload.string("level"),
|
||||
kind = payload.string("kind"),
|
||||
ttlMs = payload.long("ttl_ms"),
|
||||
key = payload.string("key"),
|
||||
id = payload.string("id"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"notification.clear" ->
|
||||
payload.string("key")?.trim()?.takeIf(String::isNotEmpty)?.let(callbacks.onNoticeClear)
|
||||
|
||||
// Unknown event types remain forward-compatible no-ops.
|
||||
else -> Unit
|
||||
}
|
||||
previousEventType = type
|
||||
@@ -596,6 +615,9 @@ private fun JsonObject?.string(key: String): String? =
|
||||
private fun JsonObject?.int(key: String): Int? =
|
||||
(this?.get(key) as? JsonPrimitive)?.intOrNull
|
||||
|
||||
private fun JsonObject?.long(key: String): Long? =
|
||||
(this?.get(key) as? JsonPrimitive)?.longOrNull
|
||||
|
||||
private fun JsonObject?.double(key: String): Double? =
|
||||
(this?.get(key) as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
|
||||
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
|
||||
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
||||
* delegates here with its live state.
|
||||
*
|
||||
* Manual picks pass through untouched (ChatViewModel handles per-turn
|
||||
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
|
||||
* gateway while the dashboard probe is unresolved or ready. A capability-
|
||||
* preferred SSE fallback is selected only after a definitive unavailable,
|
||||
* unsupported, or sign-in-required verdict.
|
||||
* Manual picks pass through untouched. "auto" follows the saved connection's
|
||||
* stable owner: Dashboard/Gateway for a standard connection, or the
|
||||
* capability-preferred SSE surface for a true API-only compatibility record.
|
||||
* Live reachability and sign-in state never change the owner of an open chat.
|
||||
*/
|
||||
fun resolveStreamingEndpointPreference(
|
||||
preference: String,
|
||||
gateway: GatewayAvailability,
|
||||
capabilities: ServerCapabilities,
|
||||
gatewayOwned: Boolean = true,
|
||||
): String = when (preference) {
|
||||
"sessions", "completions", "runs", "gateway" -> preference
|
||||
else -> if (
|
||||
gateway == GatewayAvailability.Ready ||
|
||||
gateway == GatewayAvailability.Unknown
|
||||
) {
|
||||
"gateway"
|
||||
} else {
|
||||
capabilities.preferredChatEndpoint()
|
||||
}
|
||||
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,6 +256,16 @@ data class GatewayToolOutputRisk(
|
||||
val redacted: Boolean,
|
||||
)
|
||||
|
||||
/** Official upstream `notification.show` AgentNotice payload. */
|
||||
data class GatewayAgentNotice(
|
||||
val text: String,
|
||||
val level: String? = null,
|
||||
val kind: String? = null,
|
||||
val ttlMs: Long? = null,
|
||||
val key: String? = null,
|
||||
val id: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One `subagent.*` lifecycle event, emitted on the PARENT session. Lifecycle
|
||||
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
||||
@@ -734,6 +737,10 @@ class GatewayTurnCallbacks(
|
||||
val onStatusUpdate: (kind: String?, text: String) -> Unit = { _, _ -> },
|
||||
/** Clear a transient status only when [kind] still owns the visible status slot. */
|
||||
val onStatusClear: (kind: String) -> Unit = { _ -> },
|
||||
/** Official upstream account/agent notice; distinct from Relay proactive messages. */
|
||||
val onNoticeShow: (GatewayAgentNotice) -> Unit = { _ -> },
|
||||
/** Exact-key dismissal for an upstream notice. */
|
||||
val onNoticeClear: (key: String) -> Unit = { _ -> },
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
+132
-21
@@ -3,10 +3,12 @@ package com.hermesandroid.relay.network.usage
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
|
||||
/** Relay-enhanced usage with an upstream fallback for hosts without Relay support. */
|
||||
/** Upstream usage enriched by the optional Relay provider/pool surface. */
|
||||
class ProviderUsageRepository(
|
||||
private val gatewayClientProvider: () -> GatewayChatClient?,
|
||||
private val dashboardClientProvider: () -> DashboardApiClient? = { null },
|
||||
@@ -14,33 +16,142 @@ class ProviderUsageRepository(
|
||||
private val profileProvider: () -> String? = { null },
|
||||
private val sessionProvider: () -> String? = { null },
|
||||
) {
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
coerceInputValues = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
suspend fun fetch(): Result<ProviderUsageResponse?> {
|
||||
val profile = profileProvider()
|
||||
val session = sessionProvider()
|
||||
val upstream: Result<ProviderUsageResponse?> = gatewayClientProvider()
|
||||
?.usageBars()
|
||||
?.mapCatching(::providerUsageFromUpstreamBars)
|
||||
?: Result.success(null)
|
||||
|
||||
val dashboard = dashboardClientProvider()
|
||||
var enhancement: Result<ProviderUsageResponse?>? = null
|
||||
if (dashboard != null) {
|
||||
val enhanced = dashboard.getProviderUsage(profile, session)
|
||||
if (enhanced.isSuccess && enhanced.getOrNull() != null) return enhanced
|
||||
enhancement = dashboard.getProviderUsage(profile, session)
|
||||
}
|
||||
|
||||
val relay = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
if (enhancement?.getOrNull() == null) {
|
||||
enhancement = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
)
|
||||
}
|
||||
|
||||
val merged = mergeProviderUsage(
|
||||
upstream = upstream.getOrNull(),
|
||||
enhancement = enhancement?.getOrNull(),
|
||||
)
|
||||
if (relay.isSuccess && relay.getOrNull() != null) return relay
|
||||
if (merged != null) return Result.success(merged)
|
||||
|
||||
val gateway = gatewayClientProvider()
|
||||
if (gateway != null) {
|
||||
val upstream = gateway.providerUsage()
|
||||
.mapCatching { json.decodeFromJsonElement<ProviderUsageResponse>(it) }
|
||||
if (upstream.isSuccess) return upstream
|
||||
return when {
|
||||
upstream.isFailure && enhancement?.isFailure == true ->
|
||||
Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
enhancement?.isFailure == true -> Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
else -> Result.success(null)
|
||||
}
|
||||
return relay
|
||||
}
|
||||
}
|
||||
|
||||
internal fun providerUsageFromUpstreamBars(root: JsonObject): ProviderUsageResponse? {
|
||||
if (root.boolean("available") != true) return null
|
||||
|
||||
val renewsAt = root.string("renews_at")
|
||||
val windows = listOfNotNull(
|
||||
root.usageWindow("plan", "Plan", renewsAt),
|
||||
root.usageWindow("topup", "Top-up", null),
|
||||
)
|
||||
val details = listOfNotNull(
|
||||
root.string("subscription_remaining_display")?.let { "Subscription remaining: $it" },
|
||||
root.string("topup_remaining_display")?.let { "Top-up remaining: $it" },
|
||||
root.string("total_spendable_display")?.let { "Total spendable: $it" },
|
||||
)
|
||||
|
||||
return ProviderUsageResponse(
|
||||
providers = listOf(
|
||||
ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "upstream:usage.bars",
|
||||
plan = root.string("plan_name"),
|
||||
windows = windows,
|
||||
details = details,
|
||||
renewsAt = renewsAt,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun mergeProviderUsage(
|
||||
upstream: ProviderUsageResponse?,
|
||||
enhancement: ProviderUsageResponse?,
|
||||
): ProviderUsageResponse? {
|
||||
if (upstream == null) return enhancement
|
||||
if (enhancement == null) return upstream
|
||||
|
||||
val providers = linkedMapOf<String, ProviderUsageProvider>()
|
||||
upstream.providers.forEach { providers[it.id] = it }
|
||||
enhancement.providers.forEach { enhanced ->
|
||||
val standard = providers[enhanced.id]
|
||||
providers[enhanced.id] = when {
|
||||
standard == null -> enhanced
|
||||
standard.available -> standard.copy(
|
||||
// Official usage.bars stays authoritative for every field it
|
||||
// supplies. Relay enriches the row with pool/balance metadata
|
||||
// and fills only gaps that upstream left absent.
|
||||
fetchedAt = standard.fetchedAt ?: enhanced.fetchedAt,
|
||||
plan = standard.plan ?: enhanced.plan,
|
||||
windows = standard.windows.ifEmpty { enhanced.windows },
|
||||
details = (standard.details + enhanced.details).distinct(),
|
||||
balances = enhanced.balances,
|
||||
renewsAt = standard.renewsAt ?: enhanced.renewsAt,
|
||||
actionUrl = standard.actionUrl ?: enhanced.actionUrl,
|
||||
credentials = enhanced.credentials,
|
||||
activeCredentialId = enhanced.activeCredentialId,
|
||||
activeCredentialState = enhanced.activeCredentialState,
|
||||
activeObservedAt = enhanced.activeObservedAt,
|
||||
message = standard.message ?: enhanced.message,
|
||||
)
|
||||
enhanced.available -> enhanced
|
||||
else -> enhanced
|
||||
}
|
||||
}
|
||||
return ProviderUsageResponse(
|
||||
schemaVersion = maxOf(upstream.schemaVersion, enhancement.schemaVersion),
|
||||
fetchedAt = enhancement.fetchedAt ?: upstream.fetchedAt,
|
||||
capabilities = upstream.capabilities + enhancement.capabilities,
|
||||
providers = providers.values.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.usageWindow(
|
||||
id: String,
|
||||
label: String,
|
||||
resetAt: String?,
|
||||
): ProviderUsageWindow? {
|
||||
val bar = this["${id}_bar"] as? JsonObject ?: return null
|
||||
val remaining = bar.string("remaining_display")
|
||||
val total = bar.string("total_display")
|
||||
val detail = when {
|
||||
remaining != null && total != null -> "$remaining remaining of $total"
|
||||
remaining != null -> "$remaining remaining"
|
||||
total != null -> "$total total"
|
||||
else -> null
|
||||
}
|
||||
return ProviderUsageWindow(
|
||||
id = id,
|
||||
label = label,
|
||||
usedPercent = bar.double("pct_used"),
|
||||
resetAt = resetAt,
|
||||
detail = detail,
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.string(key: String): String? =
|
||||
(this[key] as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty)
|
||||
|
||||
private fun JsonObject.boolean(key: String): Boolean? =
|
||||
(this[key] as? JsonPrimitive)?.booleanOrNull
|
||||
|
||||
private fun JsonObject.double(key: String): Double? =
|
||||
(this[key] as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.hermesandroid.relay.data.EnhancedVoiceOverrides
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||
import com.hermesandroid.relay.data.VoiceProfileScope
|
||||
import com.hermesandroid.relay.data.VoiceSettings
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||
@@ -170,6 +171,9 @@ internal class HermesRuntimeBinder(
|
||||
relayHttpClient = connection.relayHttpClient,
|
||||
mediaSettingsRepo = connection.mediaSettingsRepo,
|
||||
mediaCacheWriter = connection.mediaCacheWriter,
|
||||
dashboardMediaClientProvider = {
|
||||
connection.activeDashboardUrl()?.let(connection::dashboardClientForActive)
|
||||
},
|
||||
)
|
||||
chat.setSelectedProfileProvider { connection.selectedProfile.value }
|
||||
chat.setIsolatedProfileApiProvider { connection.selectedProfileUsesIsolatedApiRoute() }
|
||||
@@ -209,6 +213,7 @@ internal class HermesRuntimeBinder(
|
||||
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
|
||||
connection.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
}
|
||||
chat.setDashboardSignInRequiredHandler(connection::probeNow)
|
||||
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
|
||||
chat.profileSessionDeleter = connection::deleteSession
|
||||
chat.profileSessionRenamer = connection::renameSession
|
||||
@@ -261,6 +266,11 @@ internal class HermesRuntimeBinder(
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.isStreaming.collect(connection::setChatStreaming)
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.conversationBinding.collect { binding ->
|
||||
connection.setActiveConversationTransport(binding.transport)
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.activeConnectionId,
|
||||
@@ -281,6 +291,36 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.connectionsHydrated,
|
||||
connection.activeConnectionId,
|
||||
connection.relayConfigured,
|
||||
voiceSettingsHydrated,
|
||||
voicePreferencesRepository.activeScope,
|
||||
) { connectionsReady, connectionId, relayConfigured, settingsReady, scope ->
|
||||
VoiceRelayReconciliationInputs(
|
||||
connectionsReady = connectionsReady,
|
||||
connectionId = connectionId,
|
||||
relayConfigured = relayConfigured,
|
||||
settingsReady = settingsReady,
|
||||
scope = scope,
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
if (
|
||||
inputs.connectionsReady &&
|
||||
inputs.settingsReady &&
|
||||
inputs.connectionId != null &&
|
||||
!inputs.relayConfigured &&
|
||||
// Default-profile storage is a legacy global layer shared
|
||||
// across connections. Keep its fallback runtime-only.
|
||||
inputs.scope.profileName != null &&
|
||||
inputs.scope.connectionId == inputs.connectionId
|
||||
) {
|
||||
voicePreferencesRepository.reconcileRelayRemoval(inputs.scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.streamingEndpoint,
|
||||
@@ -397,13 +437,22 @@ internal class HermesRuntimeBinder(
|
||||
connection.chatReady,
|
||||
connection.standardVoiceAvailability,
|
||||
connection.relayVoiceReady,
|
||||
connection.profileSelectionSettled,
|
||||
) { settings, chatReady, standard, relayReady, profileSettled ->
|
||||
connection.relayConfigured,
|
||||
) { settings, chatReady, standard, relayReady, relayConfigured ->
|
||||
VoiceReadinessInputs(
|
||||
settings = settings,
|
||||
chatReady = chatReady,
|
||||
standardAvailability = standard,
|
||||
relayReady = relayReady,
|
||||
relayConfigured = relayConfigured,
|
||||
)
|
||||
}.combine(connection.profileSelectionSettled) { inputs, profileSettled ->
|
||||
resolveVoiceActivationReadiness(
|
||||
settings,
|
||||
chatReady,
|
||||
standard,
|
||||
relayReady,
|
||||
inputs.settings,
|
||||
inputs.chatReady,
|
||||
inputs.standardAvailability,
|
||||
inputs.relayReady,
|
||||
inputs.relayConfigured,
|
||||
profileSettled,
|
||||
)
|
||||
}
|
||||
@@ -557,6 +606,22 @@ internal class HermesRuntimeBinder(
|
||||
val hiddenSources: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
private data class VoiceRelayReconciliationInputs(
|
||||
val connectionsReady: Boolean,
|
||||
val connectionId: String?,
|
||||
val relayConfigured: Boolean,
|
||||
val settingsReady: Boolean,
|
||||
val scope: VoiceProfileScope,
|
||||
)
|
||||
|
||||
private data class VoiceReadinessInputs(
|
||||
val settings: VoiceSettings,
|
||||
val chatReady: Boolean,
|
||||
val standardAvailability: StandardVoiceAvailability,
|
||||
val relayReady: Boolean,
|
||||
val relayConfigured: Boolean,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val PROFILE_SETTLE_BACKSTOP_MS = 2_500L
|
||||
const val PROFILE_CONTEXT_COALESCE_MS = 160L
|
||||
@@ -595,12 +660,14 @@ internal fun resolveVoiceActivationReadiness(
|
||||
chatReady: Boolean,
|
||||
standardAvailability: StandardVoiceAvailability,
|
||||
relayReady: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
profileSettled: Boolean,
|
||||
): HermesVoiceActivationReadiness {
|
||||
if (!profileSettled) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Loading the selected Hermes profile")
|
||||
}
|
||||
return when (VoiceEngineMode.fromStorage(settings.engineMode)) {
|
||||
val effectiveSettings = voiceSettingsForRelayConfiguration(settings, relayConfigured)
|
||||
return when (VoiceEngineMode.fromStorage(effectiveSettings.engineMode)) {
|
||||
VoiceEngineMode.RealtimeAgent -> {
|
||||
if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Realtime)
|
||||
@@ -612,7 +679,7 @@ internal fun resolveVoiceActivationReadiness(
|
||||
if (!chatReady) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Waiting for Hermes chat")
|
||||
}
|
||||
when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
when (VoiceAudioRoute.fromStorage(effectiveSettings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(
|
||||
HermesVoiceActivationRoute.RelayAudio
|
||||
@@ -636,6 +703,24 @@ internal fun resolveVoiceActivationReadiness(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relay absence is a topology decision, unlike a transient route outage. Only
|
||||
* the former may fall back from Relay-only persisted selections.
|
||||
*/
|
||||
internal fun voiceSettingsForRelayConfiguration(
|
||||
settings: VoiceSettings,
|
||||
relayConfigured: Boolean,
|
||||
): VoiceSettings {
|
||||
if (relayConfigured) return settings
|
||||
return settings.copy(
|
||||
engineMode = VoiceEngineMode.HermesVoiceOutput.storageValue,
|
||||
audioRoute = when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> VoiceAudioRoute.Auto.storageValue
|
||||
else -> settings.audioRoute
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun standardVoiceReadiness(
|
||||
availability: StandardVoiceAvailability,
|
||||
): HermesVoiceActivationReadiness = when (availability) {
|
||||
|
||||
@@ -136,6 +136,8 @@ import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.CandidateBuild
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
@@ -283,6 +285,8 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
connection: Connection?,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
streamingEndpoint: String = "auto",
|
||||
conversationOwner: SessionTransport? = null,
|
||||
): ChatRuntimeStatus {
|
||||
val capabilities = connection?.capabilities
|
||||
val gateway = when {
|
||||
@@ -298,7 +302,11 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
||||
else -> ChatTransportReadiness.Unavailable
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
|
||||
val owner = when (conversationOwner ?: connection?.chatTransportForPreference(streamingEndpoint)) {
|
||||
SessionTransport.SSE -> ChatTransportPath.ApiSse
|
||||
else -> ChatTransportPath.Gateway
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api, owner = owner)
|
||||
}
|
||||
|
||||
internal fun shouldSettleStartupUnreachable(
|
||||
@@ -360,7 +368,7 @@ internal fun resolveFooterRouteCandidate(
|
||||
*
|
||||
* Endpoint roles are operator and wire metadata, so an internal role such as
|
||||
* `authenticated_dashboard` must never leak into this constrained surface.
|
||||
* Gateway labels describe how the Dashboard is reached; API fallback keeps
|
||||
* Gateway labels describe how the Dashboard is reached; Direct API keeps
|
||||
* the route's ordinary transport label.
|
||||
*/
|
||||
internal fun resolveFooterRouteLabel(
|
||||
@@ -1007,6 +1015,17 @@ fun RelayApp() {
|
||||
chatSessions.firstOrNull { it.sessionId == currentChatSessionId }
|
||||
}
|
||||
|
||||
LaunchedEffect(
|
||||
gitOwnerKey,
|
||||
activeChatSession?.gitRepoRoot,
|
||||
activeChatSession?.workingDirectory,
|
||||
) {
|
||||
gitStateViewModel.setSessionWorkspace(
|
||||
repoRoot = activeChatSession?.gitRepoRoot,
|
||||
workingDirectory = activeChatSession?.workingDirectory,
|
||||
)
|
||||
}
|
||||
|
||||
// Bind Git to the active coding session when upstream supplies its exact
|
||||
// workspace metadata. CWD fallback only matches a path-segment descendant;
|
||||
// an ambiguous multi-repo catalog stays unselected until the user chooses.
|
||||
@@ -1023,7 +1042,7 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
|
||||
val gitWorkspaceAvailable = gitRepoScanningEnabled &&
|
||||
val gitWorkspaceAvailable =
|
||||
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
||||
val gitWorkspaceSummary = remember(
|
||||
gitReposState,
|
||||
@@ -1593,6 +1612,7 @@ fun RelayApp() {
|
||||
// evidence alone left a window where the reveal showed the CTA for
|
||||
// the few hundred ms until the client-based health verdict landed.
|
||||
val chatReady by connectionViewModel.chatReady.collectAsState()
|
||||
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
||||
var startupGateTimedOut by remember { mutableStateOf(false) }
|
||||
var startupGateReleased by remember { mutableStateOf(false) }
|
||||
@@ -1619,6 +1639,8 @@ fun RelayApp() {
|
||||
connection = activeConnection,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
apiHealth = apiHealth,
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
conversationOwner = conversationOwner,
|
||||
)
|
||||
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
||||
// connection. Startup readiness follows the same transport-neutral
|
||||
@@ -2125,7 +2147,9 @@ fun RelayApp() {
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||
streamingEndpoint,
|
||||
),
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
@@ -2967,7 +2991,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.AdvancedSettings.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
AdvancedSettingsScreen(
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
@@ -2998,7 +3027,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.SupervisedControls.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SupervisedControlsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
|
||||
@@ -138,12 +138,10 @@ internal fun sanitizeSupervisedChatRouteArgs(
|
||||
}
|
||||
}
|
||||
|
||||
/** A disabled policy may become active only after an enrolled credential succeeds. */
|
||||
/** A disabled policy may become active only after the app-specific parent credential succeeds. */
|
||||
internal fun mayEnableSupervisedMode(
|
||||
policy: SupervisedModePolicy,
|
||||
deviceSecure: Boolean,
|
||||
deviceCredentialConfirmed: Boolean,
|
||||
parentCredentialConfirmed: Boolean,
|
||||
): Boolean = !policy.enabled &&
|
||||
policy.isConfigured &&
|
||||
deviceSecure &&
|
||||
deviceCredentialConfirmed
|
||||
parentCredentialConfirmed
|
||||
|
||||
@@ -8,17 +8,38 @@ import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** Visual tone of a transient banner message. Errors are NOT modelled here —
|
||||
* they stay on the snackbar (see [LocalSnackbarHost]); this bus is info-only. */
|
||||
enum class UiMessageSeverity { Info, Success, Status }
|
||||
/** Visual tone of a transient banner message. */
|
||||
enum class UiMessageSeverity { Info, Success, Status, Warning }
|
||||
|
||||
data class UiMessage(
|
||||
val id: Long,
|
||||
val text: String,
|
||||
val severity: UiMessageSeverity,
|
||||
val ttlMillis: Long,
|
||||
/** Stable upstream key for replace-in-place and exact dismissal. */
|
||||
val key: String? = null,
|
||||
)
|
||||
|
||||
sealed interface UiMessageEvent {
|
||||
data class Show(val message: UiMessage) : UiMessageEvent
|
||||
data class Clear(val key: String) : UiMessageEvent
|
||||
}
|
||||
|
||||
internal fun reduceUiMessages(
|
||||
current: List<UiMessage>,
|
||||
event: UiMessageEvent,
|
||||
maxRetained: Int,
|
||||
): List<UiMessage> = when (event) {
|
||||
is UiMessageEvent.Clear -> current.filterNot { it.key == event.key }
|
||||
is UiMessageEvent.Show -> {
|
||||
val incoming = event.message
|
||||
val withoutDuplicate = current.filterNot { existing ->
|
||||
if (incoming.key != null) existing.key == incoming.key else existing.text == incoming.text
|
||||
}
|
||||
(withoutDuplicate + incoming).takeLast(maxRetained)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* App-wide bus for transient, non-error status/confirmation messages that
|
||||
* surface in the top [com.hermesandroid.relay.ui.components.MessageBannerHost]
|
||||
@@ -26,8 +47,10 @@ data class UiMessage(
|
||||
* shows the newest line collapsed, expands to a few recent lines, auto-dismisses
|
||||
* and coalesces duplicates.
|
||||
*
|
||||
* Deliberately info-only: errors and persistent/actionable messages keep going
|
||||
* to the snackbar so they demand acknowledgement. Migrate frequent
|
||||
* App-owned errors and persistent/actionable messages keep going to the
|
||||
* snackbar so they demand acknowledgement. Upstream keyed AgentNotices may use
|
||||
* the warning tone here because their own sticky/clear lifecycle owns them.
|
||||
* Migrate frequent
|
||||
* `snackbarHostState.showSnackbar("…")` confirmations/status to [info] /
|
||||
* [success] / [status] here.
|
||||
*
|
||||
@@ -39,8 +62,8 @@ object UiMessageBus {
|
||||
const val STATUS_TTL_MS = 6_000L
|
||||
|
||||
private val counter = AtomicLong(0L)
|
||||
private val _events = MutableSharedFlow<UiMessage>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessage> = _events.asSharedFlow()
|
||||
private val _events = MutableSharedFlow<UiMessageEvent>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessageEvent> = _events.asSharedFlow()
|
||||
|
||||
// Number of messages currently shown by the host. Lifted here so the app
|
||||
// scaffold can fold banner visibility into its status-bar inset accounting
|
||||
@@ -52,10 +75,26 @@ object UiMessageBus {
|
||||
text: String,
|
||||
severity: UiMessageSeverity = UiMessageSeverity.Info,
|
||||
ttlMillis: Long = DEFAULT_TTL_MS,
|
||||
key: String? = null,
|
||||
) {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return
|
||||
_events.tryEmit(UiMessage(counter.incrementAndGet(), trimmed, severity, ttlMillis))
|
||||
_events.tryEmit(
|
||||
UiMessageEvent.Show(
|
||||
UiMessage(
|
||||
id = counter.incrementAndGet(),
|
||||
text = trimmed,
|
||||
severity = severity,
|
||||
ttlMillis = ttlMillis.coerceAtLeast(0L),
|
||||
key = key?.trim()?.takeIf(String::isNotEmpty),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Dismiss only the keyed message owned by the matching upstream notice. */
|
||||
fun clear(key: String) {
|
||||
key.trim().takeIf(String::isNotEmpty)?.let { _events.tryEmit(UiMessageEvent.Clear(it)) }
|
||||
}
|
||||
|
||||
/** Neutral confirmation/info (e.g. "Pairing code copied"). */
|
||||
|
||||
+1
-1
@@ -613,7 +613,7 @@ private fun CapabilityRow(
|
||||
|
||||
/**
|
||||
* Advanced compatibility and override content:
|
||||
* - optional direct API fallback URL/key
|
||||
* - optional Direct API URL/key
|
||||
* - explicit direct Relay endpoint override/test
|
||||
* - allow-insecure-connections development toggle
|
||||
*
|
||||
|
||||
+20
-46
@@ -21,9 +21,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
|
||||
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
||||
Gateway("gateway", "⚡ Gateway"),
|
||||
Sessions("sessions", "📡 Sessions"),
|
||||
Completions("completions", "Completions"),
|
||||
Runs("runs", "Runs"),
|
||||
Sessions("sessions", "Direct API"),
|
||||
Completions("completions", "Direct API"),
|
||||
Runs("runs", "Direct API"),
|
||||
Offline("offline", "offline"),
|
||||
}
|
||||
|
||||
@@ -67,18 +67,6 @@ fun resolveChatTransportStatus(
|
||||
detail = "No reachable Hermes chat transport is available.",
|
||||
)
|
||||
|
||||
fun sseFallback(gatewayReason: String): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline(gatewayReason)
|
||||
val tier = preferredAvailableSseTier(serverCapabilities)
|
||||
?: return offline(gatewayReason)
|
||||
return ChatTransportStatus(
|
||||
tier = tier,
|
||||
tone = ChatTransportTone.Fallback,
|
||||
reason = "$gatewayReason → ${tier.plainName()}",
|
||||
detail = "${tier.detailText()} Using this as the fallback while Gateway is unavailable.",
|
||||
)
|
||||
}
|
||||
|
||||
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline()
|
||||
return if (supported) {
|
||||
@@ -94,23 +82,17 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
|
||||
return when (preference) {
|
||||
"auto" -> when {
|
||||
"auto", "gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "auto → Gateway (best)",
|
||||
reason = "Gateway connected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "Gateway selected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
else -> unavailable(
|
||||
ChatTransportTier.Gateway,
|
||||
gatewayFallbackReason(gatewayAvailability),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
||||
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
||||
@@ -119,42 +101,34 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
}
|
||||
|
||||
private fun preferredAvailableSseTier(capabilities: ServerCapabilities): ChatTransportTier? =
|
||||
when {
|
||||
capabilities.sessionsChatStream -> ChatTransportTier.Sessions
|
||||
capabilities.portable -> ChatTransportTier.Completions
|
||||
capabilities.runs -> ChatTransportTier.Runs
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
|
||||
when (availability) {
|
||||
GatewayAvailability.SignInRequired -> "gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "checking gateway"
|
||||
GatewayAvailability.Ready -> "gateway ready"
|
||||
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "Gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "Gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "Checking Gateway"
|
||||
GatewayAvailability.Ready -> "Gateway ready"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.plainName(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway -> "Gateway"
|
||||
ChatTransportTier.Sessions -> "Sessions"
|
||||
ChatTransportTier.Completions -> "Completions"
|
||||
ChatTransportTier.Runs -> "Runs"
|
||||
ChatTransportTier.Sessions -> "Direct API"
|
||||
ChatTransportTier.Completions -> "Direct API"
|
||||
ChatTransportTier.Runs -> "Direct API"
|
||||
ChatTransportTier.Offline -> "offline"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.detailText(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway ->
|
||||
"Gateway uses the dashboard WebSocket /api/ws for live thinking and rich tool events."
|
||||
"Hermes Chat uses the signed-in Dashboard connection."
|
||||
ChatTransportTier.Sessions ->
|
||||
"Sessions uses /api/sessions/{id}/chat/stream with server-side session history."
|
||||
"Direct API compatibility chat with server-side session history."
|
||||
ChatTransportTier.Completions ->
|
||||
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
|
||||
"Direct API compatibility chat."
|
||||
ChatTransportTier.Runs ->
|
||||
"Runs uses /v1/runs plus streamed run events."
|
||||
"Direct API compatibility chat with streamed run events."
|
||||
ChatTransportTier.Offline ->
|
||||
"No chat transport is reachable."
|
||||
}
|
||||
|
||||
@@ -741,6 +741,7 @@ fun AgentInfoSheet(
|
||||
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||
val standardVoiceReady by connectionViewModel.standardVoiceReady.collectAsState()
|
||||
val proactiveEnabled by connectionViewModel.proactiveEnabled.collectAsState()
|
||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||
val allConnections by connectionViewModel.connectionStore.connections.collectAsState()
|
||||
@@ -842,6 +843,7 @@ fun AgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready || standardVoiceReady,
|
||||
relayConnected = relayConnectionState == ConnectionState.Connected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
@@ -3423,6 +3425,8 @@ private fun LegacyAgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready ||
|
||||
connectionViewModel.standardVoiceReady.collectAsState().value,
|
||||
relayConnected = relayConnected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
|
||||
@@ -132,7 +132,7 @@ import java.net.URI
|
||||
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
||||
* the phone can open, probes public `/api/status`, and lets advertised
|
||||
* capabilities select authentication. A separate public sign-in URL is never
|
||||
* universally required. API fallback, Relay pairing, and extra LAN/Tailscale
|
||||
* universally required. Direct API, Relay pairing, and extra LAN/Tailscale
|
||||
* routes remain explicit advanced paths.
|
||||
*
|
||||
* Steps:
|
||||
|
||||
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
|
||||
val label = when (surface) {
|
||||
EndpointSurface.Standard,
|
||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||
EndpointSurface.Api -> "API fallback"
|
||||
EndpointSurface.Api -> "Direct API"
|
||||
EndpointSurface.Relay -> "Relay tools"
|
||||
}
|
||||
val securityVerdict = classifySurfaceSecurity(
|
||||
|
||||
@@ -206,29 +206,49 @@ private fun FailedCard(
|
||||
modifier: Modifier,
|
||||
maxWidth: Dp
|
||||
) {
|
||||
val hostOnly = attachment.errorMessage == ChatViewModel.MEDIA_HOST_ONLY
|
||||
Surface(
|
||||
shape = appearanceRoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
color = if (hostOnly) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = modifier
|
||||
.widthIn(max = maxWidth)
|
||||
.clickable { onRetry() }
|
||||
.then(if (hostOnly) Modifier else Modifier.clickable { onRetry() })
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Text(text = "\u26A0\uFE0F", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = if (hostOnly) "\uD83D\uDCCE" else "\u26A0\uFE0F",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only)
|
||||
} else {
|
||||
attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer
|
||||
},
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.inbound_attach_tap_retry),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only_help)
|
||||
} else {
|
||||
stringResource(R.string.inbound_attach_tap_retry)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -53,7 +54,9 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.UiMessage
|
||||
import com.hermesandroid.relay.ui.UiMessageBus
|
||||
import com.hermesandroid.relay.ui.UiMessageEvent
|
||||
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||
import com.hermesandroid.relay.ui.reduceUiMessages
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val MAX_RETAINED = 6
|
||||
@@ -68,7 +71,8 @@ private const val ROW_MIN_HEIGHT_DP = 34
|
||||
* overlay. Auto-dismisses (paused while expanded) and coalesces duplicates so a
|
||||
* burst of the same status collapses to one refreshed row.
|
||||
*
|
||||
* Errors stay on the snackbar — only post info/success/status here.
|
||||
* App-owned errors stay on the snackbar. Keyed upstream AgentNotices may also
|
||||
* use the warning tone because their sticky/clear lifecycle is server-owned.
|
||||
*/
|
||||
@Composable
|
||||
fun MessageBannerHost(
|
||||
@@ -82,18 +86,19 @@ fun MessageBannerHost(
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
UiMessageBus.events.collect { msg ->
|
||||
// Coalesce identical text so e.g. repeated "Reconnecting…" collapses
|
||||
// to a single, freshly-timed row rather than stacking.
|
||||
shown.filter { it.text == msg.text }.forEach { dup ->
|
||||
shown.remove(dup)
|
||||
expiresAt.remove(dup.id)
|
||||
}
|
||||
shown.add(msg)
|
||||
expiresAt[msg.id] = nowMs() + msg.ttlMillis
|
||||
while (shown.size > MAX_RETAINED) {
|
||||
val dropped = shown.removeAt(0)
|
||||
expiresAt.remove(dropped.id)
|
||||
UiMessageBus.events.collect { event ->
|
||||
val next = reduceUiMessages(shown, event, MAX_RETAINED)
|
||||
val retainedIds = next.mapTo(mutableSetOf()) { it.id }
|
||||
expiresAt.keys.filterNot(retainedIds::contains).forEach { expiresAt.remove(it) }
|
||||
shown.clear()
|
||||
shown.addAll(next)
|
||||
if (event is UiMessageEvent.Show) {
|
||||
val msg = event.message
|
||||
expiresAt[msg.id] = if (msg.ttlMillis == 0L) {
|
||||
Long.MAX_VALUE
|
||||
} else {
|
||||
nowMs() + msg.ttlMillis
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,6 +109,7 @@ fun MessageBannerHost(
|
||||
while (shown.isNotEmpty()) {
|
||||
val now = nowMs()
|
||||
val soonest = shown.minOfOrNull { expiresAt[it.id] ?: Long.MAX_VALUE } ?: break
|
||||
if (soonest == Long.MAX_VALUE) break
|
||||
if (soonest <= now) {
|
||||
shown.filter { (expiresAt[it.id] ?: Long.MAX_VALUE) <= now }.forEach { expired ->
|
||||
shown.remove(expired)
|
||||
@@ -281,6 +287,7 @@ private fun MessageRow(
|
||||
private fun severityContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.58f)
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.74f)
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f)
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.90f)
|
||||
}
|
||||
|
||||
@@ -288,12 +295,14 @@ private fun severityContainer(severity: UiMessageSeverity): Color = when (severi
|
||||
private fun severityOnContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.onTertiaryContainer
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.onErrorContainer
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
|
||||
private fun severityIcon(severity: UiMessageSeverity): ImageVector = when (severity) {
|
||||
UiMessageSeverity.Success -> Icons.Filled.CheckCircle
|
||||
UiMessageSeverity.Status -> Icons.Filled.Sync
|
||||
UiMessageSeverity.Warning -> Icons.Filled.Warning
|
||||
UiMessageSeverity.Info -> Icons.Filled.Info
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
@@ -41,7 +43,7 @@ fun RelayStatusStrip(
|
||||
/** Optional security marker rendered just before the route label. */
|
||||
securityGlyph: (@Composable () -> Unit)? = null,
|
||||
/**
|
||||
* When true, the strip shows an amber "Reconnecting…" cue in place of the
|
||||
* When true, the strip shows an amber "Relay reconnecting" cue in place of the
|
||||
* route label. This is where a **routine** in-progress relay reconnect
|
||||
* surfaces — the top chrome stays empty so chat content never shifts.
|
||||
*/
|
||||
@@ -108,7 +110,7 @@ fun RelayStatusStrip(
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber "· Reconnecting…" cue with a softly pulsing dot. This is the *only*
|
||||
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
|
||||
* surface for a routine in-progress relay reconnect — the top of the app stays
|
||||
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
|
||||
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
||||
@@ -132,7 +134,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
||||
.background(RelayRefresh.Amber),
|
||||
)
|
||||
Text(
|
||||
text = "Reconnecting…",
|
||||
text = stringResource(R.string.settings_relay_reconnecting),
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Amber,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -141,8 +141,8 @@ internal data class SessionCapability(
|
||||
* live. SSE paths only get post-hoc reasoning, so this is gateway-only.
|
||||
* While the gateway is still being probed (Unknown) we surface it as a
|
||||
* "checking" reason rather than a confirmed chip.
|
||||
* - Media / Terminal → require the relay to be CONNECTED (the relay brokers
|
||||
* those channels). A configured-but-disconnected relay is not enough.
|
||||
* - Media → current upstream Dashboard managed-file delivery OR connected
|
||||
* Relay compatibility transport. Terminal remains Relay-owned.
|
||||
* - Voice → `voiceReady` (standard dashboard voice OR relay voice — whichever
|
||||
* the connection actually has).
|
||||
*/
|
||||
@@ -150,6 +150,7 @@ internal data class SessionCapability(
|
||||
internal fun sessionCapabilities(
|
||||
transport: SessionPathTransport,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
upstreamMediaAvailable: Boolean,
|
||||
relayConnected: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
voiceReady: Boolean,
|
||||
@@ -170,11 +171,11 @@ internal fun sessionCapabilities(
|
||||
),
|
||||
SessionCapability(
|
||||
type = "media",
|
||||
available = relayConnected,
|
||||
available = upstreamMediaAvailable || relayConnected,
|
||||
reason = when {
|
||||
relayConnected -> null
|
||||
upstreamMediaAvailable || relayConnected -> null
|
||||
relayConfigured -> stringResource(R.string.session_path_relay_not_connected)
|
||||
else -> stringResource(R.string.session_path_pair_relay_media)
|
||||
else -> stringResource(R.string.session_path_media_not_ready)
|
||||
},
|
||||
),
|
||||
SessionCapability(
|
||||
@@ -401,7 +402,7 @@ internal fun SessionPathDetails(
|
||||
* Vertical "transport path" ladder, basic → best:
|
||||
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
||||
* highlighted; tiers the server doesn't expose render muted; the resolver's
|
||||
* reason ("auto → Gateway (best)" / "gateway unavailable → Sessions") is shown
|
||||
* owner/readiness reason ("Gateway connected" / "Gateway unavailable") is shown
|
||||
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
|
||||
* the drawer and the badge can never disagree.
|
||||
*/
|
||||
|
||||
@@ -706,8 +706,9 @@ fun ChatSettingsScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// Live preview of the exact text that will be sent.
|
||||
// Rebuilds on every toggle change via remember(key1..key5).
|
||||
// Representative preview of each enabled block.
|
||||
// The chat context audit remains the exact selected-
|
||||
// session preview. Rebuilds on every toggle change.
|
||||
val previewText = remember(
|
||||
appContextEnabled,
|
||||
appContextBridgeState,
|
||||
@@ -735,6 +736,14 @@ fun ChatSettingsScreen(
|
||||
destructiveVerbCount = 5,
|
||||
autoDisableMinutes = 15,
|
||||
),
|
||||
// This card is an explanatory fixture, not
|
||||
// the active session audit. Supply one
|
||||
// representative Relay tool so the bridge
|
||||
// and safety toggles remain visible; the
|
||||
// real send path uses the selected
|
||||
// session/profile's authoritative catalog.
|
||||
availableTools =
|
||||
com.hermesandroid.relay.util.PHONE_CONTEXT_PREVIEW_TOOLS,
|
||||
)
|
||||
}
|
||||
Card(
|
||||
@@ -778,7 +787,7 @@ fun ChatSettingsScreen(
|
||||
serverCaps,
|
||||
) {
|
||||
resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = resolvedStreamingEndpoint,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCaps,
|
||||
)
|
||||
|
||||
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
@@ -83,6 +84,7 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -476,12 +478,16 @@ private fun ActiveOverview(
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
)
|
||||
val currentRouteUrl = if (usingApiFallback) {
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
// Observe the binding as well as the saved preference so a restored
|
||||
// conversation immediately presents its actual owner.
|
||||
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
val usingDirectApi = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport,
|
||||
connection = connection,
|
||||
preference = streamingEndpoint,
|
||||
) == SessionTransport.SSE
|
||||
val currentRouteUrl = if (usingDirectApi) {
|
||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||
} else {
|
||||
effectiveDashboardUrl
|
||||
@@ -492,23 +498,29 @@ private fun ActiveOverview(
|
||||
effectiveDashboardUrl = currentRouteUrl,
|
||||
)
|
||||
val routeStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
||||
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
|
||||
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
||||
}
|
||||
val chatStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unreachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
usingDirectApi && !apiReachable && apiHealth != ConnectionViewModel.HealthStatus.Probing ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
|
||||
+22
-7
@@ -62,6 +62,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.data.isDashboardOnlyRoute
|
||||
@@ -386,6 +387,12 @@ private fun ConnectionListCard(
|
||||
} else {
|
||||
connection.resolvedDashboardUrl
|
||||
}
|
||||
val selectedProfile: Profile? = if (activeConnectionViewModel != null) {
|
||||
val profile by activeConnectionViewModel.selectedProfile.collectAsState()
|
||||
profile
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val presentedConnection = activeConnection ?: connection
|
||||
val presentation = resolveGatewayCardPresentation(
|
||||
connection = presentedConnection,
|
||||
@@ -429,13 +436,7 @@ private fun ConnectionListCard(
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(
|
||||
if (presentation.status == GatewayCardStatus.Online) {
|
||||
com.hermesandroid.relay.ui.theme.RelayRefresh.Green
|
||||
} else {
|
||||
MaterialTheme.colorScheme.outline
|
||||
},
|
||||
),
|
||||
.background(gatewayStatusColor(presentation.status)),
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Dns,
|
||||
@@ -484,6 +485,20 @@ private fun ConnectionListCard(
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (isActive) {
|
||||
Text(
|
||||
text = listOfNotNull(
|
||||
stringResource(R.string.conn_info_profile),
|
||||
selectedProfile?.name?.takeIf { it.isNotBlank() }
|
||||
?: stringResource(R.string.settings_server_default),
|
||||
selectedProfile?.model?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onSwitch != null || isSwitching || justSwitched) {
|
||||
OutlinedButton(
|
||||
|
||||
@@ -544,19 +544,24 @@ internal fun buildStatusChecks(
|
||||
)
|
||||
}
|
||||
|
||||
// A healthy standard-only connection should not read like three missing
|
||||
// dependencies. Collapse the absent optional extension to one neutral row;
|
||||
// configured Relay keeps the detailed auth/server/plugin troubleshooting.
|
||||
if (!relayConfigured) {
|
||||
checks += StatusCheck(
|
||||
context.getString(R.string.diag_relay_tools_optional),
|
||||
CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.diag_relay_tools_not_paired),
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
}
|
||||
// 6) Optional Relay / pairing auth.
|
||||
val authLabel = context.getString(R.string.diag_check_pairing_auth)
|
||||
val authRelayActive = context.getString(R.string.diag_check_relay_active)
|
||||
val authPairingProg = context.getString(R.string.diag_check_pairing_progress)
|
||||
val authNotPaired = context.getString(R.string.diag_check_not_paired)
|
||||
val authErr = recentError(DiagnosticCategory.Auth)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.active_section_optional),
|
||||
category = DiagnosticCategory.Auth,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
authState is AuthState.Paired ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Pass,
|
||||
@@ -586,18 +591,11 @@ internal fun buildStatusChecks(
|
||||
|
||||
// 7) Relay server (optional — Unknown when not paired/configured).
|
||||
val relayLabel = context.getString(R.string.active_section_optional_relay)
|
||||
val relayNotConfigured = context.getString(R.string.diag_check_relay_not_configured)
|
||||
val relayConnected = context.getString(R.string.diag_check_connected)
|
||||
val relayReachableNotReady = context.getString(R.string.diag_check_reachable_not_ready)
|
||||
val relayConfiguredNotReachable = context.getString(R.string.diag_check_configured_not_reachable)
|
||||
val relayErr = recentError(DiagnosticCategory.Relay)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Unknown,
|
||||
reason = relayNotConfigured,
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
relayReady ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Pass,
|
||||
@@ -629,7 +627,7 @@ internal fun buildStatusChecks(
|
||||
relayReady = relayReady,
|
||||
relayUpdateInfo = relayUpdateInfo,
|
||||
)
|
||||
checks += when (pluginState) {
|
||||
if (relayConfigured) checks += when (pluginState) {
|
||||
RelayPluginDiagnosticState.NotConfigured ->
|
||||
StatusCheck(
|
||||
pluginLabel, CheckStatus.Unknown,
|
||||
|
||||
@@ -98,7 +98,7 @@ private data class DisplayFile(
|
||||
val deletions: Int?,
|
||||
)
|
||||
|
||||
/** First-class native Git workspace backed by the optional Relay contribution. */
|
||||
/** Native Git workspace: upstream current-session reads plus optional Relay enhancements. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GitStateScreen(
|
||||
@@ -131,7 +131,7 @@ fun GitStateScreen(
|
||||
var pendingConfirm by remember { mutableStateOf<ConfirmationRequest?>(null) }
|
||||
|
||||
LaunchedEffect(scanningEnabled) {
|
||||
if (scanningEnabled) viewModel.loadRepos()
|
||||
viewModel.loadRepos()
|
||||
}
|
||||
|
||||
val repos = (reposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
@@ -202,29 +202,27 @@ fun GitStateScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (scanningEnabled) {
|
||||
IconButton(onClick = { selectedRepo?.let { viewModel.selectRepo(it.id) } ?: viewModel.loadRepos() }) {
|
||||
Icon(Icons.Filled.Refresh, "Refresh Git workspace")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showOverflow = true }) { Icon(Icons.Filled.MoreVert, "More Git actions") }
|
||||
DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {
|
||||
DropdownMenuItem(text = { Text("Choose repository") }, onClick = { showOverflow = false; showRepos = true })
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.git_state_branches)) }, enabled = detail != null, onClick = { showOverflow = false; showBranches = true })
|
||||
}
|
||||
IconButton(onClick = { selectedRepo?.let { viewModel.selectRepo(it.id) } ?: viewModel.loadRepos() }) {
|
||||
Icon(Icons.Filled.Refresh, "Refresh Git workspace")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showOverflow = true }) { Icon(Icons.Filled.MoreVert, "More Git actions") }
|
||||
DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {
|
||||
DropdownMenuItem(text = { Text("Choose repository") }, onClick = { showOverflow = false; showRepos = true })
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.git_state_branches)) }, enabled = detail != null, onClick = { showOverflow = false; showBranches = true })
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (scanningEnabled && detail != null) {
|
||||
if (detail != null) {
|
||||
Surface(shadowElevation = 8.dp, tonalElevation = 2.dp) {
|
||||
Column {
|
||||
if (selection.isNotEmpty()) {
|
||||
SelectionRail(
|
||||
count = selection.size,
|
||||
canWrite = hasGrant,
|
||||
canWrite = hasGrant && scanningEnabled,
|
||||
allStaged = selection.all { it.filter == FileFilter.Staged },
|
||||
onStage = stageSelection,
|
||||
onDiscard = discardSelection,
|
||||
@@ -234,7 +232,7 @@ fun GitStateScreen(
|
||||
OutlinedButton(onClick = { showBranches = true }, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AccountTree, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_branches))
|
||||
}
|
||||
Button(onClick = { showCommit = true }, enabled = hasGrant && detail.status.counts.staged > 0, modifier = Modifier.weight(1f)) {
|
||||
Button(onClick = { showCommit = true }, enabled = scanningEnabled && hasGrant && detail.status.counts.staged > 0, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_commit))
|
||||
}
|
||||
}
|
||||
@@ -248,21 +246,21 @@ fun GitStateScreen(
|
||||
enabled = scanningEnabled,
|
||||
onEnabledChange = onScanningEnabledChange,
|
||||
)
|
||||
if (scanningEnabled) {
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No Git repositories found", "Add a repository to the host's configured Git roots, then refresh.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No current-session Git repository", "Open a Hermes coding session with repository context, or enable host repository discovery above.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
modifier = Modifier.weight(1f),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
relayEnhancementsEnabled = scanningEnabled,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
@@ -289,8 +287,7 @@ fun GitStateScreen(
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,7 +308,7 @@ fun GitStateScreen(
|
||||
onCreate = { name, track -> showBranches = false; viewModel.checkout("", newBranch = name, track = track) },
|
||||
)
|
||||
}
|
||||
if (showCommit && detail != null) {
|
||||
if (showCommit && scanningEnabled && detail != null) {
|
||||
val stagedPaths = detail.status.staged.map { it.path }
|
||||
CommitDialog(
|
||||
hasStaged = stagedPaths.isNotEmpty(),
|
||||
@@ -392,6 +389,7 @@ private fun WorkspaceBody(
|
||||
detailState: GitRepoDetailState,
|
||||
mutation: GitMutationState,
|
||||
stashNotice: String?,
|
||||
relayEnhancementsEnabled: Boolean,
|
||||
hasGrant: Boolean,
|
||||
filter: FileFilter,
|
||||
onFilter: (FileFilter) -> Unit,
|
||||
@@ -421,9 +419,11 @@ private fun WorkspaceBody(
|
||||
LazyColumn(modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 18.dp)) {
|
||||
item {
|
||||
SummaryRail(repo, detailState)
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
if (relayEnhancementsEnabled) {
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
}
|
||||
reposNotice?.let { NoticeCard(it) }
|
||||
if (!hasGrant) WriteGrantNotice()
|
||||
if (relayEnhancementsEnabled && !hasGrant) WriteGrantNotice()
|
||||
MutationBanner(mutation, onClearMutation)
|
||||
stashNotice?.let { NoticeCard(it) }
|
||||
if (status.truncated) NoticeCard(stringResource(R.string.git_state_truncated), error = true)
|
||||
@@ -438,6 +438,7 @@ private fun WorkspaceBody(
|
||||
FileRow(
|
||||
file = file,
|
||||
selected = file in selection,
|
||||
selectionEnabled = relayEnhancementsEnabled,
|
||||
expanded = expandedPath == file.path,
|
||||
mode = contentMode,
|
||||
contentState = contentState,
|
||||
@@ -554,6 +555,7 @@ private fun GitStatus.uniqueChangeCount(): Int = counts.changes.takeIf { it >= 0
|
||||
private fun FileRow(
|
||||
file: DisplayFile,
|
||||
selected: Boolean,
|
||||
selectionEnabled: Boolean,
|
||||
expanded: Boolean,
|
||||
mode: ContentMode,
|
||||
contentState: GitContentViewState,
|
||||
@@ -572,7 +574,7 @@ private fun FileRow(
|
||||
) {
|
||||
Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelected() },
|
||||
onCheckedChange = if (selectionEnabled) ({ _ -> onToggleSelected() }) else null,
|
||||
modifier = Modifier.semantics {
|
||||
contentDescription = "Select ${file.path}"
|
||||
},
|
||||
@@ -602,7 +604,9 @@ private fun FileRow(
|
||||
if (expanded && file.filter != FileFilter.Untracked) {
|
||||
Row(Modifier.padding(start = 56.dp, end = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (file.filter != FileFilter.Untracked) FilterChip(mode == ContentMode.Diff, { onOpen(ContentMode.Diff) }, label = { Text("Diff") })
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
if (selectionEnabled) {
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
}
|
||||
}
|
||||
InlineContent(contentState, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp))
|
||||
}
|
||||
|
||||
@@ -355,7 +355,7 @@ fun SettingsScreen(
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
// The Power tools below all ride the relay plugin. Rather than stamp an
|
||||
// The Relay tools below all ride the optional plugin. Rather than stamp an
|
||||
// identical badge on every card (noise, not signal), the dependency is
|
||||
// surfaced ONCE on the section header as a single plugin-state badge.
|
||||
val pluginBadge = when (relayUiState) {
|
||||
@@ -629,6 +629,14 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc),
|
||||
onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.GraphicEq,
|
||||
title = stringResource(R.string.settings_voice_mode),
|
||||
@@ -637,6 +645,8 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.AutoMirrored.Filled.Message,
|
||||
title = stringResource(R.string.settings_threads),
|
||||
@@ -645,8 +655,6 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Code,
|
||||
title = stringResource(R.string.settings_terminal),
|
||||
@@ -681,13 +689,6 @@ fun SettingsScreen(
|
||||
)
|
||||
// === END PHASE3-notif-listener-followup ===
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc), onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
if (BuildFlavor.isSideload) {
|
||||
// === PHASE3-safety-rails: bridge safety entry-point ===
|
||||
SettingsCategoryRow(
|
||||
|
||||
+863
@@ -0,0 +1,863 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Intent
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Backspace
|
||||
import androidx.compose.material.icons.filled.Dialpad
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthResult
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStore
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthenticator
|
||||
import com.hermesandroid.relay.data.SupervisedParentCredentialType
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentVerifyDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
onDismiss: () -> Unit,
|
||||
onVerified: () -> Unit,
|
||||
onUseRecoveryCode: () -> Unit,
|
||||
) {
|
||||
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
|
||||
var selectedLegacyType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
|
||||
?: selectedLegacyType
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun verify(candidateText: String) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val candidate = candidateText.toCharArray()
|
||||
val result = try {
|
||||
store.verify(candidate)
|
||||
} finally {
|
||||
candidate.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
when (result) {
|
||||
SupervisedParentAuthResult.Success -> onVerified()
|
||||
else -> error = result.toUserMessage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ParentAuthDialogSurface(
|
||||
step = null,
|
||||
onBack = if (storedType == SupervisedParentCredentialType.Legacy && inputType != null) {
|
||||
{ selectedLegacyType = null; error = null }
|
||||
} else {
|
||||
onDismiss
|
||||
},
|
||||
) {
|
||||
when (inputType) {
|
||||
SupervisedParentCredentialType.Pin -> PinEntryScreen(
|
||||
title = "Parent PIN",
|
||||
subtitle = "Enter your 6-digit PIN.",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::verify,
|
||||
onUseRecovery = onUseRecoveryCode,
|
||||
)
|
||||
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onSubmit = ::verify,
|
||||
onUseRecovery = onUseRecoveryCode,
|
||||
)
|
||||
else -> CredentialChoiceScreen(
|
||||
title = "How do you enter your parent credential?",
|
||||
subtitle = "This existing setup predates the PIN/password choice.",
|
||||
onSelected = { selectedLegacyType = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentSetupDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
currentSecretRequired: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onEnrolled: (SupervisedParentEnrollment) -> Unit,
|
||||
) {
|
||||
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
|
||||
var stage by remember(currentSecretRequired) {
|
||||
mutableStateOf(if (currentSecretRequired) SetupStage.VerifyCurrent else SetupStage.Choose)
|
||||
}
|
||||
var legacyInputType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var currentSecret by remember { mutableStateOf("") }
|
||||
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun enroll(newSecretText: String) {
|
||||
val type = credentialType ?: return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val current = currentSecret.toCharArray()
|
||||
val replacement = newSecretText.toCharArray()
|
||||
val result = try {
|
||||
if (currentSecretRequired) store.change(current, replacement, type)
|
||||
else store.enroll(replacement, type)
|
||||
} finally {
|
||||
current.fill('\u0000')
|
||||
replacement.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
result.fold(onSuccess = onEnrolled, onFailure = { error = it.toUserMessage() })
|
||||
}
|
||||
}
|
||||
|
||||
fun verifyCurrent(candidateText: String) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
val candidate = candidateText.toCharArray()
|
||||
val result = try { store.verify(candidate) } finally { candidate.fill('\u0000') }
|
||||
busy = false
|
||||
if (result == SupervisedParentAuthResult.Success) {
|
||||
currentSecret = candidateText
|
||||
error = null
|
||||
stage = SetupStage.Choose
|
||||
} else {
|
||||
error = result.toUserMessage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val backAction: () -> Unit = when (stage) {
|
||||
SetupStage.VerifyCurrent, SetupStage.Choose -> onDismiss
|
||||
SetupStage.Pin, SetupStage.Password -> {
|
||||
{ stage = SetupStage.Choose; credentialType = null; error = null }
|
||||
}
|
||||
}
|
||||
val step = when (stage) {
|
||||
SetupStage.VerifyCurrent -> 1 to 3
|
||||
SetupStage.Choose -> if (currentSecretRequired) 2 to 3 else 1 to 2
|
||||
SetupStage.Pin, SetupStage.Password -> if (currentSecretRequired) 3 to 3 else 2 to 2
|
||||
}
|
||||
|
||||
ParentAuthDialogSurface(step = step, onBack = backAction) {
|
||||
when (stage) {
|
||||
SetupStage.VerifyCurrent -> {
|
||||
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
|
||||
?: legacyInputType
|
||||
when (inputType) {
|
||||
SupervisedParentCredentialType.Pin -> PinEntryScreen(
|
||||
title = "Current parent PIN",
|
||||
subtitle = "Confirm before changing parent access.",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::verifyCurrent,
|
||||
)
|
||||
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
|
||||
title = "Current parent password",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onSubmit = ::verifyCurrent,
|
||||
)
|
||||
else -> CredentialChoiceScreen(
|
||||
title = "How do you enter the current credential?",
|
||||
subtitle = "Choose the input that matches the existing setup.",
|
||||
onSelected = { legacyInputType = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
SetupStage.Choose -> CredentialChoiceScreen(
|
||||
title = if (currentSecretRequired) "Choose new parent access" else "Choose parent access",
|
||||
subtitle = "Pick one way to unlock parent settings. You can change it later.",
|
||||
onSelected = {
|
||||
credentialType = it
|
||||
stage = if (it == SupervisedParentCredentialType.Pin) SetupStage.Pin else SetupStage.Password
|
||||
},
|
||||
)
|
||||
SetupStage.Pin -> PinSetupScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::enroll,
|
||||
)
|
||||
SetupStage.Password -> PasswordSetupScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::enroll,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
onDismiss: () -> Unit,
|
||||
onReset: (SupervisedParentEnrollment) -> Unit,
|
||||
) {
|
||||
var stage by remember { mutableStateOf(RecoveryStage.Phrase) }
|
||||
var recoveryPhrase by remember { mutableStateOf("") }
|
||||
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun reset(newSecretText: String) {
|
||||
val type = credentialType ?: return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val recovery = recoveryPhrase.toCharArray()
|
||||
val replacement = newSecretText.toCharArray()
|
||||
val result = try {
|
||||
store.resetWithRecoveryPhrase(recovery, replacement, type)
|
||||
} finally {
|
||||
recovery.fill('\u0000')
|
||||
replacement.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
result.fold(onSuccess = onReset, onFailure = { error = it.toUserMessage() })
|
||||
}
|
||||
}
|
||||
|
||||
val step = when (stage) {
|
||||
RecoveryStage.Phrase -> 1 to 3
|
||||
RecoveryStage.Choose -> 2 to 3
|
||||
RecoveryStage.Pin, RecoveryStage.Password -> 3 to 3
|
||||
}
|
||||
ParentAuthDialogSurface(
|
||||
step = step,
|
||||
onBack = when (stage) {
|
||||
RecoveryStage.Phrase -> onDismiss
|
||||
RecoveryStage.Choose -> ({ stage = RecoveryStage.Phrase })
|
||||
RecoveryStage.Pin, RecoveryStage.Password -> ({ stage = RecoveryStage.Choose })
|
||||
},
|
||||
) {
|
||||
when (stage) {
|
||||
RecoveryStage.Phrase -> RecoveryPhraseInputScreen(
|
||||
value = recoveryPhrase,
|
||||
error = error,
|
||||
onValueChange = { recoveryPhrase = it; error = null },
|
||||
onContinue = { stage = RecoveryStage.Choose },
|
||||
)
|
||||
RecoveryStage.Choose -> CredentialChoiceScreen(
|
||||
title = "Choose new parent access",
|
||||
subtitle = "Your recovery phrase will be replaced after reset.",
|
||||
onSelected = {
|
||||
credentialType = it
|
||||
stage = if (it == SupervisedParentCredentialType.Pin) RecoveryStage.Pin
|
||||
else RecoveryStage.Password
|
||||
},
|
||||
)
|
||||
RecoveryStage.Pin -> PinSetupScreen(busy = busy, error = error, onComplete = ::reset)
|
||||
RecoveryStage.Password -> PasswordSetupScreen(busy = busy, error = error, onComplete = ::reset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryCodeDialog(
|
||||
enrollment: SupervisedParentEnrollment,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val clipboard = remember(context) {
|
||||
context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
}
|
||||
ParentAuthDialogSurface(step = 3 to 3, onBack = null) {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
enrollment = enrollment,
|
||||
onShare = {
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = "text/plain"
|
||||
putExtra(Intent.EXTRA_TEXT, enrollment.recoveryPhrase)
|
||||
}
|
||||
context.startActivity(Intent.createChooser(intent, "Share recovery phrase"))
|
||||
},
|
||||
onCopy = {
|
||||
clipboard.setPrimaryClip(
|
||||
ClipData.newPlainText("Parent recovery phrase", enrollment.recoveryPhrase),
|
||||
)
|
||||
},
|
||||
onDone = onDone,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ParentAuthDialogSurface(
|
||||
step: Pair<Int, Int>?,
|
||||
onBack: (() -> Unit)?,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(
|
||||
onDismissRequest = { onBack?.invoke() },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
ParentAuthScreenSurface(step = step, onBack = onBack, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ParentAuthScreenSurface(
|
||||
step: Pair<Int, Int>?,
|
||||
onBack: (() -> Unit)?,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.systemBarsPadding()
|
||||
.imePadding()
|
||||
.padding(horizontal = 24.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().height(64.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (onBack != null) {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
} else {
|
||||
Spacer(Modifier.size(48.dp))
|
||||
}
|
||||
step?.let { (current, total) ->
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
repeat(total) { index ->
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(width = 46.dp, height = 4.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (index < current) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"$current of $total",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} ?: Spacer(Modifier.weight(1f))
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.TopCenter,
|
||||
) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun CredentialChoiceScreen(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onSelected: (SupervisedParentCredentialType) -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 28.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, subtitle)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
CredentialChoiceRow(
|
||||
icon = { Icon(Icons.Filled.Dialpad, contentDescription = null) },
|
||||
title = "Use a PIN",
|
||||
subtitle = "Fast on this phone · 6 digits",
|
||||
onClick = { onSelected(SupervisedParentCredentialType.Pin) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
CredentialChoiceRow(
|
||||
icon = { Icon(Icons.Filled.Lock, contentDescription = null) },
|
||||
title = "Use a password",
|
||||
subtitle = "Works with password managers · 8+ characters",
|
||||
onClick = { onSelected(SupervisedParentCredentialType.Password) },
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
"PIN and password are separate choices.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CredentialChoiceRow(
|
||||
icon: @Composable () -> Unit,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 18.dp, vertical = 18.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(48.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) { icon() }
|
||||
}
|
||||
Column(Modifier.weight(1f).padding(horizontal = 16.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Text("›", fontSize = 30.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PinEntryScreen(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
onUseRecovery: (() -> Unit)? = null,
|
||||
) {
|
||||
var pin by remember { mutableStateOf("") }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, subtitle)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PinDots(pin.length)
|
||||
Spacer(Modifier.height(26.dp))
|
||||
NumericKeypad(
|
||||
enabled = !busy,
|
||||
onDigit = { digit ->
|
||||
if (pin.length < 6) {
|
||||
val next = pin + digit
|
||||
pin = next
|
||||
if (next.length == 6) onComplete(next)
|
||||
}
|
||||
},
|
||||
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
|
||||
)
|
||||
AuthError(error)
|
||||
onUseRecovery?.let {
|
||||
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PinSetupScreen(
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
) {
|
||||
var firstPin by remember { mutableStateOf<String?>(null) }
|
||||
var pin by remember(firstPin) { mutableStateOf("") }
|
||||
var localError by remember { mutableStateOf<String?>(null) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(
|
||||
if (firstPin == null) "Create a parent PIN" else "Confirm parent PIN",
|
||||
if (firstPin == null) "Choose a 6-digit PIN." else "Enter the same 6 digits again.",
|
||||
)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PinDots(pin.length)
|
||||
Spacer(Modifier.height(26.dp))
|
||||
NumericKeypad(
|
||||
enabled = !busy,
|
||||
onDigit = { digit ->
|
||||
if (pin.length < 6) {
|
||||
val next = pin + digit
|
||||
pin = next
|
||||
if (next.length == 6) {
|
||||
if (firstPin == null) {
|
||||
firstPin = next
|
||||
} else if (firstPin == next) {
|
||||
onComplete(next)
|
||||
} else {
|
||||
localError = "The PINs do not match. Try again."
|
||||
firstPin = null
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
|
||||
)
|
||||
AuthError(localError ?: error)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NumericKeypad(
|
||||
enabled: Boolean,
|
||||
onDigit: (String) -> Unit,
|
||||
onBackspace: () -> Unit,
|
||||
) {
|
||||
val rows = listOf(listOf("1", "2", "3"), listOf("4", "5", "6"), listOf("7", "8", "9"))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
rows.forEach { row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
row.forEach { digit -> KeypadButton(digit, enabled) { onDigit(digit) } }
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Spacer(Modifier.size(width = 92.dp, height = 58.dp))
|
||||
KeypadButton("0", enabled) { onDigit("0") }
|
||||
Surface(
|
||||
modifier = Modifier.size(width = 92.dp, height = 58.dp).clickable(enabled = enabled, onClick = onBackspace),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.AutoMirrored.Filled.Backspace, contentDescription = "Delete digit")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KeypadButton(label: String, enabled: Boolean, onClick: () -> Unit) {
|
||||
Button(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.size(width = 92.dp, height = 58.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.headlineSmall)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PinDots(count: Int) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
repeat(6) { index ->
|
||||
Box(
|
||||
Modifier
|
||||
.size(22.dp)
|
||||
.clip(CircleShape)
|
||||
.then(
|
||||
if (index < count) Modifier.background(MaterialTheme.colorScheme.primary)
|
||||
else Modifier.border(2.dp, MaterialTheme.colorScheme.outline, CircleShape),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PasswordSetupScreen(
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
) {
|
||||
var password by remember { mutableStateOf("") }
|
||||
var confirmation by remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
var localError by remember { mutableStateOf<String?>(null) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading("Create a parent password", "Use 8 or more characters.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PasswordField("Password", password, { password = it; localError = null }, reveal, { reveal = !reveal })
|
||||
Spacer(Modifier.height(12.dp))
|
||||
PasswordField("Confirm password", confirmation, { confirmation = it; localError = null }, reveal, { reveal = !reveal }, ImeAction.Done)
|
||||
AuthError(localError ?: error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = !busy && password.isNotEmpty() && confirmation.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = {
|
||||
when {
|
||||
password != confirmation -> localError = "The passwords do not match."
|
||||
!SupervisedParentAuthStore.validateNewSecret(
|
||||
password.toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).valid -> localError = "Use a password with at least 8 characters."
|
||||
else -> onComplete(password)
|
||||
}
|
||||
},
|
||||
) { Text(if (busy) "Saving…" else "Continue") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PasswordVerifyScreen(
|
||||
title: String = "Parent password",
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onSubmit: (String) -> Unit,
|
||||
onUseRecovery: (() -> Unit)? = null,
|
||||
) {
|
||||
var password by remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, "Enter your password.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PasswordField("Password", password, { password = it }, reveal, { reveal = !reveal }, ImeAction.Done)
|
||||
AuthError(error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = !busy && password.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = { onSubmit(password) },
|
||||
) { Text(if (busy) "Checking…" else "Unlock") }
|
||||
onUseRecovery?.let {
|
||||
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PasswordField(
|
||||
label: String,
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
reveal: Boolean,
|
||||
onReveal: () -> Unit,
|
||||
imeAction: ImeAction = ImeAction.Next,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = { if (it.length <= 64) onValueChange(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text(label) },
|
||||
visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = onReveal) {
|
||||
Icon(
|
||||
if (reveal) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
|
||||
contentDescription = if (reveal) "Hide password" else "Show password",
|
||||
)
|
||||
}
|
||||
},
|
||||
singleLine = true,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RecoveryPhraseInputScreen(
|
||||
value: String,
|
||||
error: String?,
|
||||
onValueChange: (String) -> Unit,
|
||||
onContinue: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading("Enter recovery phrase", "Paste or type the six words.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("Recovery phrase") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done),
|
||||
minLines = 2,
|
||||
)
|
||||
AuthError(error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = value.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onContinue,
|
||||
) { Text("Continue") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryCodeContent(
|
||||
enrollment: SupervisedParentEnrollment,
|
||||
onShare: () -> Unit = {},
|
||||
onCopy: () -> Unit = {},
|
||||
onDone: () -> Unit = {},
|
||||
) {
|
||||
val words = enrollment.recoveryPhrase.split('-')
|
||||
val displayPhrase = if (words.size == 6) {
|
||||
words.take(3).joinToString("-") + "\n" + words.drop(3).joinToString("-")
|
||||
} else {
|
||||
enrollment.recoveryPhrase
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(
|
||||
"Save your recovery phrase",
|
||||
"This is the only way to reset parent access if you forget it.",
|
||||
)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
SelectionContainer {
|
||||
Text(
|
||||
displayPhrase,
|
||||
modifier = Modifier.padding(20.dp),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
style = MaterialTheme.typography.titleMedium.copy(lineHeight = 28.sp),
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Text(
|
||||
"Send it somewhere parent-only, then delete the message or saved copy from this phone.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onShare,
|
||||
) {
|
||||
Icon(Icons.Filled.Share, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text("Share")
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedButton(
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onCopy,
|
||||
) { Text("Copy phrase") }
|
||||
TextButton(onClick = onDone) { Text("Done") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AuthHeading(title: String, subtitle: String) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AuthError(error: String?) {
|
||||
error?.let {
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
|
||||
private fun SupervisedParentAuthResult.toUserMessage(): String = when (this) {
|
||||
SupervisedParentAuthResult.Success -> ""
|
||||
is SupervisedParentAuthResult.Invalid -> if (attemptsBeforeDelay > 0) {
|
||||
"Incorrect parent credential. $attemptsBeforeDelay attempts remain before a delay."
|
||||
} else {
|
||||
"Incorrect parent credential."
|
||||
}
|
||||
is SupervisedParentAuthResult.Throttled -> {
|
||||
val seconds = ((retryAfterMillis + 999L) / 1_000L).coerceAtLeast(1)
|
||||
"Too many attempts. Try again in $seconds seconds."
|
||||
}
|
||||
SupervisedParentAuthResult.Missing -> "Parent access has not been set up."
|
||||
SupervisedParentAuthResult.Corrupt -> "Parent access data is unavailable. Supervised Mode remains locked."
|
||||
}
|
||||
|
||||
private fun Throwable.toUserMessage(): String = when (this) {
|
||||
is IllegalArgumentException -> message ?: "The new parent credential is not valid."
|
||||
is SupervisedParentAuthStore.ParentAuthenticationException -> authResult.toUserMessage()
|
||||
else -> "Parent access could not be updated. Try again."
|
||||
}
|
||||
|
||||
private enum class SetupStage { VerifyCurrent, Choose, Pin, Password }
|
||||
private enum class RecoveryStage { Phrase, Choose, Pin, Password }
|
||||
+240
-54
@@ -1,8 +1,5 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -52,7 +49,9 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -65,6 +64,9 @@ import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStatus
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStore
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.data.SupervisedSessionActions
|
||||
import com.hermesandroid.relay.data.SupervisedVisibilityPreset
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
|
||||
@@ -77,6 +79,7 @@ import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.gradientBorder
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* The settings surface available while supervised mode is locked.
|
||||
@@ -100,28 +103,29 @@ fun SupervisedSettingsScreen(
|
||||
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
|
||||
val profileAlias by connectionViewModel.profileDisplayAlias.collectAsState()
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
var authError by remember { mutableStateOf<String?>(null) }
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var showAbout by remember { mutableStateOf(false) }
|
||||
|
||||
val credentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
}
|
||||
}
|
||||
|
||||
fun requestParentAccess() {
|
||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val intent = keyguard?.createConfirmDeviceCredentialIntent(
|
||||
"Parent access",
|
||||
"Unlock full Hermes settings and supervised-mode controls. Device credentials verify an enrolled device user, not a distinct parent identity.",
|
||||
)
|
||||
if (intent == null) {
|
||||
authError = "Set a device screen lock before using parent access."
|
||||
} else {
|
||||
credentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
authError = "This legacy supervised policy has no app-specific parent credential and stays locked. " +
|
||||
"Reset this app's local data, reconnect, and configure parent access before enabling Supervised Mode again."
|
||||
}
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
authError = "Parent access data is unavailable. Supervised Mode remains locked."
|
||||
}
|
||||
null -> authError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +190,7 @@ fun SupervisedSettingsScreen(
|
||||
SupervisedNavigationRow(
|
||||
icon = Icons.Filled.Lock,
|
||||
title = "Parent access",
|
||||
subtitle = "Unlock full settings with the device screen lock",
|
||||
subtitle = "Unlock full settings with the app parent PIN or password",
|
||||
onClick = ::requestParentAccess,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
@@ -217,6 +221,38 @@ fun SupervisedSettingsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
else -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Restricted appearance editor backed by the supervised policy, not global theme settings. */
|
||||
@@ -293,42 +329,41 @@ fun SupervisedControlsScreen(
|
||||
onReturnToSupervisedView: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val keyguardManager = remember(context) {
|
||||
context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
val deviceSecure = keyguardManager?.isDeviceSecure == true
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
var showProfilePicker by remember { mutableStateOf(false) }
|
||||
var sessionActionsExpanded by remember { mutableStateOf(false) }
|
||||
var enableAuthError by remember { mutableStateOf<String?>(null) }
|
||||
var enableRequested by remember { mutableStateOf(false) }
|
||||
val enableCredentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
val shouldEnable = enableRequested && mayEnableSupervisedMode(
|
||||
policy = policy,
|
||||
deviceSecure = deviceSecure,
|
||||
deviceCredentialConfirmed = result.resultCode == Activity.RESULT_OK,
|
||||
)
|
||||
enableRequested = false
|
||||
if (shouldEnable) {
|
||||
enableAuthError = null
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
}
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var enableAfterEnrollment by remember { mutableStateOf(false) }
|
||||
var showRemoveCredentialConfirm by remember { mutableStateOf(false) }
|
||||
var removeCredentialBusy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun requestFirstEnable() {
|
||||
val intent = keyguardManager?.createConfirmDeviceCredentialIntent(
|
||||
"Enable supervised mode",
|
||||
"Confirm with an enrolled device credential. This does not verify a distinct parent identity.",
|
||||
)
|
||||
if (!deviceSecure || intent == null) {
|
||||
enableAuthError = "Set a secure device screen lock before enabling supervised mode."
|
||||
if (!policy.isConfigured) {
|
||||
enableAuthError = "Choose an agent profile before enabling Supervised Mode."
|
||||
return
|
||||
}
|
||||
enableRequested = true
|
||||
enableCredentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
enableAfterEnrollment = true
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
}
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
enableAuthError = "Parent access data is unavailable. Reset local app data before enabling Supervised Mode."
|
||||
}
|
||||
null -> enableAuthError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
@@ -360,14 +395,18 @@ fun SupervisedControlsScreen(
|
||||
subtitle = when {
|
||||
policy.pinnedProfileName.isNullOrBlank() ->
|
||||
"Choose an agent profile before enabling"
|
||||
!deviceSecure ->
|
||||
"Set a device screen lock before enabling"
|
||||
parentAuthStatus == SupervisedParentAuthStatus.Missing ->
|
||||
"Set an app-specific parent PIN or password"
|
||||
else ->
|
||||
"Show only the approved Android chat surfaces"
|
||||
},
|
||||
checked = policy.enabled,
|
||||
enabled = policy.enabled ||
|
||||
(!policy.pinnedProfileName.isNullOrBlank() && deviceSecure),
|
||||
(!policy.pinnedProfileName.isNullOrBlank() &&
|
||||
parentAuthStatus in setOf(
|
||||
SupervisedParentAuthStatus.Missing,
|
||||
SupervisedParentAuthStatus.Configured,
|
||||
)),
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled) requestFirstEnable()
|
||||
else onPolicyChange(policy.copy(enabled = false))
|
||||
@@ -404,7 +443,7 @@ fun SupervisedControlsScreen(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"Android device credentials authenticate an enrolled device user; they do not establish a separate parent identity. Use a parent-only device credential or managed-device policy where that distinction matters.",
|
||||
"Parent access uses an app-specific PIN or password, separate from the supervised user's Android screen lock and biometrics.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -713,14 +752,42 @@ fun SupervisedControlsScreen(
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Column(Modifier.padding(start = 12.dp)) {
|
||||
Text("Device authentication", style = MaterialTheme.typography.titleSmall)
|
||||
Text("App parent credential", style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
"Full features require the device screen lock. This verifies an enrolled device user, not a distinct parent identity.",
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> "A parent PIN or password is configured for this app."
|
||||
SupervisedParentAuthStatus.Missing -> "Set a parent PIN or password before enabling Supervised Mode."
|
||||
SupervisedParentAuthStatus.Corrupt -> "Parent access data is unavailable and fails closed."
|
||||
null -> "Loading parent access…"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> OutlinedButton(
|
||||
onClick = {
|
||||
enableAfterEnrollment = false
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
},
|
||||
) { Text("Set parent PIN or password") }
|
||||
SupervisedParentAuthStatus.Configured -> {
|
||||
OutlinedButton(onClick = { parentAuthDialog = ParentAuthDialog.Change }) {
|
||||
Text("Change parent PIN or password")
|
||||
}
|
||||
TextButton(onClick = { parentAuthDialog = ParentAuthDialog.Recovery }) {
|
||||
Text("Reset with recovery phrase")
|
||||
}
|
||||
TextButton(onClick = { showRemoveCredentialConfirm = true }) {
|
||||
Text(
|
||||
"Remove parent credential",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
HorizontalDivider()
|
||||
SupervisedSwitchRow(
|
||||
title = "Relock when the app leaves the screen",
|
||||
@@ -794,6 +861,118 @@ fun SupervisedControlsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showRemoveCredentialConfirm) {
|
||||
RemoveParentCredentialDialog(
|
||||
busy = removeCredentialBusy,
|
||||
onDismiss = { showRemoveCredentialConfirm = false },
|
||||
onConfirm = {
|
||||
removeCredentialBusy = true
|
||||
scope.launch {
|
||||
val result = parentAuthStore.clearCredentialAndDisablePolicies()
|
||||
removeCredentialBusy = false
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
showRemoveCredentialConfirm = false
|
||||
enableAuthError = null
|
||||
onBack()
|
||||
},
|
||||
onFailure = {
|
||||
enableAuthError = "Parent access could not be removed. Try again."
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
enableAuthError = null
|
||||
if (mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Setup -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = false,
|
||||
onDismiss = {
|
||||
parentAuthDialog = null
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Change -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = true,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
null -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
enableAuthError = null
|
||||
if (enableAfterEnrollment && mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun RemoveParentCredentialDialog(
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
title = { Text("Remove parent credential?") },
|
||||
text = {
|
||||
Text(
|
||||
"This disables Supervised Mode on every connection and removes the app-wide " +
|
||||
"PIN or password and recovery phrase. Your supervised settings and toggles are kept. " +
|
||||
"Hermes sessions and server history are not deleted.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = !busy, onClick = onConfirm) {
|
||||
Text(
|
||||
if (busy) "Removing…" else "Remove",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(enabled = !busy, onClick = onDismiss) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -984,6 +1163,13 @@ private fun sessionActionsSummary(actions: SupervisedSessionActions): String = w
|
||||
else -> "${actions.enabledCount} of ${SupervisedSessionActions.TOTAL} allowed"
|
||||
}
|
||||
|
||||
private enum class ParentAuthDialog {
|
||||
Verify,
|
||||
Setup,
|
||||
Change,
|
||||
Recovery,
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SessionActionSwitch(
|
||||
title: String,
|
||||
|
||||
@@ -957,25 +957,6 @@ private fun VoiceForThisProfileCard(
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// Auto-repair when Relay disappears out from under a Relay-only selection:
|
||||
// a persisted RealtimeAgent engine (Relay-only) or Relay route can't run
|
||||
// without a paired Relay, so fall back to the always-available defaults.
|
||||
LaunchedEffect(relayVoiceReady, currentEngine, currentAudioRoute) {
|
||||
if (!relayVoiceReady) {
|
||||
if (currentEngine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefsRepo.setEngineMode(VoiceEngineMode.HermesVoiceOutput)
|
||||
}
|
||||
val coerced = coerceAudioRoute(
|
||||
engine = VoiceEngineMode.HermesVoiceOutput,
|
||||
route = currentAudioRoute,
|
||||
relayVoiceReady = false,
|
||||
)
|
||||
if (coerced != currentAudioRoute) {
|
||||
prefsRepo.setAudioRoute(coerced)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionCard(title = stringResource(R.string.voice_settings_for_profile_title)) {
|
||||
Text(
|
||||
text = stringResource(R.string.voice_settings_engine_label),
|
||||
|
||||
@@ -99,8 +99,14 @@ private const val PREAMBLE =
|
||||
"The user is chatting via the Hermes-Relay Android app. " +
|
||||
"Keep responses mobile-friendly and concise when possible."
|
||||
|
||||
/** Representative capability used only by the Settings preview fixture. */
|
||||
internal val PHONE_CONTEXT_PREVIEW_TOOLS = setOf("android_phone_status")
|
||||
|
||||
/**
|
||||
* Build the system-prompt block from [settings] + [snapshot].
|
||||
* Build the system-prompt block from [settings] + [snapshot]. Relay-only
|
||||
* bridge guidance is emitted only when [availableTools] proves that this exact
|
||||
* selected session/profile can call at least one `android_*` tool. A missing
|
||||
* catalog fails closed for tool claims while preserving neutral mobile context.
|
||||
*
|
||||
* Returns `null` iff:
|
||||
* 1. [AppContextSettings.master] is false, OR
|
||||
@@ -112,14 +118,27 @@ private const val PREAMBLE =
|
||||
* itself is useful (it's the original v0.1.0 behavior). The "everything
|
||||
* off → null" case in the brief is the `master=false` branch.
|
||||
*/
|
||||
fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): String? {
|
||||
fun buildPromptBlock(
|
||||
settings: AppContextSettings,
|
||||
snapshot: PhoneSnapshot,
|
||||
availableTools: Set<String>? = null,
|
||||
): String? {
|
||||
if (!settings.master) return null
|
||||
|
||||
val lines = mutableListOf<String>()
|
||||
lines += PREAMBLE
|
||||
|
||||
if (settings.bridgeState) {
|
||||
lines += buildBridgeLine(snapshot)
|
||||
val phoneControlTools = availableTools
|
||||
?.filterTo(mutableSetOf()) {
|
||||
it.startsWith("android_") && it != "android_setup"
|
||||
}
|
||||
.orEmpty()
|
||||
|
||||
if (settings.bridgeState && phoneControlTools.isNotEmpty()) {
|
||||
lines += buildBridgeLine(
|
||||
snapshot = snapshot,
|
||||
phoneStatusToolAvailable = "android_phone_status" in phoneControlTools,
|
||||
)
|
||||
}
|
||||
|
||||
if (settings.currentApp && snapshot.currentApp != null) {
|
||||
@@ -130,7 +149,7 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
lines += "Battery: ${snapshot.batteryPercent}%."
|
||||
}
|
||||
|
||||
if (settings.safetyStatus) {
|
||||
if (settings.safetyStatus && phoneControlTools.isNotEmpty()) {
|
||||
buildSafetyLine(snapshot)?.let { lines += it }
|
||||
}
|
||||
|
||||
@@ -151,7 +170,10 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
* the bridge isn't bound — "Phone bridge: not installed" is itself useful
|
||||
* context (tells the agent not to try tool calls into the phone).
|
||||
*/
|
||||
private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
private fun buildBridgeLine(
|
||||
snapshot: PhoneSnapshot,
|
||||
phoneStatusToolAvailable: Boolean,
|
||||
): String {
|
||||
if (!snapshot.bridgeBound) {
|
||||
return "Phone bridge: not connected. Tool calls into the phone are unavailable."
|
||||
}
|
||||
@@ -189,8 +211,12 @@ private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
|
||||
val screenText = if (snapshot.screenOn) "Screen: on." else "Screen: off."
|
||||
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText " +
|
||||
"For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
val statusToolHint = if (phoneStatusToolAvailable) {
|
||||
" For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText$statusToolHint"
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,25 +28,26 @@ sealed interface ChatRuntimeStatus {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve chat health in product priority order:
|
||||
* Gateway primary, API/SSE fallback, pending connection, then unavailable.
|
||||
* Resolve chat health for the active conversation owner only. A reachable
|
||||
* sibling endpoint cannot make a signed-out or unreachable conversation look
|
||||
* connected.
|
||||
*/
|
||||
fun resolveChatRuntimeStatus(
|
||||
gateway: ChatTransportReadiness,
|
||||
apiSse: ChatTransportReadiness,
|
||||
): ChatRuntimeStatus = when {
|
||||
gateway == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.Gateway,
|
||||
fallback = false,
|
||||
)
|
||||
|
||||
apiSse == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.ApiSse,
|
||||
fallback = true,
|
||||
)
|
||||
|
||||
gateway == ChatTransportReadiness.Connecting ||
|
||||
apiSse == ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
|
||||
else -> ChatRuntimeStatus.Unavailable
|
||||
owner: ChatTransportPath = ChatTransportPath.Gateway,
|
||||
): ChatRuntimeStatus {
|
||||
val readiness = when (owner) {
|
||||
ChatTransportPath.Gateway -> gateway
|
||||
ChatTransportPath.ApiSse -> apiSse
|
||||
}
|
||||
return when (readiness) {
|
||||
ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = owner,
|
||||
fallback = false,
|
||||
)
|
||||
ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
ChatTransportReadiness.NotConfigured,
|
||||
ChatTransportReadiness.Unavailable -> ChatRuntimeStatus.Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -55,6 +55,8 @@ import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.automaticChatTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.ConnectionSecurity
|
||||
import com.hermesandroid.relay.data.ConnectionStore
|
||||
import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
|
||||
@@ -348,16 +350,16 @@ internal fun resolveChatConnectState(
|
||||
ready: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
chatOwner: SessionTransport = connection?.automaticChatTransport ?: SessionTransport.GATEWAY,
|
||||
): ChatConnectState {
|
||||
if (ready) return ChatConnectState.Ready
|
||||
if (!hydrated) return ChatConnectState.Connecting
|
||||
val active = connection ?: return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = active.capabilities.dashboardGatewayConfigured &&
|
||||
if (connection == null) return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability in setOf(
|
||||
GatewayAvailability.Unknown,
|
||||
GatewayAvailability.SignInRequired,
|
||||
)
|
||||
val apiStillSettling = active.capabilities.apiServerConfigured &&
|
||||
val apiStillSettling = chatOwner == SessionTransport.SSE &&
|
||||
apiHealth in setOf(
|
||||
ConnectionViewModel.HealthStatus.Unknown,
|
||||
ConnectionViewModel.HealthStatus.Probing,
|
||||
@@ -374,9 +376,20 @@ internal fun isChatTransportReady(
|
||||
apiClientPresent: Boolean,
|
||||
apiReachable: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
chatOwner: SessionTransport = SessionTransport.GATEWAY,
|
||||
): Boolean =
|
||||
gatewayAvailability == GatewayAvailability.Ready ||
|
||||
(apiClientPresent && apiReachable)
|
||||
when (chatOwner) {
|
||||
SessionTransport.GATEWAY -> gatewayAvailability == GatewayAvailability.Ready
|
||||
SessionTransport.SSE -> apiClientPresent && apiReachable
|
||||
}
|
||||
|
||||
internal fun resolveActiveChatTransport(
|
||||
boundOwner: SessionTransport?,
|
||||
connection: Connection?,
|
||||
preference: String,
|
||||
): SessionTransport = boundOwner
|
||||
?: connection?.chatTransportForPreference(preference)
|
||||
?: SessionTransport.GATEWAY
|
||||
|
||||
/** Startup transport timeouts are retryable evidence, not an offline verdict. */
|
||||
internal fun isTransientDashboardTransportFailure(error: Throwable?): Boolean =
|
||||
@@ -1325,7 +1338,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
upstreamTransport.dashboardSessionClientFor(cid, url)
|
||||
},
|
||||
streamingEndpointProvider = { streamingEndpoint.value },
|
||||
gatewayAvailabilityProvider = { upstreamTransport.gatewayAvailability.value },
|
||||
automaticTransportProvider = {
|
||||
activeConnection.value?.automaticChatTransport ?: SessionTransport.GATEWAY
|
||||
},
|
||||
setLastSessionId = { _lastSessionId.value = it },
|
||||
legacyDefaultSessionId = {
|
||||
getApplication<Application>().relayDataStore.data.first()[KEY_LAST_SESSION_ID]
|
||||
@@ -1667,10 +1682,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val _chatApiClient = MutableStateFlow<HermesApiClient?>(null)
|
||||
val chatApiClient: StateFlow<HermesApiClient?> = _chatApiClient.asStateFlow()
|
||||
private val _activeConversationTransport = MutableStateFlow<SessionTransport?>(null)
|
||||
val activeConversationTransport: StateFlow<SessionTransport?> =
|
||||
_activeConversationTransport.asStateFlow()
|
||||
private var profileChatApiClient: HermesApiClient? = null
|
||||
private var profileChatApiClientUrl: String? = null
|
||||
private var profileChatApiClientKey: String? = null
|
||||
|
||||
fun setActiveConversationTransport(transport: SessionTransport?) {
|
||||
_activeConversationTransport.value = transport
|
||||
}
|
||||
|
||||
// Chat mode + per-endpoint capability snapshot — owned by
|
||||
// [upstreamTransport]; getters delegate. `rebuildApiClient()` pushes the
|
||||
// freshly-probed snapshot via `setCapabilitiesAndMode`.
|
||||
@@ -1863,16 +1885,24 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return upstreamTransport.dashboardClientFor(connectionId, dashboardUrl).getConfig()
|
||||
}
|
||||
|
||||
// Gateway/Dashboard is the standard path; API remains an optional fallback.
|
||||
private val streamingEndpointPreference: StateFlow<String> =
|
||||
application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
// Readiness follows the active conversation owner, not any reachable sibling route.
|
||||
val chatReady: StateFlow<Boolean> = combine(
|
||||
_chatApiClient,
|
||||
_apiServerReachable,
|
||||
combine(_chatApiClient, _apiServerReachable) { client, reachable -> client to reachable },
|
||||
upstreamTransport.gatewayAvailability,
|
||||
) { client, apiReachable, gateway ->
|
||||
activeConnection,
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (client, apiReachable), gateway, connection, preference, boundOwner ->
|
||||
isChatTransportReady(
|
||||
apiClientPresent = client != null,
|
||||
apiReachable = apiReachable,
|
||||
gatewayAvailability = gateway,
|
||||
chatOwner = resolveActiveChatTransport(boundOwner, connection, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
|
||||
@@ -1892,13 +1922,22 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* before any flow emits — is the neutral state, not the CTA.
|
||||
*/
|
||||
val chatConnectState: StateFlow<ChatConnectState> = combine(
|
||||
connectionStore.isHydrated,
|
||||
activeConnection,
|
||||
chatReady,
|
||||
combine(connectionStore.isHydrated, activeConnection, chatReady) { hydrated, active, ready ->
|
||||
Triple(hydrated, active, ready)
|
||||
},
|
||||
upstreamTransport.gatewayAvailability,
|
||||
_apiServerHealth,
|
||||
) { hydrated, active, ready, gateway, apiHealth ->
|
||||
resolveChatConnectState(hydrated, active, ready, gateway, apiHealth)
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (hydrated, active, ready), gateway, apiHealth, preference, boundOwner ->
|
||||
resolveChatConnectState(
|
||||
hydrated,
|
||||
active,
|
||||
ready,
|
||||
gateway,
|
||||
apiHealth,
|
||||
resolveActiveChatTransport(boundOwner, active, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, ChatConnectState.Connecting)
|
||||
// NOTE: [relayReady] / [voiceReady] are declared below the [_relayUrl]
|
||||
// MutableStateFlow,
|
||||
@@ -2749,9 +2788,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
//
|
||||
// Existing users keep whatever they previously chose. Only fresh installs
|
||||
// (no value persisted yet) get the new "auto" default.
|
||||
val streamingEndpoint: StateFlow<String> = application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
val streamingEndpoint: StateFlow<String> = streamingEndpointPreference
|
||||
|
||||
fun setStreamingEndpoint(endpoint: String) {
|
||||
viewModelScope.launch {
|
||||
@@ -2833,14 +2870,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
upstreamTransport.resolveStreamingEndpoint(preference)
|
||||
upstreamTransport.resolveStreamingEndpoint(
|
||||
preference = preference,
|
||||
gatewayOwned = activeConnection.value
|
||||
?.chatTransportForPreference(preference) == SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [ChatViewModel.sseFallbackEndpoint] for per-turn gateway fallbacks.
|
||||
* [ChatViewModel.sseFallbackEndpoint] only for an API-owned compatibility
|
||||
* binding.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String = upstreamTransport.resolveSseStreamingEndpoint()
|
||||
|
||||
fun resolveActiveStreamingEndpoint(preference: String): String =
|
||||
when (activeConversationTransport.value) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> resolveStreamingEndpoint(preference)
|
||||
.takeUnless { it == "gateway" }
|
||||
?: resolveSseStreamingEndpoint()
|
||||
null -> resolveStreamingEndpoint(preference)
|
||||
}
|
||||
|
||||
// Parse tool annotations from text markers toggle
|
||||
val parseToolAnnotations: StateFlow<Boolean> = application.relayDataStore.data
|
||||
.map { it[KEY_PARSE_TOOL_ANNOTATIONS] ?: false }
|
||||
@@ -3674,11 +3725,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
val dashboardConfigured = activeConnection?.capabilities?.dashboardGatewayConfigured == true
|
||||
val apiConfigured = activeConnection?.capabilities?.apiServerConfigured == true
|
||||
// This helper runs from an eager StateFlow during construction. Read
|
||||
// the earlier-declared backing preference, not its later public alias.
|
||||
val chatOwner = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport.value,
|
||||
connection = activeConnection,
|
||||
preference = streamingEndpointPreference.value,
|
||||
)
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_sign_in_required),
|
||||
@@ -3695,8 +3753,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_not_reachable),
|
||||
@@ -3712,7 +3770,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
return when {
|
||||
apiConfigured &&
|
||||
chatOwner == SessionTransport.SSE &&
|
||||
apiConfigured &&
|
||||
apiHealth == HealthStatus.Unreachable &&
|
||||
gatewayAvailability != GatewayAvailability.Ready -> {
|
||||
// Diagnose, don't just report: for a single-route connection
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -23,6 +24,7 @@ internal data class ConversationBinding(
|
||||
val contextKey: String? = null,
|
||||
val profileName: String? = null,
|
||||
val sessionId: String? = null,
|
||||
val transport: SessionTransport? = null,
|
||||
val displayProfile: Profile? = null,
|
||||
val origin: ConversationBindingOrigin = ConversationBindingOrigin.GlobalSelection,
|
||||
val revision: Long = 0L,
|
||||
@@ -46,6 +48,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
lockedProfileToken: String?,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
if (!profileAllowed(profileName, lockedProfileToken)) return false
|
||||
reduce(
|
||||
@@ -54,6 +57,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
transport = transport,
|
||||
)
|
||||
return true
|
||||
}
|
||||
@@ -63,6 +67,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
) {
|
||||
reduce(
|
||||
contextKey = contextKey,
|
||||
@@ -70,6 +75,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.GlobalSelection,
|
||||
transport = transport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,6 +85,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
val current = _state.value
|
||||
if (
|
||||
@@ -89,7 +96,7 @@ internal class ConversationBindingController {
|
||||
current.sessionId != sessionId
|
||||
)
|
||||
) return false
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile)
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile, transport)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,17 +105,19 @@ internal class ConversationBindingController {
|
||||
if (current.sessionId == sessionId) return
|
||||
_state.value = current.copy(
|
||||
sessionId = sessionId,
|
||||
transport = sessionId?.let(SessionTransport::forSessionId) ?: current.transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
}
|
||||
|
||||
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
|
||||
fun startFreshDraft() {
|
||||
fun startFreshDraft(transport: SessionTransport? = _state.value.transport) {
|
||||
val current = _state.value
|
||||
if (!current.isBound) return
|
||||
if (current.sessionId == null && current.hasExplicitOwner) return
|
||||
_state.value = current.copy(
|
||||
sessionId = null,
|
||||
transport = transport,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
@@ -130,6 +139,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
origin: ConversationBindingOrigin,
|
||||
transport: SessionTransport?,
|
||||
) {
|
||||
val current = _state.value
|
||||
val next = ConversationBinding(
|
||||
@@ -138,6 +148,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = origin,
|
||||
transport = transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
if (current.copy(revision = next.revision) != next) {
|
||||
|
||||
@@ -72,8 +72,9 @@ data class GitTarget(
|
||||
/**
|
||||
* View model for the Git State Android surface (read + write).
|
||||
*
|
||||
* Loads the scanned repo list from the Hermes-Relay plugin and, on selection,
|
||||
* fetches working-tree status + branches. Mutations (stage/unstage/discard/
|
||||
* Loads the active session repository from upstream first and adds repositories
|
||||
* discovered by the Hermes-Relay plugin. On selection it fetches working-tree
|
||||
* status + branches. Mutations (stage/unstage/discard/
|
||||
* commit/fetch/pull/push/checkout) all require the ``plugin.api.write`` grant:
|
||||
* ``configure`` binds one connection/profile/Dashboard owner and every mutation
|
||||
* refuses (surfacing a readable message, never a POST) when that owner's grant
|
||||
@@ -119,12 +120,12 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
private var mutationJob: Job? = null
|
||||
private var messageJob: Job? = null
|
||||
private var scopeKey: String? = null
|
||||
private var sessionRepoPath: String? = null
|
||||
private var targetGeneration: Long = 0
|
||||
|
||||
fun selectedRepoIdForDisplay(): String? = _selectedRepoId.value
|
||||
|
||||
fun currentTarget(): GitTarget? {
|
||||
if (!_scanningEnabled.value) return null
|
||||
val owner = scopeKey ?: return null
|
||||
val repo = _selectedRepoId.value ?: return null
|
||||
return GitTarget(owner, repo, targetGeneration)
|
||||
@@ -143,10 +144,34 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
api = dashboard?.let(::GitStateApiClient)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind standard Git to the active upstream session workspace.
|
||||
*
|
||||
* An exact `git_repo_root` wins; `cwd` is the official Desktop-compatible
|
||||
* fallback. Changing sessions invalidates every selected repository target
|
||||
* before starting a fresh, owner-bound discovery pass.
|
||||
*/
|
||||
fun setSessionWorkspace(repoRoot: String?, workingDirectory: String?) {
|
||||
val next = repoRoot?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: workingDirectory?.trim()?.takeIf { it.isNotBlank() }
|
||||
if (sessionRepoPath == next) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
sessionRepoPath = next
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
// Preserve lazy discovery: the first host scan still starts only when
|
||||
// the Git workspace asks for it. Once visible/loaded, a session switch
|
||||
// refreshes immediately against the new exact workspace.
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
fun setScanningEnabled(enabled: Boolean) {
|
||||
if (_scanningEnabled.value == enabled) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
_scanningEnabled.value = enabled
|
||||
if (!enabled) clearWorkspaceState()
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
/** Grants the plugin.api.write capability for this connection/profile. */
|
||||
@@ -158,7 +183,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
fun hasWriteGrant(): Boolean = _writeGrant.value
|
||||
|
||||
fun loadRepos() {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: run {
|
||||
_repos.value = GitStateUiState.Error("Dashboard connection unavailable")
|
||||
return
|
||||
@@ -167,7 +191,10 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
reposJob?.cancel()
|
||||
reposJob = viewModelScope.launch {
|
||||
_repos.value = GitStateUiState.Loading
|
||||
client.repos().fold(
|
||||
client.repos(
|
||||
sessionRepoPath = sessionRepoPath,
|
||||
includeRelayDiscovery = _scanningEnabled.value,
|
||||
).fold(
|
||||
onSuccess = { list ->
|
||||
if (scopeKey == expectedScope) {
|
||||
_repos.value = GitStateUiState.Ready(list, null)
|
||||
@@ -208,7 +235,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
}
|
||||
|
||||
fun selectRepo(repoId: String) {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: return
|
||||
targetGeneration += 1
|
||||
_selectedRepoId.value = repoId
|
||||
|
||||
+6
-11
@@ -130,8 +130,8 @@ class ProfileController(
|
||||
private val dashboardClientFactory: (connectionId: String, dashboardUrl: String) -> DashboardApiClient,
|
||||
/** Current `streamingEndpoint` preference (for [activeSessionTransport]). */
|
||||
private val streamingEndpointProvider: () -> String,
|
||||
/** Current gateway availability tier (for [activeSessionTransport]). */
|
||||
private val gatewayAvailabilityProvider: () -> GatewayAvailability,
|
||||
/** Stable Auto owner for the active saved connection. */
|
||||
private val automaticTransportProvider: () -> SessionTransport,
|
||||
/** Writes `ConnectionViewModel._lastSessionId`. */
|
||||
private val setLastSessionId: (String?) -> Unit,
|
||||
/** Legacy default (untransported) session id for the server-default profile. */
|
||||
@@ -1517,19 +1517,14 @@ class ProfileController(
|
||||
|
||||
/**
|
||||
* Which transport's session slot to restore right now — or `null` when the
|
||||
* decision is still pending (the gateway probe hasn't landed). A manual
|
||||
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
|
||||
* remains Gateway-owned because the transport resolver also chooses Gateway
|
||||
* until a definitive fallback verdict exists.
|
||||
* decision is still pending. A manual streaming-endpoint override resolves
|
||||
* immediately; under `"auto"`, the saved connection contract owns the
|
||||
* choice, never a transient reachability or authentication verdict.
|
||||
*/
|
||||
fun activeSessionTransport(): SessionTransport? {
|
||||
val preference = streamingEndpointProvider()
|
||||
if (preference != "auto") return SessionTransport.forEndpoint(preference)
|
||||
return when (gatewayAvailabilityProvider()) {
|
||||
GatewayAvailability.Ready -> SessionTransport.GATEWAY
|
||||
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
|
||||
else -> SessionTransport.SSE
|
||||
}
|
||||
return automaticTransportProvider()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -667,17 +667,21 @@ class UpstreamTransportController(
|
||||
* - "sessions" / "completions" / "runs" pass through unchanged (manual override wins).
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
fun resolveStreamingEndpoint(
|
||||
preference: String,
|
||||
gatewayOwned: Boolean,
|
||||
): String =
|
||||
resolveStreamingEndpointPreference(
|
||||
preference = preference,
|
||||
gateway = _gatewayAvailability.value,
|
||||
capabilities = _serverCapabilities.value,
|
||||
gatewayOwned = gatewayOwned,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.sseFallbackEndpoint] for
|
||||
* per-turn gateway fallbacks.
|
||||
* explicit API-owned compatibility conversations.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String =
|
||||
_serverCapabilities.value.preferredChatEndpoint()
|
||||
|
||||
@@ -288,7 +288,7 @@
|
||||
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Informe o endereço do Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e fallback da API são opcionais.</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e API direta são opcionais.</string>
|
||||
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
|
||||
<string name="cw_cloud_agent_name">Endereço do agente</string>
|
||||
@@ -373,7 +373,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 ou http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API do Hermes usada pelo Chat e pelas sessões — a porta 8642 da API e http:// são presumidos para hosts sem esquema (a porta 9119 do painel é determinada separadamente)</string>
|
||||
<string name="cw_scan_message">Procurando o painel/a API do Hermes nesta LAN…</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas no fallback opcional pela API direta.</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas em conexões explícitas pela API direta.</string>
|
||||
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
|
||||
<string name="cw_pair_relay_section_desc">O plugin do Relay já está em execução? Faça o pareamento aqui para ativar Terminal, Bridge e permissões de canais.</string>
|
||||
<string name="cw_pair_relay_url_label">URL do Relay</string>
|
||||
@@ -665,12 +665,12 @@
|
||||
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
|
||||
<string name="settings_hermes_management_desc">Recursos do painel: habilidades, cron, MCP, perfis e modelos</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, fallback da API, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, API direta, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Voz do painel, opções de relay em tempo real e provedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Permita que o agente inicie conversas com você (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas avançadas</string>
|
||||
<string name="settings_threads_desc">Conversas iniciadas pelo Relay e entrega proativa (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas do Relay</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Acesso ao shell do servidor por uma sessão pareada do relay</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -682,7 +682,7 @@
|
||||
<string name="settings_notification_companion">Assistente de notificações</string>
|
||||
<string name="settings_notification_companion_desc">Notificações compartilhadas do celular para ferramentas pareadas do relay</string>
|
||||
<string name="settings_media">Mídia</string>
|
||||
<string name="settings_media_desc">Anexos recebidos pelo Relay, busca automática e limite do cache</string>
|
||||
<string name="settings_media_desc">Anexos do chat, downloads, privacidade e cache</string>
|
||||
<string name="settings_bridge_safety">Segurança do Bridge</string>
|
||||
<string name="settings_bridge_safety_desc">Lista de bloqueio, confirmação de verbos destrutivos e desativação automática</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -775,11 +775,11 @@
|
||||
<string name="chat_settings_debug">Depuração</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostre os marcadores ocultos \"[System: …]\" do servidor (alterações de modelo/personalidade). Desativado corresponde ao desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Endpoint de streaming</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: escolhe o melhor caminho com base no que seu servidor oferece. Em uso no momento: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: conexões padrão usam o Gateway; conexões somente API usam a API direta. Em uso no momento: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamento ao vivo pelo WebSocket do painel)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat por /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat transmitido explicitamente por /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, usa SSE como alternativa em cada turno.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, este chat permanece no Gateway e oferece login ou nova tentativa.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessões: fluxo nativo do Hermes em /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatível com OpenAI por /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use somente quando seu servidor transmitir /v1/runs diretamente.</string>
|
||||
@@ -1162,8 +1162,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Mídia</string>
|
||||
<string name="media_back">Voltar</string>
|
||||
<string name="media_intro_1">Controla como o app lida com arquivos enviados pelos resultados de ferramentas (capturas de tela, PDFs etc.) pelo relay.</string>
|
||||
<string name="media_intro_2">Somente Relay — estas configurações não afetam as imagens que você anexa no chat nem nada em uma conexão padrão (sem Relay).</string>
|
||||
<string name="media_intro_1">Controla como o app baixa, protege e armazena em cache os arquivos enviados pelo Hermes no chat.</string>
|
||||
<string name="media_intro_2">A mídia padrão do Dashboard é priorizada. Quando pareado, o Relay pode acrescentar entrega de compatibilidade e metadados de sensibilidade.</string>
|
||||
<string name="media_max_inbound">Tamanho máximo dos anexos recebidos</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Arquivos maiores que isso são rejeitados após o download.</string>
|
||||
@@ -2080,7 +2080,8 @@
|
||||
<string name="session_path_signin_for_gateway">Entre em Gerenciar para usar o Gateway com pensamento ao vivo.</string>
|
||||
<string name="session_path_gateway_api_server">Disponível no transporte do Gateway — esta sessão transmite pelo servidor API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay pareado, mas desconectado.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o relay para enviar e receber mídia.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o Relay para compatibilidade de mídia em hosts Hermes mais antigos.</string>
|
||||
<string name="session_path_media_not_ready">Atualize o Hermes para entrega de mídia padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="session_path_pair_relay_terminal">Pareie o relay para acessar o terminal.</string>
|
||||
<string name="session_path_voice_not_ready">A voz não está pronta nesta conexão.</string>
|
||||
<string name="session_path_threads_pair_relay">Pareie o relay e ative \"Permitir que o Hermes me envie mensagens\" para o agente poder abrir Threads.</string>
|
||||
@@ -2678,6 +2679,8 @@
|
||||
<string name="inbound_attach_downloading">Baixando…%1$s</string>
|
||||
<string name="inbound_attach_failed">Falha no anexo</string>
|
||||
<string name="inbound_attach_tap_retry">Toque para tentar novamente</string>
|
||||
<string name="inbound_attach_host_only">O arquivo está no seu host Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Atualize o Hermes para downloads padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="inbound_attach_open">Abrir externamente</string>
|
||||
<string name="inbound_attach_share">Compartilhar</string>
|
||||
<string name="inbound_attach_save">Salvar no dispositivo</string>
|
||||
@@ -3151,6 +3154,8 @@
|
||||
<string name="diag_check_ready_with">Pronto com %s</string>
|
||||
<string name="diag_check_relay_active">Relay ativo</string>
|
||||
<string name="diag_check_relay_not_configured">Relay não configurado</string>
|
||||
<string name="diag_relay_tools_optional">Ferramentas do Relay (opcionais)</string>
|
||||
<string name="diag_relay_tools_not_paired">Não pareado</string>
|
||||
<string name="diag_check_relay_server">Verificar servidor relay</string>
|
||||
<string name="diag_check_relay_plugin">Plugin do Relay</string>
|
||||
<string name="diag_plugin_not_configured">O plugin opcional não está configurado</string>
|
||||
@@ -3180,8 +3185,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancelar</string>
|
||||
<string name="inbound_attach_open_failed">Não foi possível abrir o anexo</string>
|
||||
<string name="inbound_attach_share_failed">Não foi possível compartilhar o anexo</string>
|
||||
<string name="injected_context_media_no_relay">A mídia exige uma conexão ativa com o Relay</string>
|
||||
<string name="injected_context_media_relay_active">Relay ativo para mídia</string>
|
||||
<string name="injected_context_media_no_relay">Nenhuma instrução extra de mídia — a entrega padrão continua sob responsabilidade do servidor</string>
|
||||
<string name="injected_context_media_relay_active">Aprimoramento de mídia do Relay disponível</string>
|
||||
<string name="injected_context_media_title">Compartilhamento de mídia</string>
|
||||
<string name="injected_context_persona_not_set">Nenhuma persona definida</string>
|
||||
<string name="injected_context_persona_server_side">Persona no servidor</string>
|
||||
@@ -3339,7 +3344,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Inacessível</string>
|
||||
<string name="active_section_no_fallback_routes">Ainda não há rotas alternativas</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Adicione uma rota de API opcional para chat direto alternativo e troca de rede.</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota alternativa</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota de API direta</string>
|
||||
<string name="active_section_security_authentication">Autenticação</string>
|
||||
<string name="active_section_dashboard_session">Sessão do Dashboard</string>
|
||||
<string name="active_section_credential_storage">Armazenamento de credenciais</string>
|
||||
@@ -3364,7 +3369,7 @@
|
||||
<string name="cw_timeline_authenticated">Autenticação verificada</string>
|
||||
<string name="cw_timeline_ready">Conexão pronta</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage e Voice podem usar este Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">Fallback opcional pela API direta</string>
|
||||
<string name="active_section_optional_api_fallback">API direta opcional</string>
|
||||
<string name="active_section_api_not_required">Não é necessário quando esta conexão usa o Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Onde obtenho essa chave?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY é criada no seu servidor Hermes; este aplicativo não fornece a chave. Configure-a somente ao ativar o servidor de API opcional, que exige uma chave utilizável, e insira aqui o mesmo valor.</string>
|
||||
@@ -4332,7 +4337,7 @@
|
||||
<string name="chat_git_deletions">%1$d exclusões</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d alteração</item><item quantity="other">%1$d alterações</item></plurals>
|
||||
<string name="settings_git_workspace">Espaço de trabalho Git</string>
|
||||
<string name="settings_git_workspace_desc">Revise alterações, branches, commits e remotos</string>
|
||||
<string name="settings_git_workspace_desc">Git da sessão atual primeiro, com descoberta opcional do host</string>
|
||||
<string name="current_chat_activity_title">Atividade atual do chat</string>
|
||||
<string name="current_chat_activity_subtitle">Detalhes ao vivo e somente leitura deste chat</string>
|
||||
<string name="current_chat_activity_open">Visualizar atividade atual do chat</string>
|
||||
@@ -4367,7 +4372,7 @@
|
||||
<string name="agent_activity_child_role_task">Tarefa</string>
|
||||
<string name="agent_activity_child_role_agent">Agente</string>
|
||||
<string name="agent_activity_child_role_system">Sistema</string>
|
||||
<string name="settings_git_workspace_off_desc">Desativado · A verificação de repositórios no host é opcional</string>
|
||||
<string name="settings_git_workspace_off_desc">Somente repositório da sessão · A descoberta do host é opcional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4378,7 +4383,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API direta</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Defina o endereço do Dashboard e do Gateway que este telefone deve usar. Rotas privadas de LAN e Tailscale podem usar HTTP ou HTTPS; rotas públicas exigem HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Endereço do gateway</string>
|
||||
@@ -4395,7 +4400,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. O fallback da API e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. A API direta e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
|
||||
<string name="chat_failure_copy_details">复制详情</string>
|
||||
<string name="chat_failure_route_gateway">网关</string>
|
||||
<string name="chat_failure_route_api">API 回退</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">打开设置</string>
|
||||
<string name="chat_connect_hermes">连接 Hermes</string>
|
||||
<string name="chat_try_demo">体验演示</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 或 http://你的服务器:8642</string>
|
||||
<string name="cw_api_url_supporting">聊天和会话使用的 Hermes API——裸主机名默认使用 API 端口 8642 和 http://(仪表盘的 9119 端口单独推导)</string>
|
||||
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于可选的直接 API 回退。</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
|
||||
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
|
||||
<string name="cw_pair_relay_for">为 %1$s 配对 Relay</string>
|
||||
<string name="cw_pair_relay_scoped_desc">为这个已保存的 Hermes 连接添加可选的 Relay 扩展。这不会添加或替换服务器。</string>
|
||||
@@ -703,12 +703,12 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">仪表盘功能:技能、定时任务、MCP、配置文件、模型</string>
|
||||
<string name="settings_chat">聊天</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、API 回退、工具显示、消息长度</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、Direct API、工具显示、消息长度</string>
|
||||
<string name="settings_voice_mode">语音模式</string>
|
||||
<string name="settings_voice_mode_desc">仪表盘语音、实时 Relay 选项、提供商</string>
|
||||
<string name="settings_threads">话题</string>
|
||||
<string name="settings_threads_desc">允许代理主动与你对话(默认关闭)</string>
|
||||
<string name="settings_power_tools">高级工具</string>
|
||||
<string name="settings_threads_desc">由 Relay 发起的对话和主动推送(默认关闭)</string>
|
||||
<string name="settings_power_tools">Relay 工具</string>
|
||||
<string name="settings_terminal">终端</string>
|
||||
<string name="settings_terminal_desc">通过已配对的 Relay 会话访问服务器 shell</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -720,7 +720,7 @@
|
||||
<string name="settings_notification_companion">通知助手</string>
|
||||
<string name="settings_notification_companion_desc">为已配对的 Relay 工具共享手机通知</string>
|
||||
<string name="settings_media">媒体</string>
|
||||
<string name="settings_media_desc">Relay 入站附件、自动获取、缓存上限</string>
|
||||
<string name="settings_media_desc">聊天附件、下载行为、隐私和缓存</string>
|
||||
<string name="settings_bridge_safety">Bridge 安全</string>
|
||||
<string name="settings_bridge_safety_desc">黑名单、破坏性动词确认、自动禁用</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -814,11 +814,11 @@
|
||||
<string name="chat_settings_debug">调试</string>
|
||||
<string name="chat_settings_show_system_messages_desc">显示服务器隐藏的 \"[System: …]\" 标记(模型/人格更改)。关闭则与桌面/TUI 一致。</string>
|
||||
<string name="chat_settings_streaming_endpoint">流式端点</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:根据服务器暴露的内容选择最佳路径。当前使用:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:标准连接使用网关;仅 API 连接使用直接 API。当前使用:</string>
|
||||
<string name="chat_settings_gateway_suffix">(通过仪表盘 WebSocket 实时思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(通过 /v1/chat/completions 聊天)</string>
|
||||
<string name="chat_settings_runs_suffix">(通过显式流式 /v1/runs 聊天)</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)实时思考+丰富工具事件——桌面应用使用的方式。需要管理登录;不可用时每轮回退到 SSE。</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)提供实时思考和丰富工具事件——桌面应用也使用此路径。需要“管理”登录;不可用时,此聊天仍保留在网关,并提示登录或重试。</string>
|
||||
<string name="chat_settings_sessions_desc">会话:Hermes 原生 /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">聊天:通过 /v1/chat/completions 的 OpenAI 兼容 SSE。</string>
|
||||
<string name="chat_settings_runs_desc">Runs:仅在服务器直接流式传输 /v1/runs 时使用。</string>
|
||||
@@ -1212,8 +1212,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">媒体</string>
|
||||
<string name="media_back">返回</string>
|
||||
<string name="media_intro_1">控制应用如何处理通过 Relay 传来的工具结果文件(截图、PDF 等)。</string>
|
||||
<string name="media_intro_2">仅限 Relay——这些设置不影响你在聊天中附加的图片或标准(无 Relay)连接上的任何内容。</string>
|
||||
<string name="media_intro_1">控制应用如何下载、保护和缓存 Hermes 在聊天中发送的文件。</string>
|
||||
<string name="media_intro_2">优先使用标准 Dashboard 媒体。配对后,Relay 可补充兼容性传输和敏感度元数据。</string>
|
||||
<string name="media_max_inbound">最大入站附件大小</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">超过此大小的文件在下载后被拒绝。</string>
|
||||
@@ -2166,7 +2166,8 @@
|
||||
<string name="session_path_signin_for_gateway">请在管理页面登录以使用实时思考 Gateway。</string>
|
||||
<string name="session_path_gateway_api_server">Gateway 传输可用——此会话通过 API 服务器传输。</string>
|
||||
<string name="session_path_relay_not_connected">Relay 已配对但未连接。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay 以发送和接收媒体。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay,以兼容较旧 Hermes 主机上的媒体。</string>
|
||||
<string name="session_path_media_not_ready">更新 Hermes 以使用标准媒体传输,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="session_path_pair_relay_terminal">配对 Relay 以使用终端。</string>
|
||||
<string name="session_path_voice_not_ready">此连接的语音未就绪。</string>
|
||||
<string name="session_path_threads_pair_relay">配对 Relay 并开启"让 Hermes 联系我",代理才能打开话题。</string>
|
||||
@@ -2791,6 +2792,8 @@
|
||||
<string name="inbound_attach_downloading">正在下载…%1$s</string>
|
||||
<string name="inbound_attach_failed">附件失败</string>
|
||||
<string name="inbound_attach_tap_retry">点击重试</string>
|
||||
<string name="inbound_attach_host_only">文件位于你的 Hermes 主机上</string>
|
||||
<string name="inbound_attach_host_only_help">更新 Hermes 以使用标准下载,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="inbound_attach_open">外部打开</string>
|
||||
<string name="inbound_attach_share">分享</string>
|
||||
<string name="inbound_attach_save">保存到设备</string>
|
||||
@@ -3250,6 +3253,8 @@
|
||||
<string name="diag_check_ready_with">已就绪(%s)</string>
|
||||
<string name="diag_check_relay_active">Relay 活跃</string>
|
||||
<string name="diag_check_relay_not_configured">Relay 未配置</string>
|
||||
<string name="diag_relay_tools_optional">Relay 工具(可选)</string>
|
||||
<string name="diag_relay_tools_not_paired">未配对</string>
|
||||
<string name="diag_check_relay_server">检查 Relay 服务器</string>
|
||||
<string name="diag_check_relay_plugin">Relay 插件</string>
|
||||
<string name="diag_plugin_not_configured">未配置可选插件</string>
|
||||
@@ -3279,8 +3284,8 @@
|
||||
<string name="inbound_attach_cd_cancel">取消</string>
|
||||
<string name="inbound_attach_open_failed">无法打开附件</string>
|
||||
<string name="inbound_attach_share_failed">无法分享附件</string>
|
||||
<string name="injected_context_media_no_relay">媒体需要活跃的 Relay 连接</string>
|
||||
<string name="injected_context_media_relay_active">Relay 已为媒体激活</string>
|
||||
<string name="injected_context_media_no_relay">没有额外媒体指令——标准传输仍由服务器负责</string>
|
||||
<string name="injected_context_media_relay_active">Relay 媒体增强可用</string>
|
||||
<string name="injected_context_media_title">媒体共享</string>
|
||||
<string name="injected_context_persona_not_set">未设置角色</string>
|
||||
<string name="injected_context_persona_server_side">服务端角色</string>
|
||||
@@ -3450,7 +3455,7 @@
|
||||
<string name="active_section_dashboard_unreachable">无法访问</string>
|
||||
<string name="active_section_no_fallback_routes">尚无备用路由</string>
|
||||
<string name="active_section_no_fallback_routes_desc">可添加 API 路由,用于直接聊天回退和网络切换。</string>
|
||||
<string name="active_section_add_api_fallback">添加备用路由</string>
|
||||
<string name="active_section_add_api_fallback">添加 Direct API 路由</string>
|
||||
<string name="active_section_security_authentication">身份验证</string>
|
||||
<string name="active_section_dashboard_session">Dashboard 会话</string>
|
||||
<string name="active_section_credential_storage">凭据存储</string>
|
||||
@@ -3516,7 +3521,7 @@
|
||||
<string name="cw_timeline_authenticated">身份验证已确认</string>
|
||||
<string name="cw_timeline_ready">连接已就绪</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage 和 Voice 可以使用此 Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">可选的直接 API 回退</string>
|
||||
<string name="active_section_optional_api_fallback">可选 Direct API</string>
|
||||
<string name="active_section_api_not_required">此连接使用 Hermes Dashboard 时不需要配置。</string>
|
||||
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
|
||||
@@ -4413,7 +4418,7 @@
|
||||
<string name="chat_git_deletions">删除 %1$d 行</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 个更改</item></plurals>
|
||||
<string name="settings_git_workspace">Git 工作区</string>
|
||||
<string name="settings_git_workspace_desc">查看更改、分支、提交和远程仓库</string>
|
||||
<string name="settings_git_workspace_desc">优先使用当前会话的 Git,可选择发现主机仓库</string>
|
||||
<string name="current_chat_activity_title">当前聊天活动</string>
|
||||
<string name="current_chat_activity_subtitle">此聊天中的只读实时详情</string>
|
||||
<string name="current_chat_activity_open">预览当前聊天活动</string>
|
||||
@@ -4448,7 +4453,7 @@
|
||||
<string name="agent_activity_child_role_task">任务</string>
|
||||
<string name="agent_activity_child_role_agent">代理</string>
|
||||
<string name="agent_activity_child_role_system">系统</string>
|
||||
<string name="settings_git_workspace_off_desc">关闭 · 主机仓库扫描需手动启用</string>
|
||||
<string name="settings_git_workspace_off_desc">仅会话仓库 · 主机发现需手动启用</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4459,7 +4464,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">直接 API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">设置此手机使用的 Dashboard 和 Gateway 地址。私有 LAN 与 Tailscale 路由可使用 HTTP 或 HTTPS;公共路由必须使用 HTTPS。</string>
|
||||
<string name="dashboard_address_editor_title">网关地址</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes hat diesen Fehler gemeldet. Die App wechselt Routen oder Modelle nicht automatisch.</string>
|
||||
<string name="chat_failure_copy_details">Details kopieren</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API-Fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Einstellungen öffnen</string>
|
||||
<string name="chat_connect_hermes">Hermes verbinden</string>
|
||||
<string name="chat_try_demo">Demo ausprobieren</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">Mit deinem gehosteten Agenten verbinden</string>
|
||||
<string name="cw_server_vps_title">Remote-Gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard-Adresse eingeben</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und API-Fallback sind optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und Direct API sind optional.</string>
|
||||
<string name="cw_cloud_entry_title">Mit von Nous gehostetem Hermes verbinden</string>
|
||||
<string name="cw_cloud_entry_description">Gib die im Nous Portal angezeigte Agentenadresse ein. Nach dem Auffinden von Hermes meldest du dich sicher an.</string>
|
||||
<string name="cw_cloud_agent_name">Agentenadresse</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 oder http://dein-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Von Chat und Sitzungen verwendete Hermes-API — bei reinen Hosts werden API-Port 8642 und http:// angenommen (Dashboard-Port 9119 wird separat abgeleitet)</string>
|
||||
<string name="cw_scan_message">Dieses LAN wird nach Hermes-Dashboard/API durchsucht…</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für den optionalen direkten API-Fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für eine explizite Direct-API-Verbindung.</string>
|
||||
<string name="cw_pair_relay_section">Relay koppeln (optional)</string>
|
||||
<string name="cw_pair_relay_for">Relay mit %1$s koppeln</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Füge dieser gespeicherten Hermes-Verbindung die optionale Relay-Erweiterung hinzu. Dadurch wird kein Server hinzugefügt oder ersetzt.</string>
|
||||
@@ -706,12 +706,12 @@
|
||||
<string name="settings_hermes_management">Hermes-Verwaltung</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard-Funktionen: Skills, Cron, MCP, Profile, Modelle</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, API-Fallback, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, Direct API, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_voice_mode">Sprachmodus</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard-Sprache, Echtzeit-Relay-Optionen, Anbieter</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Dem Agenten erlauben, Unterhaltungen mit dir zu beginnen (standardmäßig aus)</string>
|
||||
<string name="settings_power_tools">Profiwerkzeuge</string>
|
||||
<string name="settings_threads_desc">Vom Relay gestartete Unterhaltungen und proaktive Zustellung (standardmäßig aus)</string>
|
||||
<string name="settings_power_tools">Relay-Werkzeuge</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Zugriff auf die Server-Shell über eine gekoppelte Relay-Sitzung</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -723,7 +723,7 @@
|
||||
<string name="settings_notification_companion">Benachrichtigungsassistent</string>
|
||||
<string name="settings_notification_companion_desc">Geteilte Smartphone-Benachrichtigungen für gekoppelte Relay-Werkzeuge</string>
|
||||
<string name="settings_media">Medien</string>
|
||||
<string name="settings_media_desc">Eingehende Relay-Anhänge, automatischer Abruf, Cache-Limit</string>
|
||||
<string name="settings_media_desc">Chat-Anhänge, Downloadverhalten, Datenschutz und Cache</string>
|
||||
<string name="settings_bridge_safety">Bridge-Sicherheit</string>
|
||||
<string name="settings_bridge_safety_desc">Sperrliste, Bestätigung destruktiver Verben, automatische Deaktivierung</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -817,11 +817,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Verborgene \"[System: …]\"-Markierungen des Servers anzeigen (Modell-/Personawechsel). Aus entspricht Desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming-Endpunkt</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: wählt anhand der Serverfunktionen den besten Pfad. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: Standardverbindungen verwenden Gateway; reine API-Verbindungen verwenden Direct API. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (Live-Denken über den Dashboard-WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (Chat über /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (Chat über ausdrücklich gestreamte /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; weicht bei Nichtverfügbarkeit pro Durchlauf auf SSE aus.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; bei Nichtverfügbarkeit bleibt dieser Chat auf Gateway und bietet Anmeldung oder Wiederholen an.</string>
|
||||
<string name="chat_settings_sessions_desc">Sitzungen: Hermes-eigener Endpunkt /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-kompatibles SSE über /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Durchläufe: nur verwenden, wenn dein Server /v1/runs direkt streamt.</string>
|
||||
@@ -1218,8 +1218,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Medien</string>
|
||||
<string name="media_back">Zurück</string>
|
||||
<string name="media_intro_1">Legt fest, wie die App über das Relay gesendete Dateien aus Werkzeugergebnissen (Screenshots, PDFs usw.) behandelt.</string>
|
||||
<string name="media_intro_2">Nur Relay — diese Einstellungen betreffen weder Bilder, die du im Chat anhängst, noch Inhalte einer Standardverbindung ohne Relay.</string>
|
||||
<string name="media_intro_1">Legt fest, wie die App von Hermes im Chat gesendete Dateien herunterlädt, schützt und zwischenspeichert.</string>
|
||||
<string name="media_intro_2">Standardmäßig werden Dashboard-Medien bevorzugt. Wenn Relay gekoppelt ist, kann es Kompatibilitätszustellung und Vertraulichkeitsmetadaten ergänzen.</string>
|
||||
<string name="media_max_inbound">Max. Größe eingehender Anhänge</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Größere Dateien werden nach dem Download abgelehnt.</string>
|
||||
@@ -2172,7 +2172,8 @@
|
||||
<string name="session_path_signin_for_gateway">Melde dich unter Verwalten für das Live-Denken-Gateway an.</string>
|
||||
<string name="session_path_gateway_api_server">Auf dem Gateway-Transport verfügbar — diese Sitzung streamt über den API-Server.</string>
|
||||
<string name="session_path_relay_not_connected">Relay gekoppelt, aber nicht verbunden.</string>
|
||||
<string name="session_path_pair_relay_media">Kopple das Relay, um Medien zu senden und zu empfangen.</string>
|
||||
<string name="session_path_pair_relay_media">Kopple Relay für Medienkompatibilität mit älteren Hermes-Hosts.</string>
|
||||
<string name="session_path_media_not_ready">Aktualisiere Hermes für die standardmäßige Medienzustellung oder kopple Relay für Kompatibilität.</string>
|
||||
<string name="session_path_pair_relay_terminal">Kopple das Relay für Terminalzugriff.</string>
|
||||
<string name="session_path_voice_not_ready">Sprache ist bei dieser Verbindung nicht bereit.</string>
|
||||
<string name="session_path_threads_pair_relay">Kopple das Relay und aktiviere „Hermes darf mir schreiben“, damit der Agent Threads öffnen kann.</string>
|
||||
@@ -2797,6 +2798,8 @@
|
||||
<string name="inbound_attach_downloading">Download läuft…%1$s</string>
|
||||
<string name="inbound_attach_failed">Anhang fehlgeschlagen</string>
|
||||
<string name="inbound_attach_tap_retry">Zum erneuten Versuch tippen</string>
|
||||
<string name="inbound_attach_host_only">Datei befindet sich auf deinem Hermes-Host</string>
|
||||
<string name="inbound_attach_host_only_help">Aktualisiere Hermes für Standarddownloads oder kopple Relay für Kompatibilität.</string>
|
||||
<string name="inbound_attach_open">Extern öffnen</string>
|
||||
<string name="inbound_attach_share">Teilen</string>
|
||||
<string name="inbound_attach_save">Auf Gerät speichern</string>
|
||||
@@ -3319,6 +3322,8 @@
|
||||
<string name="diag_check_ready_with">Bereit mit %s</string>
|
||||
<string name="diag_check_relay_active">Relay aktiv</string>
|
||||
<string name="diag_check_relay_not_configured">Relay nicht konfiguriert</string>
|
||||
<string name="diag_relay_tools_optional">Relay-Werkzeuge (optional)</string>
|
||||
<string name="diag_relay_tools_not_paired">Nicht gekoppelt</string>
|
||||
<string name="diag_check_relay_server">Relay-Server prüfen</string>
|
||||
<string name="diag_check_relay_plugin">Relay-Plugin</string>
|
||||
<string name="diag_plugin_not_configured">Optionales Plugin ist nicht konfiguriert</string>
|
||||
@@ -3348,8 +3353,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Abbrechen</string>
|
||||
<string name="inbound_attach_open_failed">Anhang konnte nicht geöffnet werden</string>
|
||||
<string name="inbound_attach_share_failed">Anhang konnte nicht geteilt werden</string>
|
||||
<string name="injected_context_media_no_relay">Medien erfordern eine aktive Relay-Verbindung</string>
|
||||
<string name="injected_context_media_relay_active">Relay für Medien aktiv</string>
|
||||
<string name="injected_context_media_no_relay">Keine zusätzliche Medienanweisung — die Standardzustellung bleibt Aufgabe des Servers</string>
|
||||
<string name="injected_context_media_relay_active">Relay-Medienerweiterung verfügbar</string>
|
||||
<string name="injected_context_media_title">Medienfreigabe</string>
|
||||
<string name="injected_context_persona_not_set">Keine Persona festgelegt</string>
|
||||
<string name="injected_context_persona_server_side">Serverseitige Persona</string>
|
||||
@@ -3520,7 +3525,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Nicht erreichbar</string>
|
||||
<string name="active_section_no_fallback_routes">Noch keine Ausweichrouten</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Füge optional eine API-Route für direkten Chat-Ausweichbetrieb und Netzwerkwechsel hinzu.</string>
|
||||
<string name="active_section_add_api_fallback">Ausweichroute hinzufügen</string>
|
||||
<string name="active_section_add_api_fallback">Direct-API-Route hinzufügen</string>
|
||||
<string name="active_section_security_authentication">Authentifizierung</string>
|
||||
<string name="active_section_dashboard_session">Dashboard-Sitzung</string>
|
||||
<string name="active_section_credential_storage">Anmeldedatenspeicher</string>
|
||||
@@ -3584,7 +3589,7 @@
|
||||
<string name="cw_timeline_authenticated">Authentifizierung bestätigt</string>
|
||||
<string name="cw_timeline_ready">Verbindung bereit</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage und Voice können dieses Dashboard verwenden</string>
|
||||
<string name="active_section_optional_api_fallback">Optionaler direkter API-Fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optionale Direct API</string>
|
||||
<string name="active_section_api_not_required">Nicht erforderlich, wenn diese Verbindung das Hermes Dashboard verwendet.</string>
|
||||
<string name="active_section_where_api_key">Wo erhalte ich diesen Schlüssel?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY wird auf deinem Hermes-Server erstellt und nicht von dieser App bereitgestellt. Konfiguriere ihn nur für den optionalen API-Server, der einen verwendbaren Schlüssel verlangt, und gib hier denselben Wert ein.</string>
|
||||
@@ -4489,7 +4494,7 @@
|
||||
<string name="chat_git_deletions">%1$d Löschungen</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d Änderung</item><item quantity="other">%1$d Änderungen</item></plurals>
|
||||
<string name="settings_git_workspace">Git-Arbeitsbereich</string>
|
||||
<string name="settings_git_workspace_desc">Änderungen, Branches, Commits und Remotes prüfen</string>
|
||||
<string name="settings_git_workspace_desc">Zuerst Git der aktuellen Sitzung, mit optionaler Host-Erkennung</string>
|
||||
<string name="current_chat_activity_title">Aktuelle Chat-Aktivität</string>
|
||||
<string name="current_chat_activity_subtitle">Schreibgeschützte Live-Details aus diesem Chat</string>
|
||||
<string name="current_chat_activity_open">Aktuelle Chat-Aktivität ansehen</string>
|
||||
@@ -4524,7 +4529,7 @@
|
||||
<string name="agent_activity_child_role_task">Aufgabe</string>
|
||||
<string name="agent_activity_child_role_agent">Agent</string>
|
||||
<string name="agent_activity_child_role_system">System</string>
|
||||
<string name="settings_git_workspace_off_desc">Aus · Repository-Scan auf dem Host ist optional</string>
|
||||
<string name="settings_git_workspace_off_desc">Nur Sitzungs-Repository · Host-Erkennung ist optional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4535,7 +4540,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Lege die Dashboard- und Gateway-Adresse für dieses Telefon fest. Private LAN- und Tailscale-Routen dürfen HTTP oder HTTPS verwenden; öffentliche Routen erfordern HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Gateway-Adresse</string>
|
||||
@@ -4552,7 +4557,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. API-Fallback und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. Direct API und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -637,8 +637,8 @@
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Panel de voz, opciones relay en tiempo real, proveedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Permita que el agente inicie conversaciones con usted (desactivado de forma predeterminada)</string>
|
||||
<string name="settings_power_tools">herramientas eléctricas</string>
|
||||
<string name="settings_threads_desc">Conversaciones iniciadas por Relay y entrega proactiva (desactivado de forma predeterminada)</string>
|
||||
<string name="settings_power_tools">Herramientas de Relay</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Acceso al shell del servidor a través de una sesión relay emparejada</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -650,7 +650,7 @@
|
||||
<string name="settings_notification_companion">Compañero de notificación</string>
|
||||
<string name="settings_notification_companion_desc">Notificaciones telefónicas compartidas para herramientas relay emparejadas</string>
|
||||
<string name="settings_media">Medios de comunicación</string>
|
||||
<string name="settings_media_desc">Relay archivos adjuntos entrantes, búsqueda automática, límite de caché</string>
|
||||
<string name="settings_media_desc">Adjuntos del chat, descargas, privacidad y caché</string>
|
||||
<string name="settings_bridge_safety">seguridad Bridge</string>
|
||||
<string name="settings_bridge_safety_desc">Lista de bloqueo, confirmación de verbo destructivo, desactivación automática</string>
|
||||
<string name="settings_sideload">Carga lateral</string>
|
||||
@@ -742,11 +742,11 @@
|
||||
<string name="chat_settings_debug">Depurar</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostrar los marcadores \" ocultos del servidor [Sistema: …]\" (cambios de modelo / personalidad). Off coincide con el escritorio/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Punto final de transmisión</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: elige la mejor ruta según lo que expone su servidor. Actualmente usando: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: las conexiones estándar usan Gateway; las conexiones solo API usan API directa. En uso: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamiento en vivo a través del tablero WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chatear vía /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chatear a través de /v1/runs transmitido explícitamente)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos en el panel WebSocket (/api/ws): lo que utiliza la aplicación de escritorio. Requiere el inicio de sesión en Administrar; vuelve a SSE por turno cuando no está disponible.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos por el WebSocket del panel (/api/ws), como en la aplicación de escritorio. Requiere iniciar sesión en Administrar; si no está disponible, este chat permanece en Gateway y ofrece iniciar sesión o reintentar.</string>
|
||||
<string name="chat_settings_sessions_desc">Sesiones: Hermes-nativo /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatible con OpenAI a través de /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Ejecuciones: utilícelo solo cuando su servidor transmita /v1/runs directamente.</string>
|
||||
@@ -1119,8 +1119,8 @@
|
||||
<string name="about_credits">Axiom Labs ❤️ Agente Hermes · Nous Research</string>
|
||||
<string name="media_title">Medios de comunicación</string>
|
||||
<string name="media_back">Atrás</string>
|
||||
<string name="media_intro_1">Controla cómo la aplicación maneja los archivos enviados por los resultados de la herramienta (capturas de pantalla, PDF, etc.) a través del relay.</string>
|
||||
<string name="media_intro_2">Solo Relay: esta configuración no afecta a las imágenes que adjunte en el chat ni a nada en una conexión estándar (no-Relay).</string>
|
||||
<string name="media_intro_1">Controla cómo la aplicación descarga, protege y almacena en caché los archivos que Hermes envía en el chat.</string>
|
||||
<string name="media_intro_2">Se priorizan los archivos multimedia del Dashboard estándar. Cuando está emparejado, Relay puede añadir entrega de compatibilidad y metadatos de confidencialidad.</string>
|
||||
<string name="media_max_inbound">Tamaño máximo del archivo adjunto entrante</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Los archivos de mayor tamaño se rechazan después de la descarga.</string>
|
||||
@@ -1989,7 +1989,8 @@
|
||||
<string name="session_path_signin_for_gateway">Inicie sesión en Administrar para el gateway que piensa en vivo.</string>
|
||||
<string name="session_path_gateway_api_server">Disponible en el transporte gateway: esta sesión se transmite a través del servidor API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay emparejado pero no conectado.</string>
|
||||
<string name="session_path_pair_relay_media">Empareje el relay para enviar y recibir medios.</string>
|
||||
<string name="session_path_pair_relay_media">Empareja Relay para obtener compatibilidad multimedia en hosts Hermes antiguos.</string>
|
||||
<string name="session_path_media_not_ready">Actualiza Hermes para la entrega multimedia estándar o empareja Relay por compatibilidad.</string>
|
||||
<string name="session_path_pair_relay_terminal">Empareje el relay para acceder al terminal.</string>
|
||||
<string name="session_path_voice_not_ready">La voz no está lista en esta conexión.</string>
|
||||
<string name="session_path_threads_pair_relay">Empareje el relay y active "Dejar que Hermes me envíe un mensaje" para que el agente pueda abrir Threads.</string>
|
||||
@@ -2556,6 +2557,8 @@
|
||||
<string name="inbound_attach_downloading">Descargando…%1$s</string>
|
||||
<string name="inbound_attach_failed">Error al adjuntar</string>
|
||||
<string name="inbound_attach_tap_retry">Toca para volver a intentarlo</string>
|
||||
<string name="inbound_attach_host_only">El archivo está en tu host de Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Actualiza Hermes para las descargas estándar o empareja Relay por compatibilidad.</string>
|
||||
<string name="inbound_attach_open">Abierto externamente</string>
|
||||
<string name="inbound_attach_share">Compartir</string>
|
||||
<string name="inbound_attach_save">Guardar en dispositivo</string>
|
||||
@@ -2983,6 +2986,8 @@
|
||||
<string name="diag_check_ready_with">Listo con %s</string>
|
||||
<string name="diag_check_relay_active">Relay activo</string>
|
||||
<string name="diag_check_relay_not_configured">Relay no configurado</string>
|
||||
<string name="diag_relay_tools_optional">Herramientas de Relay (opcionales)</string>
|
||||
<string name="diag_relay_tools_not_paired">Sin emparejar</string>
|
||||
<string name="diag_check_relay_server">Verifique el servidor relay</string>
|
||||
<string name="diag_check_relay_plugin">Plugin de Relay</string>
|
||||
<string name="diag_plugin_not_configured">El plugin opcional no está configurado</string>
|
||||
@@ -3012,8 +3017,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancelar</string>
|
||||
<string name="inbound_attach_open_failed">No se pudo abrir el archivo adjunto</string>
|
||||
<string name="inbound_attach_share_failed">No se pudo compartir el archivo adjunto</string>
|
||||
<string name="injected_context_media_no_relay">Los medios requieren una conexión Relay activa</string>
|
||||
<string name="injected_context_media_relay_active">Relay activo para medios</string>
|
||||
<string name="injected_context_media_no_relay">Sin instrucciones multimedia adicionales: la entrega estándar sigue a cargo del servidor</string>
|
||||
<string name="injected_context_media_relay_active">Mejora multimedia de Relay disponible</string>
|
||||
<string name="injected_context_media_title">Compartir medios</string>
|
||||
<string name="injected_context_persona_not_set">No se ha definido ninguna persona</string>
|
||||
<string name="injected_context_persona_server_side">Persona del lado del servidor</string>
|
||||
@@ -4180,7 +4185,7 @@
|
||||
<string name="chat_git_deletions">%1$d eliminaciones</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d cambio</item><item quantity="other">%1$d cambios</item></plurals>
|
||||
<string name="settings_git_workspace">Espacio de Git</string>
|
||||
<string name="settings_git_workspace_desc">Revisa cambios, ramas, commits y remotos</string>
|
||||
<string name="settings_git_workspace_desc">Primero el Git de la sesión actual, con detección opcional del host</string>
|
||||
<string name="current_chat_activity_title">Actividad actual del chat</string>
|
||||
<string name="current_chat_activity_subtitle">Detalles en vivo de solo lectura de este chat</string>
|
||||
<string name="current_chat_activity_open">Ver la actividad actual del chat</string>
|
||||
@@ -4215,7 +4220,7 @@
|
||||
<string name="agent_activity_child_role_task">Tarea</string>
|
||||
<string name="agent_activity_child_role_agent">Agente</string>
|
||||
<string name="agent_activity_child_role_system">Sistema</string>
|
||||
<string name="settings_git_workspace_off_desc">Desactivado · El análisis de repositorios del host es opcional</string>
|
||||
<string name="settings_git_workspace_off_desc">Solo el repositorio de la sesión · La detección del host es opcional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4226,7 +4231,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API directa</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Define la dirección del Dashboard y Gateway que usará este teléfono. Las rutas privadas LAN y Tailscale pueden usar HTTP o HTTPS; las rutas públicas requieren HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Dirección del gateway</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes からこのエラーが報告されました。アプリがルートやモデルを自動的に切り替えることはありません。</string>
|
||||
<string name="chat_failure_copy_details">詳細をコピー</string>
|
||||
<string name="chat_failure_route_gateway">ゲートウェイ</string>
|
||||
<string name="chat_failure_route_api">API フォールバック</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">設定を開く</string>
|
||||
<string name="chat_connect_hermes">Hermesを接続してください</string>
|
||||
<string name="chat_try_demo">デモを試してみる</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">ホスト済みエージェントに接続します</string>
|
||||
<string name="cw_server_vps_title">リモートゲートウェイ</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard アドレスを入力</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と API フォールバックは任意です。</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と Direct API は任意です。</string>
|
||||
<string name="cw_cloud_entry_title">Nous ホスト版 Hermes に接続</string>
|
||||
<string name="cw_cloud_entry_description">Nous Portal に表示されるエージェントのアドレスを入力してください。Hermes が見つかった後、安全にサインインします。</string>
|
||||
<string name="cw_cloud_agent_name">エージェントのアドレス</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 または http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API チャットとセッションで使用されます — API ポート 8642 および http:// はベア ホストとして想定されます (ダッシュボードの 9119 は個別に派生します)</string>
|
||||
<string name="cw_scan_message">この LAN をスキャンして Hermes ダッシュボード/API を探しています…</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは任意の直接 API フォールバックでのみ使います。</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは明示的な Direct API 接続でのみ使います。</string>
|
||||
<string name="cw_pair_relay_section">Relay のペア (オプション)</string>
|
||||
<string name="cw_pair_relay_section_desc">すでに Relay プラグインを実行していますか?ここでペアリングすると、ターミナル、Bridge、およびチャネル許可が有効になります。</string>
|
||||
<string name="cw_pair_relay_url_label">Relay URL</string>
|
||||
@@ -703,12 +703,12 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">ダッシュボードの機能: スキル、cron、MCP、プロファイル、モデル</string>
|
||||
<string name="settings_chat">チャット</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、API フォールバック、ツール表示、メッセージ長</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、Direct API、ツール表示、メッセージ長</string>
|
||||
<string name="settings_voice_mode">ボイスモード</string>
|
||||
<string name="settings_voice_mode_desc">ダッシュボード音声、リアルタイムRelayオプション、プロバイダー</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">エージェントがあなたと会話を開始できるようにします (デフォルトではオフ)</string>
|
||||
<string name="settings_power_tools">パワーツール</string>
|
||||
<string name="settings_threads_desc">Relay が開始する会話とプロアクティブ配信(デフォルトではオフ)</string>
|
||||
<string name="settings_power_tools">Relay ツール</string>
|
||||
<string name="settings_terminal">ターミナル</string>
|
||||
<string name="settings_terminal_desc">ペアリングされたRelayセッションを介したサーバーシェルアクセス</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -720,7 +720,7 @@
|
||||
<string name="settings_notification_companion">通知コンパニオン</string>
|
||||
<string name="settings_notification_companion_desc">ペアリングされたRelayツールの共有電話通知</string>
|
||||
<string name="settings_media">メディア</string>
|
||||
<string name="settings_media_desc">Relay 受信添付ファイル、自動取得、キャッシュキャップ</string>
|
||||
<string name="settings_media_desc">チャットの添付ファイル、ダウンロード動作、プライバシー、キャッシュ</string>
|
||||
<string name="settings_bridge_safety">Bridge 安全性</string>
|
||||
<string name="settings_bridge_safety_desc">ブロックリスト、破壊的な動詞の確認、自動無効化</string>
|
||||
<string name="settings_sideload">サイドロード</string>
|
||||
@@ -814,11 +814,11 @@
|
||||
<string name="chat_settings_debug">デバッグ</string>
|
||||
<string name="chat_settings_show_system_messages_desc">サーバーの非表示の「[システム: …]」マーカーを表示します (モデル/パーソナリティの変更)。 Off はデスクトップ/TUI に一致します。</string>
|
||||
<string name="chat_settings_streaming_endpoint">ストリーミングエンドポイント</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: サーバーが公開しているものに基づいて最適なパスを選択します。現在使用しているもの:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: 標準接続は Gateway、API 専用接続は Direct API を使用します。現在使用中: </string>
|
||||
<string name="chat_settings_gateway_suffix">(ダッシュボード WebSocket を介したライブ思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(/v1/chat/completions 経由でチャット)</string>
|
||||
<string name="chat_settings_runs_suffix">(明示的にストリーミングされた /v1/runs を介してチャットします)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード上のライブ思考 + 豊富なツール イベント WebSocket (/api/ws) — デスクトップ アプリが使用するもの。管理サインインが必要です。利用できない場合はターンごとに SSE に戻ります。</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード WebSocket(/api/ws)経由のライブ思考と豊富なツールイベント — デスクトップアプリと同じ経路です。管理へのサインインが必要です。利用できない場合もこのチャットは Gateway のまま、サインインまたは再試行を案内します。</string>
|
||||
<string name="chat_settings_sessions_desc">セッション: Hermes-native /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">チャット: /v1/chat/completions 経由の OpenAI 互換の SSE。</string>
|
||||
<string name="chat_settings_runs_desc">実行: サーバーが /v1/runs を直接ストリーミングする場合にのみ使用します。</string>
|
||||
@@ -1228,8 +1228,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">メディア</string>
|
||||
<string name="media_back">戻る</string>
|
||||
<string name="media_intro_1">ツールの結果 (スクリーンショット、PDF など) によってRelay経由で送信されたファイルをアプリが処理する方法を制御します。</string>
|
||||
<string name="media_intro_2">Relay のみ — これらの設定は、チャットに添付した画像や標準 (Relay なし) 接続上のものには影響しません。</string>
|
||||
<string name="media_intro_1">Hermes がチャットで送信したファイルのダウンロード、保護、キャッシュ方法を設定します。</string>
|
||||
<string name="media_intro_2">標準の Dashboard メディアが優先されます。Relay をペアリングすると、互換配信と機密性メタデータを追加できます。</string>
|
||||
<string name="media_max_inbound">受信添付ファイルの最大サイズ</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">これより大きいファイルはダウンロード後に拒否されます。</string>
|
||||
@@ -2182,7 +2182,8 @@
|
||||
<string name="session_path_signin_for_gateway">Live Thinking Gateway の [管理] でサインインします。</string>
|
||||
<string name="session_path_gateway_api_server">Gateway トランスポートで利用可能 — このセッションは API サーバー経由でストリーミングされます。</string>
|
||||
<string name="session_path_relay_not_connected">Relay はペアリングされていますが、接続されていません。</string>
|
||||
<string name="session_path_pair_relay_media">Relayをペアリングしてメディアを送受信します。</string>
|
||||
<string name="session_path_pair_relay_media">古い Hermes ホストとのメディア互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="session_path_media_not_ready">標準メディア配信には Hermes を更新するか、互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="session_path_pair_relay_terminal">ターミナルアクセス用にRelayをペアリングします。</string>
|
||||
<string name="session_path_voice_not_ready">この接続では音声の準備ができていません。</string>
|
||||
<string name="session_path_threads_pair_relay">Relayをペアリングし、「Hermes にメッセージを送信する」をオンにすると、エージェントが Threads を開けるようになります。</string>
|
||||
@@ -2805,6 +2806,8 @@
|
||||
<string name="inbound_attach_downloading">ダウンロード中…%1$s</string>
|
||||
<string name="inbound_attach_failed">添付に失敗しました</string>
|
||||
<string name="inbound_attach_tap_retry">タップして再試行してください</string>
|
||||
<string name="inbound_attach_host_only">ファイルは Hermes ホスト上にあります</string>
|
||||
<string name="inbound_attach_host_only_help">標準ダウンロードには Hermes を更新するか、互換性のために Relay をペアリングしてください。</string>
|
||||
<string name="inbound_attach_open">外部に開く</string>
|
||||
<string name="inbound_attach_share">共有</string>
|
||||
<string name="inbound_attach_save">デバイスに保存</string>
|
||||
@@ -3326,6 +3329,8 @@
|
||||
<string name="diag_check_ready_with">%s で準備完了</string>
|
||||
<string name="diag_check_relay_active">Relay アクティブ</string>
|
||||
<string name="diag_check_relay_not_configured">Relay が構成されていません</string>
|
||||
<string name="diag_relay_tools_optional">Relay ツール(オプション)</string>
|
||||
<string name="diag_relay_tools_not_paired">未ペアリング</string>
|
||||
<string name="diag_check_relay_server">中継サーバーを確認する</string>
|
||||
<string name="diag_check_relay_plugin">Relay プラグイン</string>
|
||||
<string name="diag_plugin_not_configured">オプションのプラグインが設定されていません</string>
|
||||
@@ -3355,8 +3360,8 @@
|
||||
<string name="inbound_attach_cd_cancel">キャンセル</string>
|
||||
<string name="inbound_attach_open_failed">添付ファイルを開けませんでした</string>
|
||||
<string name="inbound_attach_share_failed">添付ファイルを共有できませんでした</string>
|
||||
<string name="injected_context_media_no_relay">メディアにはアクティブな Relay 接続が必要です</string>
|
||||
<string name="injected_context_media_relay_active">Relay はメディア向けにアクティブです</string>
|
||||
<string name="injected_context_media_no_relay">追加のメディア指示なし — 標準配信は引き続きサーバーが担当します</string>
|
||||
<string name="injected_context_media_relay_active">Relay メディア拡張を利用できます</string>
|
||||
<string name="injected_context_media_title">メディア共有</string>
|
||||
<string name="injected_context_persona_not_set">ペルソナ設定なし</string>
|
||||
<string name="injected_context_persona_server_side">サーバー側のペルソナ</string>
|
||||
@@ -3514,7 +3519,7 @@
|
||||
<string name="active_section_dashboard_unreachable">接続できません</string>
|
||||
<string name="active_section_no_fallback_routes">フォールバックルートはまだありません</string>
|
||||
<string name="active_section_no_fallback_routes_desc">直接チャットのフォールバックやネットワーク切り替え用に、任意の API ルートを追加できます。</string>
|
||||
<string name="active_section_add_api_fallback">フォールバックルートを追加</string>
|
||||
<string name="active_section_add_api_fallback">Direct API ルートを追加</string>
|
||||
<string name="active_section_security_authentication">認証</string>
|
||||
<string name="active_section_dashboard_session">Dashboard セッション</string>
|
||||
<string name="active_section_credential_storage">認証情報ストレージ</string>
|
||||
@@ -3580,7 +3585,7 @@
|
||||
<string name="cw_timeline_authenticated">認証を確認済み</string>
|
||||
<string name="cw_timeline_ready">接続準備完了</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage、Voice でこの Dashboard を使用できます</string>
|
||||
<string name="active_section_optional_api_fallback">任意の直接 API フォールバック</string>
|
||||
<string name="active_section_optional_api_fallback">任意の Direct API</string>
|
||||
<string name="active_section_api_not_required">この接続が Hermes Dashboard を使用する場合は必要ありません。</string>
|
||||
<string name="active_section_where_api_key">このキーはどこで入手しますか?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY は Hermes サーバー上で作成します。このアプリからは発行されません。任意の API サーバーを有効にする場合のみ設定します。このサーバーには使用可能なキーが必要です。同じ値をここに入力してください。</string>
|
||||
@@ -4484,7 +4489,7 @@
|
||||
<string name="chat_git_deletions">%1$d 件の削除</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 件の変更</item></plurals>
|
||||
<string name="settings_git_workspace">Git ワークスペース</string>
|
||||
<string name="settings_git_workspace_desc">変更、ブランチ、コミット、リモートを確認</string>
|
||||
<string name="settings_git_workspace_desc">現在のセッションの Git を優先し、必要に応じてホストを検出</string>
|
||||
<string name="current_chat_activity_title">現在のチャットのアクティビティ</string>
|
||||
<string name="current_chat_activity_subtitle">このチャットからの読み取り専用ライブ詳細</string>
|
||||
<string name="current_chat_activity_open">現在のチャットのアクティビティを表示</string>
|
||||
@@ -4519,7 +4524,7 @@
|
||||
<string name="agent_activity_child_role_task">タスク</string>
|
||||
<string name="agent_activity_child_role_agent">エージェント</string>
|
||||
<string name="agent_activity_child_role_system">システム</string>
|
||||
<string name="settings_git_workspace_off_desc">オフ · ホストのリポジトリスキャンはオプトインです</string>
|
||||
<string name="settings_git_workspace_off_desc">セッションのリポジトリのみ · ホスト検出はオプトインです</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4530,7 +4535,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">この端末で使う Dashboard と Gateway のアドレスを設定します。プライベート LAN と Tailscale ルートは HTTP または HTTPS を使用でき、公開ルートには HTTPS が必要です。</string>
|
||||
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
|
||||
@@ -4547,7 +4552,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。API フォールバックと Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。Direct API と Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -292,7 +292,7 @@
|
||||
<string name="cw_cloud_subtitle">Подключитесь к своему размещённому агенту</string>
|
||||
<string name="cw_server_vps_title">Удалённый шлюз</string>
|
||||
<string name="cw_server_vps_subtitle">Введите адрес Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и резервный API необязательны.</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и Direct API необязательны.</string>
|
||||
<string name="cw_cloud_entry_title">Подключиться к Hermes на хостинге Nous</string>
|
||||
<string name="cw_cloud_entry_description">Введите адрес агента, указанный в Nous Portal. После обнаружения Hermes вы безопасно войдёте в систему.</string>
|
||||
<string name="cw_cloud_agent_name">Адрес агента</string>
|
||||
@@ -392,7 +392,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 или http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API Гермеса, используемый Чатом и сеансами — порт API 8642 и http:// предполагаются для голых хостов (порт 9119 панели управления выводится отдельно)</string>
|
||||
<string name="cw_scan_message">Сканирование этой локальной сети на предмет панели управления/API Гермеса…</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для необязательного резервного копирования прямого API.</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для явно настроенного Direct API.</string>
|
||||
<string name="cw_pair_relay_section">Сопряжение Relay (необязательно)</string>
|
||||
<string name="cw_pair_relay_for">Сопряжение Relay с %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Добавьте необязательное расширение Relay к этому сохранённому подключению Гермеса. Это не добавляет и не заменяет сервер.</string>
|
||||
@@ -682,12 +682,12 @@
|
||||
<string name="settings_hermes_management">Управление Гермесом</string>
|
||||
<string name="settings_hermes_management_desc">Функции панели управления: навыки, cron, MCP, профили, модели</string>
|
||||
<string name="settings_chat">Чат</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, резервный API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, Direct API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_voice_mode">Режим голоса</string>
|
||||
<string name="settings_voice_mode_desc">Голос панели управления, опции Relay в реальном времени, поставщики</string>
|
||||
<string name="settings_threads">Потоки</string>
|
||||
<string name="settings_threads_desc">Позволяет агенту начинать разговоры с вами (по умолчанию выключено)</string>
|
||||
<string name="settings_power_tools">Мощные инструменты</string>
|
||||
<string name="settings_threads_desc">Разговоры, начатые Relay, и проактивная доставка (по умолчанию выключено)</string>
|
||||
<string name="settings_power_tools">Инструменты Relay</string>
|
||||
<string name="settings_terminal">Терминал</string>
|
||||
<string name="settings_terminal_desc">Доступ к оболочке сервера через сопряженный сеанс Relay</string>
|
||||
<string name="settings_bridge">Мост</string>
|
||||
@@ -699,7 +699,7 @@
|
||||
<string name="settings_notification_companion">Сопровождение уведомлений</string>
|
||||
<string name="settings_notification_companion_desc">Общие уведомления телефона для сопряженных инструментов Relay</string>
|
||||
<string name="settings_media">Медиа</string>
|
||||
<string name="settings_media_desc">Передача входящих вложений, автозагрузка, кэш</string>
|
||||
<string name="settings_media_desc">Вложения чата, загрузка, конфиденциальность и кэш</string>
|
||||
<string name="settings_bridge_safety">Безопасность моста</string>
|
||||
<string name="settings_bridge_safety_desc">Черный список, подтверждение деструктивных действий, автоотключение</string>
|
||||
<string name="settings_sideload">Установка из APK</string>
|
||||
@@ -791,11 +791,11 @@
|
||||
<string name="chat_settings_debug">Отладка</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Показывать скрытые сервером маркеры \"[Система: …]\" (изменения модели / личности). Выключено соответствует рабочему столу/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Потоковая конечная точка</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: выбирает лучший путь на основе того, что ваш сервер предоставляет. В настоящее время используется:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: стандартные подключения используют Gateway; подключения только к API используют Direct API. Сейчас используется: </string>
|
||||
<string name="chat_settings_gateway_suffix">(живое мышление через WebSocket панели управления)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(чат через /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix">(чат через явно потоковые /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Шлюз: живое мышление + богатые события инструментов через WebSocket панели управления (/api/ws) — что использует настольное приложение. Требует входа в систему Manage; возвращается к SSE на каждый ход, когда недоступен.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: живое мышление и расширенные события инструментов через WebSocket панели управления (/api/ws), как в настольном приложении. Требует входа в Manage; если Gateway недоступен, чат остается на нем и предлагает войти или повторить попытку.</string>
|
||||
<string name="chat_settings_sessions_desc">Сессии: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Чат: совместимый с OpenAI SSE через /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Запуски: используйте только когда ваш сервер напрямую потоковые /v1/runs.</string>
|
||||
@@ -927,7 +927,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Недоступно</string>
|
||||
<string name="active_section_no_fallback_routes">Нет резервных маршрутов</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Добавьте локальный адрес, Tailscale или публичный адрес, чтобы сохранить это соединение доступным при изменении сетей.</string>
|
||||
<string name="active_section_add_api_fallback">Добавить резервный маршрут</string>
|
||||
<string name="active_section_add_api_fallback">Добавить маршрут Direct API</string>
|
||||
<string name="active_section_security_authentication">Аутентификация</string>
|
||||
<string name="active_section_dashboard_session">Сессия панели управления</string>
|
||||
<string name="active_section_credential_storage">Хранение учетных данных</string>
|
||||
@@ -942,7 +942,7 @@
|
||||
<string name="active_section_route_selection">Выбор маршрута</string>
|
||||
<string name="active_section_automatic">Автоматически</string>
|
||||
<string name="active_section_api_access">Доступ к API</string>
|
||||
<string name="active_section_optional_api_fallback">Дополнительный прямой резерв API</string>
|
||||
<string name="active_section_optional_api_fallback">Необязательный Direct API</string>
|
||||
<string name="active_section_api_not_required">Не требуется, если это соединение использует панель управления Гермесом.</string>
|
||||
<string name="active_section_where_api_key">Где взять это?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY создается на вашем сервере Гермеса; он не предоставляется этим приложением. Настройте его только при включении дополнительного сервера API, который требует рабочего ключа, затем введите то же значение здесь.</string>
|
||||
@@ -1233,8 +1233,8 @@
|
||||
<string name="about_credits">Axiom Labs ❤️ Агент Гермес · Nous Research</string>
|
||||
<string name="media_title">Медиа</string>
|
||||
<string name="media_back">Назад</string>
|
||||
<string name="media_intro_1">Управляет тем, как приложение обрабатывает файлы, отправленные результатами инструментов (скриншоты, PDF и т. д.) через Relay.</string>
|
||||
<string name="media_intro_2">Только Relay — эти настройки не влияют на изображения, которые вы прикрепляете в чате, или что-либо на стандартном (без Relay) соединении.</string>
|
||||
<string name="media_intro_1">Определяет, как приложение скачивает, защищает и кэширует файлы, отправленные Hermes в чате.</string>
|
||||
<string name="media_intro_2">Предпочтение отдаётся стандартным медиа Dashboard. После сопряжения Relay может добавить совместимую доставку и метаданные конфиденциальности.</string>
|
||||
<string name="media_max_inbound">Максимальный размер входящего вложения</string>
|
||||
<string name="media_max_inbound_value">%1$d МБ</string>
|
||||
<string name="media_max_inbound_desc">Файлы, превышающие этот размер, отклоняются после загрузки.</string>
|
||||
@@ -2185,7 +2185,8 @@
|
||||
<string name="session_path_signin_for_gateway">Войдите в систему под управлением для шлюза живого мышления.</string>
|
||||
<string name="session_path_gateway_api_server">Доступно на транспортном шлюзе — этот сеанс передается через сервер API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay сопряжён, но не подключен.</string>
|
||||
<string name="session_path_pair_relay_media">Сопрягите Relay для отправки и получения медиа.</string>
|
||||
<string name="session_path_pair_relay_media">Сопрягите Relay для совместимости медиа со старыми хостами Hermes.</string>
|
||||
<string name="session_path_media_not_ready">Обновите Hermes для стандартной доставки медиа или сопрягите Relay для совместимости.</string>
|
||||
<string name="session_path_pair_relay_terminal">Сопрягите Relay для доступа к терминалу.</string>
|
||||
<string name="session_path_voice_not_ready">Голос не готов на этом подключении.</string>
|
||||
<string name="session_path_threads_pair_relay">Сопрягите Relay и включите "Позволить Гермесу отправлять мне сообщения", чтобы агент мог открывать потоки.</string>
|
||||
@@ -2782,6 +2783,8 @@
|
||||
<string name="inbound_attach_downloading">Скачивание\&#8230;%1$s</string>
|
||||
<string name="inbound_attach_failed">Ошибка вложения</string>
|
||||
<string name="inbound_attach_tap_retry">Нажмите для повторной попытки</string>
|
||||
<string name="inbound_attach_host_only">Файл находится на вашем хосте Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Обновите Hermes для стандартных загрузок или сопрягите Relay для совместимости.</string>
|
||||
<string name="inbound_attach_open">Открыть внешне</string>
|
||||
<string name="inbound_attach_share">Поделиться</string>
|
||||
<string name="inbound_attach_save">Сохранить на устройство</string>
|
||||
@@ -3187,6 +3190,8 @@
|
||||
<string name="diag_check_ready_with">Готово с %s</string>
|
||||
<string name="diag_check_relay_active">Relay активен</string>
|
||||
<string name="diag_check_relay_not_configured">Relay не настроен</string>
|
||||
<string name="diag_relay_tools_optional">Инструменты Relay (необязательно)</string>
|
||||
<string name="diag_relay_tools_not_paired">Не сопряжено</string>
|
||||
<string name="diag_check_relay_server">Проверить сервер Relay</string>
|
||||
<string name="diag_check_relay_plugin">Плагин Relay</string>
|
||||
<string name="diag_plugin_not_configured">Дополнительный плагин не настроен</string>
|
||||
@@ -3218,8 +3223,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Отмена</string>
|
||||
<string name="inbound_attach_open_failed">Не удалось открыть вложение</string>
|
||||
<string name="inbound_attach_share_failed">Не удалось поделиться вложением</string>
|
||||
<string name="injected_context_media_no_relay">Для мультимедиа требуется активное подключение Relay</string>
|
||||
<string name="injected_context_media_relay_active">плагин Relay активен для мультимедиа</string>
|
||||
<string name="injected_context_media_no_relay">Нет дополнительных инструкций для медиа — стандартная доставка остаётся на стороне сервера</string>
|
||||
<string name="injected_context_media_relay_active">Доступно расширение Relay для медиа</string>
|
||||
<string name="injected_context_media_title">Обмен мультимедиа</string>
|
||||
<string name="injected_context_persona_not_set">Персона не установлена</string>
|
||||
<string name="injected_context_persona_server_side">Персона на стороне сервера</string>
|
||||
@@ -4228,7 +4233,7 @@
|
||||
<string name="chat_git_deletions">Удалено строк: %1$d</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d изменение</item><item quantity="few">%1$d изменения</item><item quantity="many">%1$d изменений</item><item quantity="other">%1$d изменения</item></plurals>
|
||||
<string name="settings_git_workspace">Рабочая область Git</string>
|
||||
<string name="settings_git_workspace_desc">Изменения, ветки, коммиты и удалённые репозитории</string>
|
||||
<string name="settings_git_workspace_desc">Сначала Git текущего сеанса, с дополнительным обнаружением на хосте</string>
|
||||
<string name="current_chat_activity_title">Текущая активность чата</string>
|
||||
<string name="current_chat_activity_subtitle">Доступные только для чтения сведения в реальном времени из этого чата</string>
|
||||
<string name="current_chat_activity_open">Просмотреть текущую активность чата</string>
|
||||
@@ -4263,7 +4268,7 @@
|
||||
<string name="agent_activity_child_role_task">Задача</string>
|
||||
<string name="agent_activity_child_role_agent">Агент</string>
|
||||
<string name="agent_activity_child_role_system">Система</string>
|
||||
<string name="settings_git_workspace_off_desc">Выкл. · Сканирование репозиториев на хосте включается вручную</string>
|
||||
<string name="settings_git_workspace_off_desc">Только репозиторий сеанса · Обнаружение на хосте включается вручную</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4274,7 +4279,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Укажите адрес Dashboard и Gateway для этого телефона. Частные маршруты LAN и Tailscale могут использовать HTTP или HTTPS; публичным маршрутам требуется HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Адрес шлюза</string>
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes reported this error. The app won’t switch routes or models automatically.</string>
|
||||
<string name="chat_failure_copy_details">Copy details</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Open Settings</string>
|
||||
<string name="chat_connect_hermes">Connect Hermes</string>
|
||||
<string name="chat_try_demo">Try the demo</string>
|
||||
@@ -315,7 +315,7 @@
|
||||
<string name="cw_cloud_subtitle">Connect to your hosted agent</string>
|
||||
<string name="cw_server_vps_title">Remote gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Enter its Dashboard address</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and API fallback are optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and Direct API are optional.</string>
|
||||
<string name="cw_cloud_entry_title">Connect to Nous-hosted Hermes</string>
|
||||
<string name="cw_cloud_entry_description">Enter the agent address shown in Nous Portal. You’ll sign in securely after Hermes is found.</string>
|
||||
<string name="cw_cloud_agent_name">Agent address</string>
|
||||
@@ -387,7 +387,7 @@
|
||||
<string name="cw_back">Back</string>
|
||||
<string name="cw_connect_button">Connect</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the preferred upstream auth path; the API key remains the Android Chat fallback.</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the standard upstream auth path; an API key is only for explicit Direct API connections.</string>
|
||||
<string name="cw_api_url_label">API server URL or host</string>
|
||||
<string name="cw_api_key_label">API key</string>
|
||||
<string name="cw_api_key_placeholder">Value from API_SERVER_KEY</string>
|
||||
@@ -419,7 +419,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 or http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API used by Chat and sessions — API port 8642 and http:// assumed for bare hosts (the dashboard\'s 9119 is derived separately)</string>
|
||||
<string name="cw_scan_message">Scanning this LAN for Hermes dashboard/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for the optional direct API fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for optional Direct API compatibility.</string>
|
||||
<string name="cw_pair_relay_section">Pair Relay (optional)</string>
|
||||
<string name="cw_pair_relay_for">Pair Relay with %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Add the optional Relay extension to this saved Hermes connection. This does not add or replace a server.</string>
|
||||
@@ -751,12 +751,12 @@
|
||||
<string name="settings_hermes_management">Hermes management</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard features: skills, cron, MCP, profiles, models</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, API fallback, tool display, message length</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, Direct API, tool display, message length</string>
|
||||
<string name="settings_voice_mode">Voice mode</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard voice, realtime relay options, providers</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Let the agent start conversations with you (off by default)</string>
|
||||
<string name="settings_power_tools">Power tools</string>
|
||||
<string name="settings_threads_desc">Relay-started conversations and proactive delivery (off by default)</string>
|
||||
<string name="settings_power_tools">Relay tools</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Server shell access through a paired relay session</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -768,7 +768,7 @@
|
||||
<string name="settings_notification_companion">Notification companion</string>
|
||||
<string name="settings_notification_companion_desc">Shared phone notifications for paired relay tools</string>
|
||||
<string name="settings_media">Media</string>
|
||||
<string name="settings_media_desc">Relay inbound attachments, auto-fetch, cache cap</string>
|
||||
<string name="settings_media_desc">Chat attachments, download behavior, privacy, and cache</string>
|
||||
<string name="settings_bridge_safety">Bridge safety</string>
|
||||
<string name="settings_bridge_safety_desc">Blocklist, destructive-verb confirmation, auto-disable</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -872,11 +872,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Show the server\'s hidden \"[System: …]\" markers (model / personality changes). Off matches the desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming endpoint</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: picks the best path based on what your server exposes. Currently using: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: standard connections use Gateway; API-only connections use Direct API. Currently using: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (live thinking via the dashboard WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat via /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat via explicitly streamed /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; falls back to SSE per turn when unavailable.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; when unavailable, this chat stays on Gateway and offers sign-in or retry.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessions: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-compatible SSE via /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use only when your server streams /v1/runs directly.</string>
|
||||
@@ -1027,14 +1027,14 @@
|
||||
<string name="active_section_primary_dashboard">Primary Dashboard</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
<string name="dashboard_gateway_secure_origin">Authenticated Dashboard address</string>
|
||||
<string name="dashboard_gateway_oidc_explainer">The configured route may be LAN, Tailscale, or public. Hermes owns the OIDC callback; Android does not require a second sign-in address.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. API fallback and Relay extensions are optional.</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. Direct API and Relay extensions are optional.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
@@ -1054,7 +1054,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Not reachable</string>
|
||||
<string name="active_section_no_fallback_routes">No fallback routes yet</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Add a LAN, Tailscale, or public address to keep this connection available when networks change.</string>
|
||||
<string name="active_section_add_api_fallback">Add fallback route</string>
|
||||
<string name="active_section_add_api_fallback">Add Direct API route</string>
|
||||
<string name="active_section_security_authentication">Authentication</string>
|
||||
<string name="active_section_dashboard_session">Dashboard session</string>
|
||||
<string name="active_section_credential_storage">Credential storage</string>
|
||||
@@ -1069,7 +1069,7 @@
|
||||
<string name="active_section_route_selection">Route selection</string>
|
||||
<string name="active_section_automatic">Automatic</string>
|
||||
<string name="active_section_api_access">API access</string>
|
||||
<string name="active_section_optional_api_fallback">Optional direct API fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optional Direct API</string>
|
||||
<string name="active_section_api_not_required">Not required when this connection uses the Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Where do I get this?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY is created on your Hermes server; it is not supplied by this app. Configure it only when you enable the optional API server, which requires a usable key, then enter the same value here.</string>
|
||||
@@ -1383,8 +1383,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Media</string>
|
||||
<string name="media_back">Back</string>
|
||||
<string name="media_intro_1">Controls how the app handles files sent by tool results (screenshots, PDFs, etc.) over the relay.</string>
|
||||
<string name="media_intro_2">Relay only — these settings don\'t affect images you attach in chat or anything on a standard (no-Relay) connection.</string>
|
||||
<string name="media_intro_1">Controls how the app downloads, protects, and caches files Hermes sends in chat.</string>
|
||||
<string name="media_intro_2">Standard Dashboard media is preferred. When paired, Relay can add compatibility delivery and sensitivity metadata.</string>
|
||||
<string name="media_max_inbound">Max inbound attachment size</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Files larger than this are rejected after download.</string>
|
||||
@@ -2513,7 +2513,8 @@
|
||||
<string name="session_path_signin_for_gateway">Sign in under Manage for the live-thinking gateway.</string>
|
||||
<string name="session_path_gateway_api_server">Available on the gateway transport — this session streams over the API server.</string>
|
||||
<string name="session_path_relay_not_connected">Relay paired but not connected.</string>
|
||||
<string name="session_path_pair_relay_media">Pair the relay to send and receive media.</string>
|
||||
<string name="session_path_pair_relay_media">Pair Relay for media compatibility on older Hermes hosts.</string>
|
||||
<string name="session_path_media_not_ready">Update Hermes for standard media delivery, or pair Relay for compatibility.</string>
|
||||
<string name="session_path_pair_relay_terminal">Pair the relay for terminal access.</string>
|
||||
<string name="session_path_voice_not_ready">Voice not ready on this connection.</string>
|
||||
<string name="session_path_threads_pair_relay">Pair the relay and turn on "Let Hermes message me" so the agent can open Threads.</string>
|
||||
@@ -3161,6 +3162,8 @@
|
||||
<string name="inbound_attach_downloading">Downloading…%1$s</string>
|
||||
<string name="inbound_attach_failed">Attachment failed</string>
|
||||
<string name="inbound_attach_tap_retry">Tap to retry</string>
|
||||
<string name="inbound_attach_host_only">File is on your Hermes host</string>
|
||||
<string name="inbound_attach_host_only_help">Update Hermes for standard downloads, or pair Relay for compatibility.</string>
|
||||
<string name="inbound_attach_open">Open externally</string>
|
||||
<string name="inbound_attach_share">Share</string>
|
||||
<string name="inbound_attach_save">Save to device</string>
|
||||
@@ -3689,6 +3692,8 @@
|
||||
<string name="diag_check_ready_with">Ready with %s</string>
|
||||
<string name="diag_check_relay_active">Relay active</string>
|
||||
<string name="diag_check_relay_not_configured">Relay not configured</string>
|
||||
<string name="diag_relay_tools_optional">Relay tools (optional)</string>
|
||||
<string name="diag_relay_tools_not_paired">Not paired</string>
|
||||
<string name="diag_check_relay_server">Check relay server</string>
|
||||
<string name="diag_check_relay_plugin">Relay plugin</string>
|
||||
<string name="diag_plugin_not_configured">Optional plugin is not configured</string>
|
||||
@@ -3720,8 +3725,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancel</string>
|
||||
<string name="inbound_attach_open_failed">Couldn\u0027t open attachment</string>
|
||||
<string name="inbound_attach_share_failed">Couldn\u0027t share attachment</string>
|
||||
<string name="injected_context_media_no_relay">Media requires an active Relay connection</string>
|
||||
<string name="injected_context_media_relay_active">Relay active for media</string>
|
||||
<string name="injected_context_media_no_relay">No extra media instruction — standard delivery stays server-owned</string>
|
||||
<string name="injected_context_media_relay_active">Relay media enhancement available</string>
|
||||
<string name="injected_context_media_title">Media sharing</string>
|
||||
<string name="injected_context_persona_not_set">No persona set</string>
|
||||
<string name="injected_context_persona_server_side">Server-side persona</string>
|
||||
@@ -4255,7 +4260,7 @@
|
||||
<string name="voice_overlay_notification_body">Microphone access remains available while Hermes is over another app.</string>
|
||||
<string name="voice_overlay_notification_stop">Stop voice</string>
|
||||
<string name="conn_info_profile_api_key_title">Profile API key</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex API fallback. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex Direct API route. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_stored">A key is stored</string>
|
||||
<string name="conn_info_profile_api_key_not_stored">No key stored</string>
|
||||
<string name="conn_info_profile_api_key_save">Save key</string>
|
||||
@@ -4586,6 +4591,6 @@
|
||||
<string name="provider_usage_capability_basic_title">Basic usage from Hermes</string>
|
||||
<string name="provider_usage_capability_basic_body">Install or update the Relay plugin for credential pools, structured Nous balances, and OpenCode Go.</string>
|
||||
<string name="settings_git_workspace">Git workspace</string>
|
||||
<string name="settings_git_workspace_desc">Review changes, branches, commits, and remotes</string>
|
||||
<string name="settings_git_workspace_off_desc">Off · Host repository scanning is opt-in</string>
|
||||
<string name="settings_git_workspace_desc">Current-session Git first, with optional host discovery</string>
|
||||
<string name="settings_git_workspace_off_desc">Session repository only · Host discovery is opt-in</string>
|
||||
</resources>
|
||||
|
||||
@@ -38,6 +38,7 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiServerConfigured)
|
||||
assertTrue(connection.capabilities.relayConfigured)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,6 +54,20 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiChatFallbackAvailable)
|
||||
assertFalse(connection.capabilities.relayFeaturesAvailable)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedDashboardOwnsAutoChatEvenWhenApiIsAlsoConfigured() {
|
||||
val connection = connection(
|
||||
dashboardUrl = "https://hermes.example.com",
|
||||
apiServerUrl = "https://api.example.com",
|
||||
relayUrl = "",
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, connection.automaticChatTransport)
|
||||
assertEquals(SessionTransport.GATEWAY, connection.chatTransportForPreference("auto"))
|
||||
assertEquals(SessionTransport.SSE, connection.chatTransportForPreference("sessions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -184,7 +184,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Tls, result.level)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -203,7 +203,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Plain, result.level)
|
||||
assertEquals(SurfaceUseState.Unavailable, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedParentAuthStoreTest {
|
||||
@Test
|
||||
fun `new credential policy accepts strong pins and passwords`() {
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("12345".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("123456".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("1234567".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("short".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("long passphrase".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret(" ".repeat(8).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("x".repeat(65).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enrollment stores only salted PBKDF2 verifiers and returns six word recovery phrase`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
|
||||
val enrollment = store.enroll(
|
||||
"correct horse".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').size)
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').distinct().size)
|
||||
assertTrue(raw.contains("PBKDF2WithHmacSHA256"))
|
||||
assertTrue(raw.contains("\"iterations\":1"))
|
||||
assertFalse(raw.contains("correct horse"))
|
||||
assertFalse(raw.contains(enrollment.recoveryPhrase))
|
||||
assertTrue(raw.contains("\"credentialType\":\"Password\""))
|
||||
assertTrue(raw.contains("\"recoveryFormat\":\"WordPhrase\""))
|
||||
val salts = Regex("\"(?:parentSalt|recoverySalt)\":\"([^\"]+)\"")
|
||||
.findAll(raw).map { it.groupValues[1] }.toList()
|
||||
assertEquals(2, salts.size)
|
||||
assertNotEquals(salts[0], salts[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `production enrollment records 310000 rounds`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 310_000,
|
||||
)
|
||||
|
||||
store.enroll("production-strength".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(
|
||||
dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting]
|
||||
.orEmpty().contains("\"iterations\":310000"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `verification is fail closed when missing or corrupt`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Missing, store.verify("anything".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "not-json" }
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Corrupt, store.verify("anything".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unsupported or weakened records fail closed`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"version\":1", "\"version\":2")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"iterations\":1", "\"iterations\":0")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `records created before credential type selection remain verifiable`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val current = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
val legacy = current
|
||||
.replace(Regex(",\"credentialType\":\"Password\""), "")
|
||||
.replace(Regex(",\"recoveryFormat\":\"WordPhrase\""), "")
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = legacy }
|
||||
|
||||
assertEquals(SupervisedParentCredentialType.Legacy, store.credentialTypeFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enroll cannot replace an existing or corrupt credential`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("first password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("first password".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "corrupt" }
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `authenticated clear removes credential and disables policies without losing settings`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val authStore = fastStore(dataStore)
|
||||
val policyStore = SupervisedModeStore.forTesting(dataStore)
|
||||
authStore.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
policyStore.setPolicy(
|
||||
"connection-a",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(attachments = false, voice = true),
|
||||
),
|
||||
)
|
||||
policyStore.setPolicy(
|
||||
"connection-b",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "coder",
|
||||
visibility = SupervisedVisibility(showTimestamps = true),
|
||||
),
|
||||
)
|
||||
val beforeA = policyStore.policyFlow("connection-a").first()
|
||||
val beforeB = policyStore.policyFlow("connection-b").first()
|
||||
|
||||
authStore.clearCredentialAndDisablePolicies().getOrThrow()
|
||||
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, authStore.statusFlow.first())
|
||||
assertEquals(beforeA.copy(enabled = false), policyStore.policyFlow("connection-a").first())
|
||||
assertEquals(beforeB.copy(enabled = false), policyStore.policyFlow("connection-b").first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed attempts persist across store recreation and backoff expires by clock`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val clock = AtomicLong(1_000L)
|
||||
var store = fastStore(dataStore, clock)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
repeat(4) {
|
||||
assertTrue(store.verify("wrong password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
}
|
||||
val fifth = store.verify("wrong password".toCharArray())
|
||||
assertEquals(SupervisedParentAuthResult.Throttled(30_000L), fifth)
|
||||
|
||||
store = fastStore(dataStore, clock)
|
||||
assertEquals(
|
||||
SupervisedParentAuthResult.Throttled(30_000L),
|
||||
store.verify("parent password".toCharArray()),
|
||||
)
|
||||
clock.addAndGet(30_001L)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `concurrent store instances preserve the capped failure sequence`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val stores = List(5) { fastStore(dataStore) }
|
||||
stores.first().enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
val results = stores.map { store -> async { store.verify("wrong password".toCharArray()) } }.awaitAll()
|
||||
|
||||
assertEquals(4, results.count { it is SupervisedParentAuthResult.Invalid })
|
||||
assertEquals(1, results.count { it == SupervisedParentAuthResult.Throttled(30_000L) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `change requires the current credential and rotates recovery`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.change("wrong".toCharArray(), "new password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("old password".toCharArray()))
|
||||
|
||||
val replacement = store.change(
|
||||
"old password".toCharArray(),
|
||||
"654321".toCharArray(),
|
||||
SupervisedParentCredentialType.Pin,
|
||||
).getOrThrow()
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertTrue(store.verify("old password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("654321".toCharArray()))
|
||||
assertEquals(SupervisedParentCredentialType.Pin, store.credentialTypeFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery is normalized one time and rotates both secrets`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val lowerSpaced = original.recoveryPhrase.uppercase().replace("-", " ").toCharArray()
|
||||
|
||||
val replacement = store.resetWithRecoveryPhrase(
|
||||
lowerSpaced,
|
||||
"new password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("new password".toCharArray()))
|
||||
assertTrue(
|
||||
store.resetWithRecoveryPhrase(
|
||||
original.recoveryPhrase.toCharArray(),
|
||||
"another password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
)
|
||||
.isFailure,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fastStore(
|
||||
dataStore: DataStore<Preferences>,
|
||||
clock: AtomicLong = AtomicLong(1_000L),
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 1,
|
||||
minimumAcceptedIterations = 1,
|
||||
nowMillis = clock::get,
|
||||
)
|
||||
}
|
||||
|
||||
private class InMemoryParentAuthDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow(emptyPreferences())
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
|
||||
val updated = transform(state.value)
|
||||
state.value = updated
|
||||
return updated
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,70 @@ class VoicePreferencesRepositoryTest {
|
||||
repository.setStopPhrases(emptyList())
|
||||
assertTrue(repository.settings.first().stopPhrases.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_normalizesOnlyRelayOwnedSelectionsInExpectedScope() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
val scope = repository.activeScope.value
|
||||
|
||||
assertTrue(repository.reconcileRelayRemoval(scope))
|
||||
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.HermesVoiceOutput.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Auto.storageValue, settings.audioRoute)
|
||||
assertFalse(repository.reconcileRelayRemoval(scope))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_doesNotMutateAProfileThatNoLongerOwnsTheScope() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
val staleScope = repository.activeScope.value
|
||||
|
||||
repository.setActiveScope("connection-a", "writer")
|
||||
assertFalse(repository.reconcileRelayRemoval(staleScope))
|
||||
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_doesNotRewriteGlobalDefaultSelectionSharedByAnotherConnection() = runTest {
|
||||
repository.setActiveScope("connection-a", null)
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
assertFalse(repository.reconcileRelayRemoval(repository.activeScope.value))
|
||||
|
||||
repository.setActiveScope("connection-b", null)
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayRemoval_normalizesNamedProfileWithoutChangingSameProfileOnAnotherConnection() = runTest {
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
repository.setActiveScope("connection-b", "coder")
|
||||
repository.setEngineMode(VoiceEngineMode.RealtimeAgent)
|
||||
repository.setAudioRoute(VoiceAudioRoute.Relay)
|
||||
|
||||
repository.setActiveScope("connection-a", "coder")
|
||||
assertTrue(repository.reconcileRelayRemoval(repository.activeScope.value))
|
||||
|
||||
repository.setActiveScope("connection-b", "coder")
|
||||
val settings = repository.settings.first()
|
||||
assertEquals(VoiceEngineMode.RealtimeAgent.storageValue, settings.engineMode)
|
||||
assertEquals(VoiceAudioRoute.Relay.storageValue, settings.audioRoute)
|
||||
}
|
||||
}
|
||||
|
||||
private class InMemoryVoicePreferencesDataStore : DataStore<Preferences> {
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.hermesandroid.relay.network.relay
|
||||
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class RelayHttpClientMediaDownloadTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fetchMediaByPathStopsChunkedResponseAtCallerLimit() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/octet-stream")
|
||||
.setChunkedBody("x".repeat(64), 8),
|
||||
)
|
||||
val client = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = {
|
||||
server.url("/").toString().replaceFirst("http://", "ws://").trimEnd('/')
|
||||
},
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
)
|
||||
|
||||
val result = client.fetchMediaByPath("/tmp/large.bin", maxBytes = 16)
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("download limit"))
|
||||
assertEquals("/media/by-path", server.takeRequest().requestUrl?.encodedPath)
|
||||
}
|
||||
}
|
||||
@@ -1530,6 +1530,42 @@ class ChatHandlerTest {
|
||||
assertTrue(handler.messages.value.single().attachments.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_carriesHydratedMarkerAttachmentWithoutReloading() {
|
||||
var requestCount = 0
|
||||
val path = "/tmp/voice-note.mp3"
|
||||
handler.onMediaBarePathRequested = { messageId, requestedPath ->
|
||||
requestCount++
|
||||
handler.mutateMessage(messageId) { message ->
|
||||
message.copy(
|
||||
attachments = message.attachments + Attachment(
|
||||
contentType = "audio/mpeg",
|
||||
content = "",
|
||||
fileName = "voice-note.mp3",
|
||||
relayToken = requestedPath,
|
||||
cachedUri = "content://media/voice-note.mp3",
|
||||
state = AttachmentState.LOADED,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val history = listOf(
|
||||
MessageItem(
|
||||
id = "assistant-media",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Voice note\nMEDIA:$path"),
|
||||
),
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(history)
|
||||
handler.loadMessageHistory(history)
|
||||
|
||||
val attachment = handler.messages.value.single().attachments.single()
|
||||
assertEquals(1, requestCount)
|
||||
assertEquals(AttachmentState.LOADED, attachment.state)
|
||||
assertEquals("content://media/voice-note.mp3", attachment.cachedUri)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_preservesCompletedGeneratedImageUntilMarkerPersists() {
|
||||
handler.addPlaceholderMessage(
|
||||
|
||||
+63
-1
@@ -562,17 +562,24 @@ class DashboardApiClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun signInRequiredClassifierAcceptsNoCookieButRejectsForbidden() {
|
||||
fun signInRequiredClassifierAcceptsEveryUnauthorizedShapeButRejectsForbidden() {
|
||||
val noCookie = DashboardHttpException(
|
||||
401,
|
||||
"Session failed - HTTP 401: {\"reason\":\"no_cookie\",\"detail\":\"Unauthorized\"}",
|
||||
)
|
||||
val expired = DashboardHttpException(
|
||||
401,
|
||||
"Session failed - HTTP 401: {\"reason\":\"session_expired\",\"detail\":\"invalid_or_expired_session\"}",
|
||||
)
|
||||
val generic = DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized")
|
||||
val forbidden = DashboardHttpException(
|
||||
403,
|
||||
"Session failed - HTTP 403: forbidden",
|
||||
)
|
||||
|
||||
assertTrue(noCookie.isDashboardSignInRequiredFailure())
|
||||
assertTrue(expired.isDashboardSignInRequiredFailure())
|
||||
assertTrue(generic.isDashboardSignInRequiredFailure())
|
||||
assertFalse(forbidden.isDashboardSignInRequiredFailure())
|
||||
}
|
||||
|
||||
@@ -2025,6 +2032,61 @@ class DashboardApiClientTest {
|
||||
assertEquals("/api/messaging/whatsapp/onboarding/pair-1/apply", apply.requestUrl!!.encodedPath)
|
||||
assertTrue(apply.body.readUtf8().contains(""""profile":"worker""""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downloadManagedFile_usesUpstreamPathRouteAndPreservesMetadata() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "audio/mpeg")
|
||||
.setHeader("Content-Disposition", "attachment; filename*=UTF-8''voice%20reply.mp3")
|
||||
.setBody("audio-bytes"),
|
||||
)
|
||||
|
||||
val fetched = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.downloadManagedFile("/tmp/Hermes audio/voice reply.mp3", 1024)
|
||||
.getOrThrow()
|
||||
|
||||
assertEquals("audio/mpeg", fetched.contentType)
|
||||
assertEquals("voice reply.mp3", fetched.fileName)
|
||||
assertEquals("audio-bytes", fetched.bytes.decodeToString())
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/files/download", request.requestUrl!!.encodedPath)
|
||||
assertEquals("/tmp/Hermes audio/voice reply.mp3", request.requestUrl!!.queryParameter("path"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downloadManagedFile_rejectsDeclaredLengthAboveCallerCap() = runTest {
|
||||
server.enqueue(MockResponse().setHeader("Content-Length", 2048))
|
||||
|
||||
val result = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.downloadManagedFile("/tmp/large.bin", 1024)
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun managedFileFallbackClassificationDistinguishesMissingRouteFromMissingFile() {
|
||||
assertTrue(
|
||||
DashboardHttpException(
|
||||
404,
|
||||
"Dashboard media download failed - HTTP 404: {\"detail\":\"Not Found\"}",
|
||||
).isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(
|
||||
404,
|
||||
"Dashboard media download failed - HTTP 404: {\"detail\":\"File not found\"}",
|
||||
).isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(403, "Access to sensitive files is not allowed")
|
||||
.isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
assertFalse(
|
||||
DashboardHttpException(500, "Managed file read failed")
|
||||
.isDashboardManagedFilesUnsupported(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun messagePageResponse(
|
||||
|
||||
+333
-1
@@ -227,6 +227,13 @@ class GatewayClientHarness(
|
||||
@Volatile
|
||||
var profileGetAssetPayload: JsonObject = buildJsonObject { put("found", false) }
|
||||
|
||||
@Volatile
|
||||
var usageBarsPayload: JsonObject = buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", true)
|
||||
put("plan_name", "Pro")
|
||||
}
|
||||
|
||||
/** Methods answered with JSON-RPC -32601 — exercises the legacy-name fallback. */
|
||||
val methodNotFound: MutableSet<String> = ConcurrentHashMap.newKeySet()
|
||||
|
||||
@@ -436,6 +443,7 @@ class GatewayClientHarness(
|
||||
"profiles.list" -> profilesListPayload
|
||||
"profiles.create" -> profileCreatePayload
|
||||
"profiles.get_asset" -> profileGetAssetPayload
|
||||
"usage.bars" -> usageBarsPayload
|
||||
"profiles.set_asset" -> buildJsonObject {
|
||||
put("ok", true)
|
||||
put("asset", "avatar")
|
||||
@@ -772,6 +780,7 @@ class GatewayChatClientTest {
|
||||
val moaReferences = ConcurrentLinkedQueue<GatewayMoaReference>()
|
||||
val usages = ConcurrentLinkedQueue<UsageInfo>()
|
||||
val reconcileRequests = AtomicInteger(0)
|
||||
val completions = AtomicInteger(0)
|
||||
val completeLatch = CountDownLatch(1)
|
||||
val preflightFailures = ConcurrentLinkedQueue<String>()
|
||||
|
||||
@@ -785,7 +794,7 @@ class GatewayChatClientTest {
|
||||
onToolCallFailed = { _, _ -> },
|
||||
onTurnComplete = { },
|
||||
onReconcileRequired = { reconcileRequests.incrementAndGet() },
|
||||
onComplete = { completeLatch.countDown() },
|
||||
onComplete = { completions.incrementAndGet(); completeLatch.countDown() },
|
||||
onUsage = { it?.let(usages::add) },
|
||||
onError = { errors += it; completeLatch.countDown() },
|
||||
onToolGenerating = { toolGenerating += it ?: "" },
|
||||
@@ -803,6 +812,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
callbackDispatcher: (block: () -> Unit) -> Unit = { it() },
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) = GatewayChatClient(
|
||||
@@ -824,6 +834,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
)
|
||||
|
||||
private fun awaitCondition(
|
||||
@@ -837,6 +848,21 @@ class GatewayChatClientTest {
|
||||
assertTrue("condition did not settle within ${timeoutMs}ms", condition())
|
||||
}
|
||||
|
||||
private fun exactActiveSessionPayload(
|
||||
status: String,
|
||||
liveSessionId: String = "live-1",
|
||||
storedSessionId: String = "20260612_120000_abc123",
|
||||
): JsonObject = buildJsonObject {
|
||||
put("sessions", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("id", liveSessionId)
|
||||
put("session_key", storedSessionId)
|
||||
put("status", status)
|
||||
put("last_active", 1_777_000_000.0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap in a client with shortened timeout seams. Mints a FRESH scope:
|
||||
* shutdown() cancels the scope's Job, and the replacement client must
|
||||
@@ -846,6 +872,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) {
|
||||
client.shutdown()
|
||||
@@ -854,6 +881,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
ticketTimeoutMs = ticketTimeoutMs,
|
||||
)
|
||||
}
|
||||
@@ -884,6 +912,21 @@ class GatewayChatClientTest {
|
||||
harness.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `provider usage calls official upstream usage bars method`() = runBlocking {
|
||||
harness.usageBarsPayload = buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", true)
|
||||
put("plan_name", "Pro")
|
||||
}
|
||||
|
||||
val response = client.usageBars().getOrThrow()
|
||||
|
||||
assertEquals("Pro", (response["plan_name"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("usage.bars", harness.rpcLog.last().first)
|
||||
assertTrue(harness.rpcLog.none { it.first == "account.usage" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `profile editor describes exact profile and maps upstream shape`() = runBlocking {
|
||||
val description = client.describeProfile("operator").getOrThrow()
|
||||
@@ -3445,6 +3488,42 @@ class GatewayChatClientTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session info exposes exact model callable tool catalog`() {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn("stored-1", "hi", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("session.resume")
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"session.info",
|
||||
buildJsonObject {
|
||||
put("tools", buildJsonObject {
|
||||
put("android", buildJsonArray {
|
||||
add(JsonPrimitive("android_phone_status"))
|
||||
add(JsonPrimitive("android_tap"))
|
||||
})
|
||||
put("terminal", buildJsonArray { add(JsonPrimitive("terminal")) })
|
||||
})
|
||||
},
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
waitUntil { client.serverTools.value?.size == 3 }
|
||||
assertEquals(
|
||||
setOf("android_phone_status", "android_tap", "terminal"),
|
||||
client.serverTools.value,
|
||||
)
|
||||
|
||||
client.clearSession()
|
||||
assertNull(client.serverTools.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session info without provider clears prior session identity`() {
|
||||
val recorder = Recorder()
|
||||
@@ -4710,6 +4789,180 @@ class GatewayChatClientTest {
|
||||
assertTrue(harness.ticketMints.get() >= 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle settles exact Android turn without interrupt`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn(null, "finish without terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "durable partial") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
|
||||
assertTrue(client.listActiveSessions() is GatewayActiveSessionsResult.Success)
|
||||
assertTrue("idle snapshot did not settle turn", recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertEquals(1, recorder.reconcileRequests.get())
|
||||
assertTrue(recorder.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle never settles passively observed turn`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.setUnsolicitedTurnProvider {
|
||||
GatewayInboundTurnRegistration(recorder.callbacks) { true }
|
||||
}
|
||||
assertTrue(client.prewarmAwait("stored-session"))
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload(
|
||||
status = "idle",
|
||||
liveSessionId = "live-resumed",
|
||||
storedSessionId = "stored-session",
|
||||
)
|
||||
|
||||
client.listActiveSessions()
|
||||
assertFalse(recorder.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale active session snapshot cannot settle newer turn generation`() = runBlocking {
|
||||
val first = Recorder()
|
||||
client.sendTurn(null, "first", null, first.callbacks) { first.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "first") }, "live-1"),
|
||||
)
|
||||
awaitCondition { first.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val staleSnapshot = scope.async { client.listActiveSessions() }
|
||||
val staleAck = harness.awaitPendingAck()
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "first") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(first.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
val second = Recorder()
|
||||
client.sendTurn(
|
||||
"20260612_120000_abc123",
|
||||
"second",
|
||||
null,
|
||||
second.callbacks,
|
||||
) { second.preflightFailures += it }
|
||||
harness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "second") }, "live-1"),
|
||||
)
|
||||
awaitCondition { second.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.releaseAck(staleAck, exactActiveSessionPayload("idle"))
|
||||
assertTrue(staleSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertFalse(second.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertEquals(0, second.reconcileRequests.get())
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "second") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(second.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancellation wins over delayed active session idle snapshot`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val handle = client.sendTurn(null, "cancel me", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "partial") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val delayedSnapshot = scope.async { client.listActiveSessions() }
|
||||
val delayedAck = harness.awaitPendingAck()
|
||||
handle.cancel()
|
||||
harness.awaitRpc("session.interrupt")
|
||||
harness.releaseAck(delayedAck, exactActiveSessionPayload("idle"))
|
||||
|
||||
assertTrue(delayedSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertEquals(0, recorder.completions.get())
|
||||
assertEquals(0, recorder.reconcileRequests.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late terminal after active session settle is consumed once`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val unmatched = ConcurrentLinkedQueue<GatewayBackgroundTurnCompletion>()
|
||||
client.setUnmatchedTurnCompleteListener(unmatched::add)
|
||||
client.sendTurn(null, "late terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
client.listActiveSessions()
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "done") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(150)
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertTrue(unmatched.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog does not fire while events keep arriving slowly`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 1_000L)
|
||||
@@ -4738,6 +4991,85 @@ class GatewayChatClientTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting status extends watchdog until a later completion`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 1_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact once", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(500)
|
||||
|
||||
assertTrue("normal idle watchdog fired during compaction: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting heartbeats rearm watchdog beyond one compaction lease`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 200L, compactingTimeoutMs = 500L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact with heartbeats", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
repeat(3) {
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(300)
|
||||
}
|
||||
|
||||
assertTrue("compaction lease was not rearmed: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non compacting status keeps the ordinary watchdog`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 2_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "ordinary status", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "process") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue("ordinary watchdog never fired", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue("expected a stream error from the watchdog", r.errors.isNotEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
harness.awaitRpc("session.interrupt")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog fires when events stop flowing`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 500L)
|
||||
|
||||
+41
-7
@@ -5,9 +5,8 @@ import org.junit.Test
|
||||
|
||||
/**
|
||||
* Resolution matrix for [resolveStreamingEndpointPreference] — the gateway
|
||||
* tier sits above the capability-preferred SSE endpoint for "auto". An
|
||||
* unresolved cold-start probe remains on Gateway until it produces a
|
||||
* definitive fallback verdict.
|
||||
* tier is a stable owner for standard "auto" conversations. API capability
|
||||
* ordering applies only to true API-only compatibility connections.
|
||||
*/
|
||||
class GatewayEndpointResolutionTest {
|
||||
|
||||
@@ -44,28 +43,63 @@ class GatewayEndpointResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto falls back after a definitive non-ready verdict`() {
|
||||
fun `standard auto remains gateway owned after auth expiry or outage`() {
|
||||
listOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
).forEach { availability ->
|
||||
assertEquals(
|
||||
"expected SSE fallback for $availability",
|
||||
"sessions",
|
||||
"expected Gateway affinity for $availability",
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference("auto", availability, fullCaps),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto fallback respects capability ordering`() {
|
||||
fun `API-only auto respects capability ordering`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"completions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
portableOnlyCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `standard auto does not consult API health when gateway is unavailable`() {
|
||||
assertEquals(
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.Unreachable,
|
||||
ServerCapabilities.DISCONNECTED,
|
||||
gatewayOwned = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `manual API selection remains explicit compatibility mode`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"sessions",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+43
@@ -34,6 +34,8 @@ class GatewayEventMapperTest {
|
||||
val failures = mutableListOf<GatewayTurnFailure>()
|
||||
val statusUpdates = mutableListOf<Pair<String?, String>>()
|
||||
val statusClears = mutableListOf<String>()
|
||||
val notices = mutableListOf<GatewayAgentNotice>()
|
||||
val noticeClears = mutableListOf<String>()
|
||||
val sessionIds = mutableListOf<String>()
|
||||
var starts = 0
|
||||
var turnCompletes = 0
|
||||
@@ -70,6 +72,8 @@ class GatewayEventMapperTest {
|
||||
onFailure = { failures += it },
|
||||
onStatusUpdate = { kind, text -> statusUpdates += kind to text },
|
||||
onStatusClear = { statusClears += it },
|
||||
onNoticeShow = { notices += it },
|
||||
onNoticeClear = { noticeClears += it },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -123,6 +127,45 @@ class GatewayEventMapperTest {
|
||||
assertTrue(r.statusUpdates.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `official notice show and clear preserve exact keyed contract`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
|
||||
mapper.onEvent(
|
||||
"notification.show",
|
||||
obj(
|
||||
"""{"text":"⚠ Credits depleted","level":"warn","kind":"sticky","ttl_ms":null,"key":"credits.depleted","id":"notice-1"}""",
|
||||
),
|
||||
)
|
||||
mapper.onEvent("notification.clear", obj("""{"key":"credits.depleted"}"""))
|
||||
|
||||
assertEquals(
|
||||
GatewayAgentNotice(
|
||||
text = "⚠ Credits depleted",
|
||||
level = "warn",
|
||||
kind = "sticky",
|
||||
ttlMs = null,
|
||||
key = "credits.depleted",
|
||||
id = "notice-1",
|
||||
),
|
||||
r.notices.single(),
|
||||
)
|
||||
assertEquals(listOf("credits.depleted"), r.noticeClears)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `malformed official notices remain forward compatible no ops`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
|
||||
mapper.onEvent("notification.show", obj("""{"level":"info"}"""))
|
||||
mapper.onEvent("notification.clear", obj("""{"key":" "}"""))
|
||||
|
||||
assertTrue(r.notices.isEmpty())
|
||||
assertTrue(r.noticeClears.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compaction status clears on resumed model tool and MoA activity only`() {
|
||||
listOf(
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package com.hermesandroid.relay.network.usage
|
||||
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ProviderUsageRepositoryTest {
|
||||
@Test
|
||||
fun mapsOfficialUpstreamUsageBars() {
|
||||
val response = providerUsageFromUpstreamBars(buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", true)
|
||||
put("plan_name", "Pro")
|
||||
put("renews_at", "2026-09-15T00:00:00Z")
|
||||
put("subscription_remaining_display", "\$12.50")
|
||||
put("topup_remaining_display", "\$3.00")
|
||||
put("total_spendable_display", "\$15.50")
|
||||
put("plan_bar", buildJsonObject {
|
||||
put("remaining_display", "\$12.50")
|
||||
put("total_display", "\$20.00")
|
||||
put("pct_used", 37.5)
|
||||
})
|
||||
put("topup_bar", buildJsonObject {
|
||||
put("remaining_display", "\$3.00")
|
||||
put("total_display", "\$5.00")
|
||||
put("pct_used", 40.0)
|
||||
})
|
||||
})!!
|
||||
|
||||
val nous = response.providers.single()
|
||||
assertEquals("nous", nous.id)
|
||||
assertEquals("upstream:usage.bars", nous.source)
|
||||
assertEquals("Pro", nous.plan)
|
||||
assertEquals("2026-09-15T00:00:00Z", nous.renewsAt)
|
||||
assertEquals(37.5, nous.windows.first().usedPercent!!, 0.001)
|
||||
assertEquals("\$12.50 remaining of \$20.00", nous.windows.first().detail)
|
||||
assertEquals(3, nous.details.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unavailableUpstreamUsageIsCapabilityAbsence() {
|
||||
assertNull(providerUsageFromUpstreamBars(buildJsonObject {
|
||||
put("ok", true)
|
||||
put("available", false)
|
||||
}))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayEnhancementAddsProvidersAndEnrichesNous() {
|
||||
val upstream = ProviderUsageResponse(
|
||||
providers = listOf(
|
||||
ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "upstream:usage.bars",
|
||||
plan = "Pro",
|
||||
windows = listOf(ProviderUsageWindow("plan", "Plan", usedPercent = 25.0)),
|
||||
details = listOf("Total spendable: \$10.00"),
|
||||
),
|
||||
),
|
||||
)
|
||||
val enhanced = ProviderUsageResponse(
|
||||
schemaVersion = 2,
|
||||
capabilities = ProviderUsageResponse.RELAY_ENHANCED_CAPABILITIES,
|
||||
providers = listOf(
|
||||
ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "relay",
|
||||
balances = listOf(ProviderUsageBalance("total", "Total usable", 10.0)),
|
||||
),
|
||||
ProviderUsageProvider(
|
||||
id = "openai-codex",
|
||||
displayName = "Codex",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val merged = mergeProviderUsage(upstream, enhanced)!!
|
||||
|
||||
assertTrue(merged.relayEnhanced)
|
||||
assertEquals(listOf("nous", "openai-codex"), merged.providers.map { it.id })
|
||||
val nous = merged.providers.first()
|
||||
assertEquals("Pro", nous.plan)
|
||||
assertEquals(25.0, nous.windows.single().usedPercent!!, 0.001)
|
||||
assertEquals(10.0, nous.balances.single().amount, 0.001)
|
||||
assertEquals(listOf("Total spendable: \$10.00"), nous.details)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unavailableEnhancementDoesNotReplaceAvailableUpstream() {
|
||||
val upstreamProvider = ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "upstream:usage.bars",
|
||||
)
|
||||
val merged = mergeProviderUsage(
|
||||
ProviderUsageResponse(providers = listOf(upstreamProvider)),
|
||||
ProviderUsageResponse(providers = listOf(
|
||||
upstreamProvider.copy(
|
||||
status = ProviderUsageProvider.STATUS_UNAVAILABLE,
|
||||
source = "relay",
|
||||
),
|
||||
)),
|
||||
)!!
|
||||
|
||||
assertEquals("upstream:usage.bars", merged.providers.single().source)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ class HermesRuntimeReadinessTest {
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = false,
|
||||
relayConfigured = false,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
@@ -32,6 +33,7 @@ class HermesRuntimeReadinessTest {
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.SignInRequired,
|
||||
relayReady = true,
|
||||
relayConfigured = true,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
@@ -45,6 +47,7 @@ class HermesRuntimeReadinessTest {
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = true,
|
||||
relayConfigured = true,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
@@ -61,6 +64,7 @@ class HermesRuntimeReadinessTest {
|
||||
chatReady = false,
|
||||
standardAvailability = StandardVoiceAvailability.Unknown,
|
||||
relayReady = true,
|
||||
relayConfigured = true,
|
||||
profileSettled = false,
|
||||
)
|
||||
val ready = resolveVoiceActivationReadiness(
|
||||
@@ -68,6 +72,7 @@ class HermesRuntimeReadinessTest {
|
||||
chatReady = false,
|
||||
standardAvailability = StandardVoiceAvailability.Unknown,
|
||||
relayReady = true,
|
||||
relayConfigured = true,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
@@ -77,4 +82,62 @@ class HermesRuntimeReadinessTest {
|
||||
ready,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relayOnlySelections_fallBackToStandardWhenRelayWasRemoved() {
|
||||
val realtime = resolveVoiceActivationReadiness(
|
||||
settings = VoiceSettings(engineMode = VoiceEngineMode.RealtimeAgent.storageValue),
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = false,
|
||||
relayConfigured = false,
|
||||
profileSettled = true,
|
||||
)
|
||||
val relayAudio = resolveVoiceActivationReadiness(
|
||||
settings = VoiceSettings(audioRoute = VoiceAudioRoute.Relay.storageValue),
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = false,
|
||||
relayConfigured = false,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Standard),
|
||||
realtime,
|
||||
)
|
||||
assertEquals(
|
||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Standard),
|
||||
relayAudio,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun configuredRelayOutage_preservesRelayOnlySelections() {
|
||||
val realtime = resolveVoiceActivationReadiness(
|
||||
settings = VoiceSettings(engineMode = VoiceEngineMode.RealtimeAgent.storageValue),
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = false,
|
||||
relayConfigured = true,
|
||||
profileSettled = true,
|
||||
)
|
||||
val relayAudio = resolveVoiceActivationReadiness(
|
||||
settings = VoiceSettings(audioRoute = VoiceAudioRoute.Relay.storageValue),
|
||||
chatReady = true,
|
||||
standardAvailability = StandardVoiceAvailability.Ready,
|
||||
relayReady = false,
|
||||
relayConfigured = true,
|
||||
profileSettled = true,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
HermesVoiceActivationReadiness.Waiting("Waiting for the Relay realtime route"),
|
||||
realtime,
|
||||
)
|
||||
assertEquals(
|
||||
HermesVoiceActivationReadiness.Waiting("Waiting for Relay voice"),
|
||||
relayAudio,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,40 @@ class GitWorkspaceScreenshotTest {
|
||||
compose.onRoot().captureRoboImage("build/store-shots/15_git_workspace.png")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun standardSessionWorkspaceRendersWithRelayDiscoveryOff() {
|
||||
enqueue("""{"branch":"main","changed":1,"staged":0,"unstaged":1,"untracked":0,"added":3,"removed":1,"files":[{"path":"app.kt","unstaged":true}]}""")
|
||||
enqueue("""{"branch":"main","changed":1,"staged":0,"unstaged":1,"untracked":0,"added":3,"removed":1,"files":[{"path":"app.kt","unstaged":true}]}""")
|
||||
enqueue("""{"files":[{"path":"app.kt","added":3,"removed":1,"staged":false}]}""")
|
||||
enqueue("""{"branches":[{"name":"main","checkedOut":true}]}""")
|
||||
val app = ApplicationProvider.getApplicationContext<Application>()
|
||||
val viewModel = GitStateViewModel(app)
|
||||
viewModel.configure(
|
||||
DashboardApiClient(server.url("/").toString()),
|
||||
"standard-owner",
|
||||
scanningEnabled = false,
|
||||
)
|
||||
viewModel.setSessionWorkspace("/srv/projects/standard", null)
|
||||
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
GitStateScreen(
|
||||
viewModel = viewModel,
|
||||
onScanningEnabledChange = {},
|
||||
onBack = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
runCatching { compose.onNodeWithText("1 changes").assertExists() }.isSuccess
|
||||
}
|
||||
val paths = buildList {
|
||||
repeat(4) { add(server.takeRequest().path.orEmpty()) }
|
||||
}
|
||||
org.junit.Assert.assertTrue(paths.none { it.contains("/api/plugins/") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatRailMatchesApprovedCompactTreatment() {
|
||||
compose.setContent {
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.ui.screens.CredentialChoiceScreen
|
||||
import com.hermesandroid.relay.ui.screens.ParentAuthScreenSurface
|
||||
import com.hermesandroid.relay.ui.screens.PasswordSetupScreen
|
||||
import com.hermesandroid.relay.ui.screens.PinSetupScreen
|
||||
import com.hermesandroid.relay.ui.screens.SupervisedParentRecoveryCodeContent
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w400dp-h900dp-432dpi")
|
||||
class SupervisedParentAuthFlowScreenshotTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun credentialChoice() {
|
||||
render("build/visual-qa/supervised-parent-choice.png", 1 to 2) {
|
||||
CredentialChoiceScreen(
|
||||
title = "Choose parent access",
|
||||
subtitle = "Pick one way to unlock parent settings. You can change it later.",
|
||||
onSelected = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinSetup() {
|
||||
render("build/visual-qa/supervised-parent-pin.png", 2 to 2) {
|
||||
PinSetupScreen(busy = false, error = null, onComplete = {})
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passwordSetup() {
|
||||
render("build/visual-qa/supervised-parent-password.png", 2 to 2) {
|
||||
PasswordSetupScreen(busy = false, error = null, onComplete = {})
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveryPhrase() {
|
||||
render("build/visual-qa/supervised-parent-recovery.png", 3 to 3) {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
enrollment = SupervisedParentEnrollment(
|
||||
"maple-river-lantern-copper-sparrow-moon",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun render(
|
||||
path: String,
|
||||
step: Pair<Int, Int>,
|
||||
content: @androidx.compose.runtime.Composable () -> Unit,
|
||||
) {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
ParentAuthScreenSurface(step = step, onBack = {}, content = content)
|
||||
}
|
||||
}
|
||||
compose.onRoot().captureRoboImage(path)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,39 @@ class RelayAppStatusTest {
|
||||
assertEquals(ChatRuntimeStatus.Connecting, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard sign-out is not masked by a reachable sibling API`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = "https://host.ts.net:9119",
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
streamingEndpoint = "sessions",
|
||||
conversationOwner = com.hermesandroid.relay.data.SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(ChatRuntimeStatus.Unavailable, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy API-only connection remains connected compatibility chat`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = null,
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `committed pair target stays ready while public inventory catches up`() {
|
||||
assertTrue(
|
||||
@@ -392,7 +425,7 @@ class RelayAppStatusTest {
|
||||
}
|
||||
|
||||
private fun connected(path: ChatTransportPath) =
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = path == ChatTransportPath.ApiSse)
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = false)
|
||||
|
||||
private fun connection(
|
||||
dashboardUrl: String? = null,
|
||||
|
||||
@@ -172,25 +172,23 @@ class SupervisedNavigationPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
|
||||
@Test fun `first enable requires configured policy and successful app parent credential`() {
|
||||
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
|
||||
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = false,
|
||||
deviceCredentialConfirmed = true,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = true,
|
||||
deviceCredentialConfirmed = false,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class UiMessageBusTest {
|
||||
@Test
|
||||
fun keyedShowReplacesInPlaceAndClearRemovesOnlyExactOwner() {
|
||||
val unrelated = message(1, "Network ready", key = "network")
|
||||
val first = message(2, "Half used", key = "credits.usage")
|
||||
val replacement = message(3, "Almost used", key = "credits.usage")
|
||||
|
||||
val replaced = reduceUiMessages(
|
||||
listOf(unrelated, first),
|
||||
UiMessageEvent.Show(replacement),
|
||||
maxRetained = 6,
|
||||
)
|
||||
val cleared = reduceUiMessages(
|
||||
replaced,
|
||||
UiMessageEvent.Clear("credits.usage"),
|
||||
maxRetained = 6,
|
||||
)
|
||||
|
||||
assertEquals(listOf(unrelated, replacement), replaced)
|
||||
assertEquals(listOf(unrelated), cleared)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unkeyedMessagesStillCoalesceByTextAndRespectBound() {
|
||||
var state = emptyList<UiMessage>()
|
||||
repeat(8) { index ->
|
||||
state = reduceUiMessages(
|
||||
state,
|
||||
UiMessageEvent.Show(message(index.toLong(), "message-$index")),
|
||||
maxRetained = 6,
|
||||
)
|
||||
}
|
||||
state = reduceUiMessages(
|
||||
state,
|
||||
UiMessageEvent.Show(message(99, "message-7")),
|
||||
maxRetained = 6,
|
||||
)
|
||||
|
||||
assertEquals(6, state.size)
|
||||
assertEquals(99L, state.last().id)
|
||||
assertEquals(1, state.count { it.text == "message-7" })
|
||||
assertTrue(state.none { it.text == "message-0" })
|
||||
}
|
||||
|
||||
private fun message(id: Long, text: String, key: String? = null) = UiMessage(
|
||||
id = id,
|
||||
text = text,
|
||||
severity = UiMessageSeverity.Info,
|
||||
ttlMillis = UiMessageBus.DEFAULT_TTL_MS,
|
||||
key = key,
|
||||
)
|
||||
}
|
||||
@@ -60,9 +60,20 @@ class DiagnosticsScreenTest {
|
||||
assertEquals(
|
||||
CheckStatus.Unknown,
|
||||
checks.single {
|
||||
it.name == context.getString(R.string.active_section_optional_relay)
|
||||
it.name == context.getString(R.string.diag_relay_tools_optional)
|
||||
}.status,
|
||||
)
|
||||
assertEquals(
|
||||
context.getString(R.string.diag_relay_tools_not_paired),
|
||||
checks.single { it.name == context.getString(R.string.diag_relay_tools_optional) }.reason,
|
||||
)
|
||||
assertFalse(
|
||||
checks.any {
|
||||
it.name == context.getString(R.string.diag_check_pairing_auth) ||
|
||||
it.name == context.getString(R.string.active_section_optional_relay) ||
|
||||
it.name == context.getString(R.string.diag_check_relay_plugin)
|
||||
},
|
||||
)
|
||||
assertFalse(
|
||||
"Absent optional API/Relay surfaces must not make chat fail",
|
||||
checks.any {
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.SupervisedParentCredentialType
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@Config(qualifiers = "w400dp-h900dp-432dpi")
|
||||
class SupervisedParentAuthDialogsTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `choice presents mutually exclusive pin and password routes`() {
|
||||
var selected: SupervisedParentCredentialType? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
CredentialChoiceScreen("Choose parent access", "Pick one.") { selected = it }
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Use a PIN").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Pin, selected) }
|
||||
compose.onNodeWithText("Use a password").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Password, selected) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pin auth uses six positions and a dedicated numeric keypad`() {
|
||||
var submitted: String? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
PinEntryScreen("Parent PIN", "Enter your 6-digit PIN.", false, null, { submitted = it })
|
||||
}
|
||||
}
|
||||
|
||||
(0..9).forEach { compose.onNodeWithText(it.toString()).assertIsDisplayed() }
|
||||
compose.onNodeWithContentDescription("Delete digit").assertIsDisplayed()
|
||||
(1..6).forEach { compose.onNodeWithText(it.toString()).performClick() }
|
||||
compose.runOnIdle { assertEquals("123456", submitted) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password setup uses distinct password fields and visibility controls`() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme { PasswordSetupScreen(false, null, {}) }
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Create a parent password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Confirm password").assertIsDisplayed()
|
||||
compose.onAllNodesWithContentDescription("Show password").assertCountEquals(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery phrase handoff exposes sharing copy and cleanup guidance`() {
|
||||
var shares = 0
|
||||
var copies = 0
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
SupervisedParentEnrollment("maple-river-lantern-copper-sparrow-moon"),
|
||||
onShare = { shares += 1 },
|
||||
onCopy = { copies += 1 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("maple-river-lantern", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("copper-sparrow-moon", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").assertIsDisplayed()
|
||||
compose.onNodeWithText("Copy phrase").assertIsDisplayed()
|
||||
compose.onNodeWithText("delete the message or saved copy", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").performClick()
|
||||
compose.onNodeWithText("Copy phrase").performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, shares)
|
||||
assertEquals(1, copies)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,12 +27,62 @@ import org.junit.Test
|
||||
class PhoneStatusPromptBuilderTest {
|
||||
|
||||
private val defaultSettings = AppContextSettings()
|
||||
private val phoneTools = setOf("android_phone_status", "android_tap")
|
||||
|
||||
@Test
|
||||
fun missingToolCatalog_keepsNeutralMobileContextWithoutRelayClaims() {
|
||||
val output = buildPromptBlock(
|
||||
defaultSettings,
|
||||
PhoneSnapshot(
|
||||
bridgeBound = true,
|
||||
masterEnabled = true,
|
||||
blocklistCount = 4,
|
||||
),
|
||||
availableTools = null,
|
||||
)
|
||||
|
||||
assertNotNull(output)
|
||||
assertTrue(output!!.contains("Hermes-Relay Android app"))
|
||||
assertFalse(output.contains("Phone bridge:"))
|
||||
assertFalse(output.contains("android_phone_status"))
|
||||
assertFalse(output.contains("Safety rails:"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun settingsPreviewFixture_keepsBridgeAndSafetyToggleExamplesVisible() {
|
||||
val output = buildPromptBlock(
|
||||
defaultSettings,
|
||||
PhoneSnapshot(
|
||||
blocklistCount = 3,
|
||||
destructiveVerbCount = 5,
|
||||
autoDisableMinutes = 15,
|
||||
),
|
||||
availableTools = PHONE_CONTEXT_PREVIEW_TOOLS,
|
||||
)
|
||||
|
||||
assertNotNull(output)
|
||||
assertTrue(output!!.contains("Phone bridge: not connected"))
|
||||
assertTrue(output.contains("Safety rails: 3 blocked apps, 5 destructive verbs, 15m auto-disable."))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setupOnlyCatalog_doesNotAdvertisePhoneControl() {
|
||||
val output = buildPromptBlock(
|
||||
defaultSettings,
|
||||
PhoneSnapshot(bridgeBound = true, masterEnabled = true),
|
||||
availableTools = setOf("android_setup"),
|
||||
)
|
||||
|
||||
assertNotNull(output)
|
||||
assertFalse(output!!.contains("Phone bridge:"))
|
||||
assertFalse(output.contains("android_phone_status"))
|
||||
}
|
||||
|
||||
// --- Case 1: bridge not bound, all defaults off ---
|
||||
|
||||
@Test
|
||||
fun defaultSnapshot_bridgeNotBound_saysNotConnected() {
|
||||
val output = buildPromptBlock(defaultSettings, PhoneSnapshot())
|
||||
val output = buildPromptBlock(defaultSettings, PhoneSnapshot(), phoneTools)
|
||||
assertNotNull(
|
||||
"master defaults to true so the block should render",
|
||||
output,
|
||||
@@ -63,7 +113,7 @@ class PhoneStatusPromptBuilderTest {
|
||||
credentialLockDetected = true,
|
||||
screenOn = true,
|
||||
)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot, phoneTools)
|
||||
assertNotNull(output)
|
||||
assertTrue(
|
||||
"expected the disabled-by-user line; got: $output",
|
||||
@@ -91,7 +141,7 @@ class PhoneStatusPromptBuilderTest {
|
||||
credentialLockDetected = false,
|
||||
screenOn = true,
|
||||
)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot, phoneTools)
|
||||
assertNotNull(output)
|
||||
assertTrue(
|
||||
"expected 'Unattended access: off' advisory; got: $output",
|
||||
@@ -123,7 +173,7 @@ class PhoneStatusPromptBuilderTest {
|
||||
credentialLockDetected = false,
|
||||
screenOn = false,
|
||||
)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot, phoneTools)
|
||||
assertNotNull(output)
|
||||
assertTrue(
|
||||
"expected the 'Unattended access: on — the screen will wake' advisory; got: $output",
|
||||
@@ -155,7 +205,7 @@ class PhoneStatusPromptBuilderTest {
|
||||
credentialLockDetected = true,
|
||||
screenOn = true,
|
||||
)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot, phoneTools)
|
||||
assertNotNull(output)
|
||||
assertTrue(
|
||||
"agent MUST see the credential-lock warning string; got: $output",
|
||||
@@ -188,6 +238,7 @@ class PhoneStatusPromptBuilderTest {
|
||||
unattendedEnabled = true,
|
||||
screenOn = true,
|
||||
),
|
||||
phoneTools,
|
||||
)
|
||||
assertNull(
|
||||
"master=false must omit the system message entirely " +
|
||||
@@ -213,11 +264,29 @@ class PhoneStatusPromptBuilderTest {
|
||||
credentialLockDetected = false,
|
||||
screenOn = true,
|
||||
)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot)
|
||||
val output = buildPromptBlock(defaultSettings, snapshot, phoneTools)
|
||||
assertNotNull(output)
|
||||
assertTrue(
|
||||
"expected permissions list; got: $output",
|
||||
output!!.contains("Permissions: accessibility, screen capture, overlay, notifications"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bridgeToolWithoutStatusTool_omitsUnavailableStatusToolAdvice() {
|
||||
val output = buildPromptBlock(
|
||||
defaultSettings,
|
||||
PhoneSnapshot(
|
||||
bridgeBound = true,
|
||||
masterEnabled = true,
|
||||
accessibilityGranted = true,
|
||||
screenOn = true,
|
||||
),
|
||||
availableTools = setOf("android_tap"),
|
||||
)
|
||||
|
||||
assertNotNull(output)
|
||||
assertTrue(output!!.contains("Phone bridge: enabled"))
|
||||
assertFalse(output.contains("android_phone_status"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.ToolsetInfo
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChatContextCapabilityTest {
|
||||
@Test
|
||||
fun mediaHint_prefersUpstreamAndFramesRelayAsEnhancement() {
|
||||
val hint = buildMediaCapabilityHint(
|
||||
upstreamAvailable = true,
|
||||
relayAvailable = true,
|
||||
)
|
||||
|
||||
assertTrue(hint!!.startsWith("Media display: this client supports standard upstream Hermes"))
|
||||
assertTrue(hint.contains("Relay enhancement:"))
|
||||
assertTrue(hint.contains("Relay is not required"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaHint_supportsStandardUpstreamWithoutRelay() {
|
||||
val hint = buildMediaCapabilityHint(
|
||||
upstreamAvailable = true,
|
||||
relayAvailable = false,
|
||||
)
|
||||
|
||||
assertTrue(hint!!.contains("authenticated upstream Dashboard file routes"))
|
||||
assertFalse(hint.contains("Relay enhancement:"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaHint_isAbsentWithoutAnyDeliveryRoute() {
|
||||
assertNull(
|
||||
buildMediaCapabilityHint(
|
||||
upstreamAvailable = false,
|
||||
relayAvailable = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sseToolCatalog_includesOnlyEnabledConfiguredToolsets() {
|
||||
val names = eligibleSseToolNames(
|
||||
listOf(
|
||||
ToolsetInfo(
|
||||
name = "android",
|
||||
enabled = true,
|
||||
configured = true,
|
||||
tools = listOf("android_phone_status", "android_tap"),
|
||||
),
|
||||
ToolsetInfo(
|
||||
name = "desktop",
|
||||
enabled = true,
|
||||
configured = false,
|
||||
tools = listOf("desktop_screenshot"),
|
||||
),
|
||||
ToolsetInfo(
|
||||
name = "terminal",
|
||||
enabled = false,
|
||||
configured = true,
|
||||
tools = listOf("terminal"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue(names == setOf("android_phone_status", "android_tap"))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -38,12 +40,54 @@ class ChatReadinessTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready with reachable API when Gateway is unavailable`() {
|
||||
fun `ready with reachable API for API-only owner`() {
|
||||
assertTrue(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
chatOwner = SessionTransport.SSE,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reachable API cannot make a Gateway-owned chat ready`() {
|
||||
assertFalse(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
chatOwner = SessionTransport.GATEWAY,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `eager status owner resolves from backing preference before public alias`() {
|
||||
val connection = Connection(
|
||||
id = "dashboard-owner",
|
||||
label = "Dashboard",
|
||||
apiServerUrl = "https://hermes.example.com:8642",
|
||||
relayUrl = "",
|
||||
tokenStoreKey = "test-key",
|
||||
dashboardUrl = "https://hermes.example.com:9119",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
SessionTransport.GATEWAY,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = null,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SessionTransport.SSE,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = SessionTransport.SSE,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,23 +28,25 @@ class ChatRuntimeStatusTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `API SSE ready is healthy fallback when gateway is unavailable`() {
|
||||
fun `API SSE ready is healthy only for an API-owned conversation`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready API fallback wins while gateway is still connecting`() {
|
||||
fun `ready sibling API cannot mask gateway auth expiry`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Unavailable,
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Connecting,
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.Gateway,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -63,6 +65,7 @@ class ChatRuntimeStatusTest {
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Connecting,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+232
-1
@@ -195,7 +195,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(STORED_SESSION_ID, failure?.sessionId)
|
||||
assertEquals(ChatFailureRoute.GATEWAY, failure?.route)
|
||||
assertTrue(failure?.recoverable == true)
|
||||
assertTrue(failure?.rawError.orEmpty().contains("no API fallback"))
|
||||
assertTrue(failure?.rawError.orEmpty().contains("belongs to the Hermes Dashboard"))
|
||||
assertEquals("Retry this after reconnect", handler.lastSentMessage.value)
|
||||
assertTrue(handler.messages.value.isEmpty())
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Session), 1).single()
|
||||
@@ -238,6 +238,63 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals("gateway", diagnostic.endpointRole)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
|
||||
DiagnosticsLog.clear()
|
||||
apiMessageRequestCount.set(0)
|
||||
val owner = Profile(name = "owner", model = "model-a", description = "Owner")
|
||||
val requestedProfiles = mutableListOf<String?>()
|
||||
val sessionRefreshes = AtomicInteger(0)
|
||||
val signInRequests = AtomicInteger(0)
|
||||
viewModel.setSelectedProfileProvider { owner }
|
||||
viewModel.setSessionProfileNameProvider { owner.name }
|
||||
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
|
||||
requestedProfiles += profileName
|
||||
assertEquals(STORED_SESSION_ID, sessionId)
|
||||
Result.failure(
|
||||
DashboardHttpException(401, "Session failed - HTTP 401: Unauthorized"),
|
||||
)
|
||||
}
|
||||
viewModel.setProfileSessionLister { profileName ->
|
||||
assertEquals(owner.name, profileName)
|
||||
sessionRefreshes.incrementAndGet()
|
||||
Result.success(emptyList())
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
|
||||
|
||||
viewModel.sendMessage("Keep this local prompt")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "Keep this local answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "Keep this local answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition {
|
||||
!handler.isStreaming.value &&
|
||||
signInRequests.get() == 1 &&
|
||||
sessionRefreshes.get() >= 1
|
||||
}
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local prompt" })
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local answer" })
|
||||
assertEquals(listOf(owner.name), requestedProfiles)
|
||||
assertEquals(0, apiMessageRequestCount.get())
|
||||
assertFalse(viewModel.steerableTurn.value)
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
|
||||
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
|
||||
assertTrue(diagnostic.suggestion.orEmpty().contains("Sign in to Dashboard"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingRequiredProfileHistoryLoaderFailsClosedWithoutApiRead() {
|
||||
DiagnosticsLog.clear()
|
||||
@@ -1593,6 +1650,39 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(gatewayClient.hasActiveTurn())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnedConversationDoesNotDispatchToReachableApiWhenGatewayIsMissing() {
|
||||
viewModel.streamingEndpoint = "gateway"
|
||||
viewModel.updateGatewayClient(null)
|
||||
val apiRequestsBefore = apiCompletionsRequestCount.get()
|
||||
|
||||
viewModel.sendMessage("Keep this turn on Victor")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
assertEquals(apiRequestsBefore, apiCompletionsRequestCount.get())
|
||||
assertTrue(handler.messages.value.none { it.role == MessageRole.ASSISTANT })
|
||||
assertEquals(
|
||||
ChatFailureRoute.GATEWAY,
|
||||
viewModel.chatFailure.value?.route,
|
||||
)
|
||||
assertEquals(STORED_SESSION_ID, handler.currentSessionId.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun boundGatewaySessionRejectsAResolverTransportFlipUntilExplicitNewChat() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
|
||||
viewModel.streamingEndpoint = "sessions"
|
||||
|
||||
assertEquals("gateway", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.GATEWAY, viewModel.conversationBinding.value.transport)
|
||||
|
||||
viewModel.createNewChat()
|
||||
|
||||
assertEquals("sessions", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.SSE, viewModel.conversationBinding.value.transport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayRichCardActionStaysOnGatewayInsteadOfDrainingThroughSessionsApi() {
|
||||
viewModel.sseFallbackEndpoint = "sessions"
|
||||
@@ -2746,6 +2836,92 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveredCompletionUnauthorizedHistoryPreservesTranscriptAndRunsCleanup() {
|
||||
DiagnosticsLog.clear()
|
||||
apiMessageRequestCount.set(0)
|
||||
val checkpointStore = MemoryCheckpointStore(
|
||||
ChatTurnCheckpoint(
|
||||
contextKey = PROFILE_CONTEXT,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
liveSessionId = "live-resumed",
|
||||
transport = "gateway",
|
||||
user = ChatTurnUserCheckpoint("prior-user", "Recovered prompt", 1L),
|
||||
assistant = ChatTurnAssistantCheckpoint(
|
||||
id = "prior-assistant",
|
||||
content = "Recovered partial",
|
||||
timestamp = 2L,
|
||||
),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
startedAt = 2L,
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
val requestedProfiles = mutableListOf<String?>()
|
||||
val sessionRefreshes = AtomicInteger(0)
|
||||
val signInRequests = AtomicInteger(0)
|
||||
var failHistory = false
|
||||
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
|
||||
requestedProfiles += profileName
|
||||
assertEquals(STORED_SESSION_ID, sessionId)
|
||||
if (failHistory) {
|
||||
Result.failure(
|
||||
DashboardHttpException(
|
||||
401,
|
||||
"Session failed - HTTP 401: {\"reason\":\"session_expired\"}",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
Result.success(emptyList())
|
||||
}
|
||||
}
|
||||
viewModel.setProfileSessionLister { profileName ->
|
||||
assertNull(profileName)
|
||||
sessionRefreshes.incrementAndGet()
|
||||
Result.success(emptyList())
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler { signInRequests.incrementAndGet() }
|
||||
gatewayHarness.recoveryRunning = true
|
||||
gatewayHarness.recoveryAssistant = "Recovered partial"
|
||||
viewModel.setChatTurnCheckpointStore(checkpointStore)
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
|
||||
viewModel.prewarmGateway()
|
||||
gatewayHarness.awaitRpc("session.activate")
|
||||
awaitCondition {
|
||||
handler.messages.value.any { it.id == "prior-assistant" && it.isStreaming }
|
||||
}
|
||||
failHistory = true
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "Recovered answer") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition {
|
||||
!handler.isStreaming.value &&
|
||||
signInRequests.get() == 1 &&
|
||||
sessionRefreshes.get() >= 1
|
||||
}
|
||||
assertTrue(handler.messages.value.any {
|
||||
it.id == "prior-assistant" &&
|
||||
it.content.contains("Recovered answer") &&
|
||||
!it.isStreaming
|
||||
})
|
||||
assertTrue(requestedProfiles.isNotEmpty())
|
||||
assertTrue(requestedProfiles.all { it == null })
|
||||
assertEquals(0, apiMessageRequestCount.get())
|
||||
assertFalse(viewModel.steerableTurn.value)
|
||||
awaitCondition { checkpointStore.checkpoint == null }
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Auth), 1).single()
|
||||
assertEquals("Dashboard sign-in required for chat history", diagnostic.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lateCanceledCompletionDrainsBeforeImmediateNextTurn() {
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
@@ -2838,6 +3014,51 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedCorrectionDrainsOnceAfterOwnedTurnSettlesFromActiveSessionIdle() = runBlocking {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
gatewayHarness.redirectStatus = "rejected"
|
||||
viewModel.sendMessage("Original Android turn")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "Answer without terminal") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { handler.isStreaming.value }
|
||||
|
||||
viewModel.sendMessage("Queued correction")
|
||||
gatewayHarness.awaitRpc("session.redirect")
|
||||
awaitCondition { viewModel.queuedMessages.value == listOf("Queued correction") }
|
||||
persistedHistory = persistedAnswerHistory("Answer without terminal", "settled-answer")
|
||||
gatewayHarness.activeSessionListPayload = buildJsonObject {
|
||||
put("sessions", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("id", "live-resumed")
|
||||
put("session_key", STORED_SESSION_ID)
|
||||
put("status", "idle")
|
||||
put("last_active", 1_777_000_000.0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
gatewayClient.listActiveSessions()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { (method, params) ->
|
||||
method == "prompt.submit" &&
|
||||
params["text"] == JsonPrimitive("Queued correction") &&
|
||||
params["queued"] == JsonPrimitive(true)
|
||||
} == 1
|
||||
}
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
assertTrue(viewModel.steerableTurn.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multipleQueuedMessagesDrainAsAnOwnedRunChain() {
|
||||
viewModel.switchProfileContext(
|
||||
@@ -3596,6 +3817,16 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { it.first == "session.active_list" } > baselineActiveList
|
||||
}
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.Working
|
||||
}
|
||||
gatewayHarness.activeSessionListPayload = activeSessionPayload("waiting")
|
||||
viewModel.requestSessionActivityRefresh()
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.NeedsInput
|
||||
}
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = "desktop-answer",
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MediaSettingsRepository
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.util.MediaCacheWriter
|
||||
import io.mockk.coEvery
|
||||
@@ -30,6 +31,7 @@ import org.robolectric.annotation.Config
|
||||
class ChatViewModelMediaStateTest {
|
||||
|
||||
private lateinit var server: MockWebServer
|
||||
private lateinit var dashboardServer: MockWebServer
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var cache: MediaCacheWriter
|
||||
@@ -37,6 +39,7 @@ class ChatViewModelMediaStateTest {
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().apply { start() }
|
||||
dashboardServer = MockWebServer().apply { start() }
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val relay = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
@@ -46,6 +49,7 @@ class ChatViewModelMediaStateTest {
|
||||
.trimEnd('/')
|
||||
},
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
pairedTokenSnapshot = { "paired-session" },
|
||||
)
|
||||
cache = mockk()
|
||||
coEvery { cache.cache(any(), any(), any()) } returns
|
||||
@@ -66,6 +70,7 @@ class ChatViewModelMediaStateTest {
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
dashboardServer.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,6 +156,175 @@ class ChatViewModelMediaStateTest {
|
||||
assertEquals(windowsPath, request.requestUrl?.queryParameter("path"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun assistantBarePathPrefersAuthenticatedUpstreamDashboardDownload() {
|
||||
val path = "/tmp/test-voice-message.mp3"
|
||||
dashboardServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "audio/mpeg")
|
||||
.setHeader("Content-Disposition", "attachment; filename=\"test-voice-message.mp3\"")
|
||||
.setBody("voice-bytes"),
|
||||
)
|
||||
viewModel.cellularNetworkOverride = false
|
||||
viewModel.initializeMedia(
|
||||
context = RuntimeEnvironment.getApplication(),
|
||||
relayHttpClient = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { server.url("/").toString().replaceFirst("http://", "ws://").trimEnd('/') },
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
pairedTokenSnapshot = { "paired-session" },
|
||||
),
|
||||
mediaSettingsRepo = MediaSettingsRepository(RuntimeEnvironment.getApplication()),
|
||||
mediaCacheWriter = cache,
|
||||
dashboardMediaClientProvider = {
|
||||
DashboardApiClient(baseUrl = dashboardServer.url("/").toString())
|
||||
},
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-audio-upstream",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Voice reply\nMEDIA:$path"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val loaded = awaitMessage {
|
||||
it.attachments.singleOrNull()?.state == AttachmentState.LOADED
|
||||
}.attachments.single()
|
||||
assertEquals("audio/mpeg", loaded.contentType)
|
||||
assertEquals("test-voice-message.mp3", loaded.fileName)
|
||||
val request = dashboardServer.takeRequest()
|
||||
assertEquals("/api/files/download", request.requestUrl?.encodedPath)
|
||||
assertEquals(path, request.requestUrl?.queryParameter("path"))
|
||||
assertEquals(0, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun assistantBarePathWithoutUpstreamOrRelaySettlesAsNeutralHostFile() {
|
||||
viewModel.cellularNetworkOverride = false
|
||||
viewModel.initializeMedia(
|
||||
context = RuntimeEnvironment.getApplication(),
|
||||
relayHttpClient = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { null },
|
||||
sessionTokenProvider = { null },
|
||||
),
|
||||
mediaSettingsRepo = MediaSettingsRepository(RuntimeEnvironment.getApplication()),
|
||||
mediaCacheWriter = cache,
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-file-unavailable",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("MEDIA:/tmp/result.zip"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val unavailable = awaitMessage {
|
||||
it.attachments.singleOrNull()?.errorMessage == ChatViewModel.MEDIA_HOST_ONLY
|
||||
}.attachments.single()
|
||||
assertEquals(AttachmentState.FAILED, unavailable.state)
|
||||
assertEquals("result.zip", unavailable.fileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun assistantBarePathFallsBackToRelayWhenUpstreamRouteIsUnavailable() {
|
||||
val path = "/tmp/legacy-host-image.png"
|
||||
dashboardServer.enqueue(MockResponse().setResponseCode(404).setBody("not found"))
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "image/png")
|
||||
.setHeader("Content-Disposition", "inline; filename=\"legacy-host-image.png\"")
|
||||
.setBody("image-bytes"),
|
||||
)
|
||||
viewModel.cellularNetworkOverride = false
|
||||
viewModel.initializeMedia(
|
||||
context = RuntimeEnvironment.getApplication(),
|
||||
relayHttpClient = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { server.url("/").toString().replaceFirst("http://", "ws://").trimEnd('/') },
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
pairedTokenSnapshot = { "paired-session" },
|
||||
),
|
||||
mediaSettingsRepo = MediaSettingsRepository(RuntimeEnvironment.getApplication()),
|
||||
mediaCacheWriter = cache,
|
||||
dashboardMediaClientProvider = {
|
||||
DashboardApiClient(baseUrl = dashboardServer.url("/").toString())
|
||||
},
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-image-fallback",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("MEDIA:$path"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val loaded = awaitMessage {
|
||||
it.attachments.singleOrNull()?.state == AttachmentState.LOADED
|
||||
}.attachments.single()
|
||||
assertEquals("image/png", loaded.contentType)
|
||||
assertEquals("/api/files/download", dashboardServer.takeRequest().requestUrl?.encodedPath)
|
||||
assertEquals("/media/by-path", server.takeRequest().requestUrl?.encodedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun assistantBarePathDoesNotBypassUpstreamSensitiveFileDenial() {
|
||||
val path = "/home/user/.ssh/id_ed25519"
|
||||
dashboardServer.enqueue(MockResponse().setResponseCode(403).setBody("sensitive file"))
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "application/octet-stream")
|
||||
.setBody("must-not-be-fetched"),
|
||||
)
|
||||
viewModel.cellularNetworkOverride = false
|
||||
viewModel.initializeMedia(
|
||||
context = RuntimeEnvironment.getApplication(),
|
||||
relayHttpClient = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { server.url("/").toString().replaceFirst("http://", "ws://").trimEnd('/') },
|
||||
sessionTokenProvider = { "paired-session" },
|
||||
pairedTokenSnapshot = { "paired-session" },
|
||||
),
|
||||
mediaSettingsRepo = MediaSettingsRepository(RuntimeEnvironment.getApplication()),
|
||||
mediaCacheWriter = cache,
|
||||
dashboardMediaClientProvider = {
|
||||
DashboardApiClient(baseUrl = dashboardServer.url("/").toString())
|
||||
},
|
||||
)
|
||||
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-sensitive-denied",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("MEDIA:$path"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val denied = awaitMessage {
|
||||
it.attachments.singleOrNull()?.let { attachment ->
|
||||
attachment.state == AttachmentState.FAILED && attachment.errorMessage != null
|
||||
} == true
|
||||
}.attachments.single()
|
||||
assertEquals(AttachmentState.FAILED, denied.state)
|
||||
assertEquals(1, dashboardServer.requestCount)
|
||||
assertEquals(0, server.requestCount)
|
||||
}
|
||||
|
||||
private fun awaitMessage(predicate: (ChatMessage) -> Boolean): ChatMessage {
|
||||
val deadline = System.nanoTime() + 5_000_000_000L
|
||||
while (System.nanoTime() < deadline) {
|
||||
|
||||
+37
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -112,4 +113,40 @@ class ConversationBindingControllerTest {
|
||||
assertEquals("alpha", controller.state.value.profileName)
|
||||
assertEquals("a1", controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnerSurvivesSessionClearAndLifecycleReconciliation() {
|
||||
controller.forceGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = "20260831_120000_deadbeef",
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
controller.startFreshDraft()
|
||||
controller.reconcileGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = null,
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.state.value.transport)
|
||||
assertNull(controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitApiSessionKeepsItsCompatibilityOwner() {
|
||||
controller.openExplicit(
|
||||
contextKey = "c::default",
|
||||
profileName = null,
|
||||
sessionId = "api_1788192000_deadbeef",
|
||||
displayProfile = null,
|
||||
lockedProfileToken = null,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
controller.switchSession(null)
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
}
|
||||
}
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAgentNotice
|
||||
import com.hermesandroid.relay.ui.UiMessageBus
|
||||
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GatewayNoticePresentationTest {
|
||||
@Test
|
||||
fun stickyWarningStripsDuplicateGlyphAndKeepsKey() {
|
||||
val presentation = gatewayNoticePresentation(
|
||||
GatewayAgentNotice(
|
||||
text = "⚠ Credits depleted",
|
||||
level = "warn",
|
||||
kind = "sticky",
|
||||
key = "credits.depleted",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("Credits depleted", presentation.text)
|
||||
assertEquals(UiMessageSeverity.Warning, presentation.severity)
|
||||
assertEquals(0L, presentation.ttlMillis)
|
||||
assertEquals("credits.depleted", presentation.key)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ttlNoticeUsesIdFallbackAndBoundsLifetime() {
|
||||
val presentation = gatewayNoticePresentation(
|
||||
GatewayAgentNotice(
|
||||
text = " ✓ Credits restored ",
|
||||
level = "success",
|
||||
kind = "ttl",
|
||||
ttlMs = 600_000L,
|
||||
id = "notice-2",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("Credits restored", presentation.text)
|
||||
assertEquals(UiMessageSeverity.Success, presentation.severity)
|
||||
assertEquals(60_000L, presentation.ttlMillis)
|
||||
assertEquals("notice-2", presentation.key)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ttlWithoutDurationUsesExistingBannerDefault() {
|
||||
val presentation = gatewayNoticePresentation(
|
||||
GatewayAgentNotice(text = "Account update", kind = "ttl"),
|
||||
)
|
||||
|
||||
assertEquals(UiMessageBus.DEFAULT_TTL_MS, presentation.ttlMillis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun agentNoticePersistsUntilGatewayClearsItsKey() {
|
||||
val presentation = gatewayNoticePresentation(
|
||||
GatewayAgentNotice(
|
||||
text = "Still starting agent",
|
||||
kind = "agent",
|
||||
key = "agent-startup",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(0L, presentation.ttlMillis)
|
||||
assertEquals("agent-startup", presentation.key)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.data.GitRepositoryRoute
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
@@ -56,21 +57,29 @@ class GitStateViewModelTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `disabled configuration does not discover repositories until enabled`() = runBlocking {
|
||||
enqueueJson("""{"repos":[]}""")
|
||||
fun `disabled Relay discovery still loads standard session repository`() = runBlocking {
|
||||
enqueueJson("""{"branch":"main","changed":0,"staged":0,"unstaged":0,"untracked":0,"files":[]}""")
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(
|
||||
DashboardApiClient(server.url("/").toString()),
|
||||
ownerKey,
|
||||
scanningEnabled = false,
|
||||
)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = null)
|
||||
|
||||
vm.loadRepos()
|
||||
assertEquals(0, server.requestCount)
|
||||
val standard = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
assertEquals(GitRepositoryRoute.UPSTREAM, standard.repos.single().route)
|
||||
assertEquals("/api/git/status?path=%2Fworkspace%2Frepo", server.takeRequest().path)
|
||||
assertEquals(1, server.requestCount)
|
||||
|
||||
enqueueJson("""{"branch":"main","changed":0,"staged":0,"unstaged":0,"untracked":0,"files":[]}""")
|
||||
enqueueJson("""{"repos":[]}""")
|
||||
vm.setScanningEnabled(true)
|
||||
vm.loadRepos()
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
assertEquals("/api/git/status?path=%2Fworkspace%2Frepo", server.takeRequest().path)
|
||||
assertEquals("/api/plugins/hermes-relay/git/repos", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@@ -203,4 +212,141 @@ class GitStateViewModelTest {
|
||||
}
|
||||
assertTrue(error.message.contains("unknown repository"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session repository uses upstream Git without Relay`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"branch":"main","changed":2,"staged":0,"unstaged":1,"untracked":1,"added":7,"removed":2,"files":[]}""",
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(404).setBody("""{"detail":"No such API endpoint"}"""),
|
||||
)
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey, scanningEnabled = true)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = "/workspace/repo/src")
|
||||
vm.loadRepos()
|
||||
|
||||
val ready = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
assertEquals(1, ready.repos.size)
|
||||
assertEquals(GitRepositoryRoute.UPSTREAM, ready.repos.single().route)
|
||||
assertEquals("/workspace/repo", ready.repos.single().root)
|
||||
assertEquals("/api/git/status?path=%2Fworkspace%2Frepo", server.takeRequest().path)
|
||||
assertEquals("/api/plugins/hermes-relay/git/repos", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `standard session repository can be selected while Relay discovery is off`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"branch":"main","changed":1,"staged":0,"unstaged":1,"untracked":0,"added":2,"removed":0,"files":[{"path":"a.kt","unstaged":true}]}""",
|
||||
)
|
||||
enqueueJson(
|
||||
"""{"branch":"main","changed":1,"staged":0,"unstaged":1,"untracked":0,"added":2,"removed":0,"files":[{"path":"a.kt","unstaged":true}]}""",
|
||||
)
|
||||
enqueueJson("""{"files":[{"path":"a.kt","added":2,"removed":0,"staged":false}]}""")
|
||||
enqueueJson("""{"branches":[{"name":"main","checkedOut":true}]}""")
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey, scanningEnabled = false)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = null)
|
||||
vm.loadRepos()
|
||||
val repos = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
|
||||
vm.selectRepo(repos.repos.single().id)
|
||||
val detail = withTimeout(5_000) {
|
||||
vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first()
|
||||
}
|
||||
assertEquals("a.kt", detail.status.modified.single().path)
|
||||
assertNotNull(vm.currentTarget())
|
||||
assertEquals(4, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upstream operational failure does not downgrade to Relay`() = runBlocking {
|
||||
server.enqueue(MockResponse().setResponseCode(500).setBody("""{"detail":"git crashed"}"""))
|
||||
enqueueJson(
|
||||
"""{"repos":[{"id":"alpha","name":"alpha","root":"/workspace/repo"}]}""",
|
||||
)
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey, scanningEnabled = true)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = null)
|
||||
vm.loadRepos()
|
||||
|
||||
val error = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Error>().first()
|
||||
}
|
||||
assertTrue(error.message.contains("HTTP 500"))
|
||||
assertEquals(1, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upstream session status maps official review and branch shapes`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"branch":"feature/x","changed":2,"staged":1,"unstaged":1,"untracked":0,"added":9,"removed":3,"files":[{"path":"a.kt","staged":true},{"path":"b.kt","unstaged":true}]}""",
|
||||
)
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"plugin absent"}"""))
|
||||
enqueueJson(
|
||||
"""{"branch":"feature/x","changed":2,"staged":1,"unstaged":1,"untracked":0,"added":9,"removed":3,"files":[{"path":"a.kt","staged":true},{"path":"b.kt","unstaged":true}]}""",
|
||||
)
|
||||
enqueueJson(
|
||||
"""{"files":[{"path":"a.kt","added":5,"removed":1,"staged":true},{"path":"b.kt","added":4,"removed":2,"staged":false}],"base":null}""",
|
||||
)
|
||||
enqueueJson(
|
||||
"""{"branches":[{"name":"feature/x","checkedOut":true,"isDefault":false,"isRemote":false,"worktreePath":"/workspace/repo"}]}""",
|
||||
)
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey, scanningEnabled = true)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = null)
|
||||
vm.loadRepos()
|
||||
val repos = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
|
||||
vm.selectRepo(repos.repos.single().id)
|
||||
val detail = withTimeout(5_000) {
|
||||
vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first()
|
||||
}
|
||||
assertEquals(2, detail.status.counts.changes)
|
||||
assertEquals(9, detail.status.counts.additions)
|
||||
assertEquals(3, detail.status.counts.deletions)
|
||||
assertEquals("a.kt", detail.status.staged.single().path)
|
||||
assertEquals("b.kt", detail.status.modified.single().path)
|
||||
assertTrue(detail.branches.single().isCurrent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing upstream read route falls back to matching Relay repository`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"branch":"main","changed":1,"staged":0,"unstaged":1,"untracked":0,"files":[]}""",
|
||||
)
|
||||
enqueueJson(
|
||||
"""{"repos":[{"id":"relay-alpha","name":"repo","root":"/workspace/repo","current_branch":"main","dirty":true}]}""",
|
||||
)
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"route unavailable"}"""))
|
||||
enqueueJson(
|
||||
"""{"counts":{"staged":0,"modified":1,"untracked":0},"staged":[],"modified":[{"path":"a.kt"}],"untracked":[],"truncated":false}""",
|
||||
)
|
||||
enqueueJson(
|
||||
"""{"branches":[{"name":"main","checkedOut":true,"isDefault":true,"isRemote":false,"worktreePath":"/workspace/repo"}]}""",
|
||||
)
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey, scanningEnabled = true)
|
||||
vm.setSessionWorkspace(repoRoot = "/workspace/repo", workingDirectory = null)
|
||||
vm.loadRepos()
|
||||
val repos = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
|
||||
vm.selectRepo(repos.repos.single().id)
|
||||
val detail = withTimeout(5_000) {
|
||||
vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first()
|
||||
}
|
||||
assertEquals("a.kt", detail.status.modified.single().path)
|
||||
val paths = buildList {
|
||||
repeat(5) { add(server.takeRequest().path.orEmpty()) }
|
||||
}
|
||||
assertTrue(paths.contains("/api/plugins/hermes-relay/git/status?repo=relay-alpha"))
|
||||
}
|
||||
}
|
||||
|
||||
+24
-2
@@ -5,6 +5,7 @@ import com.hermesandroid.relay.data.SessionLiveStatus
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSession
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSessionStatus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -40,14 +41,35 @@ class SessionActivityResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unscoped stored id stays unresolved even when bounded directory looks unique`() {
|
||||
fun `unique selected passive owner resolves without a runtime binding`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Starting,
|
||||
status = GatewayActiveSessionStatus.Waiting,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
directory = setOf(alpha, unique),
|
||||
currentOwner = unique,
|
||||
)
|
||||
|
||||
assertEquals(unique, result.runtimes.single().owner)
|
||||
assertEquals(SessionLiveStatus.Waiting, result.runtimes.single().status)
|
||||
assertFalse(result.ambiguous)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unique passive owner for a nonselected session stays unresolved`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Working,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
|
||||
+5
-2
@@ -118,7 +118,7 @@ class ProfileControllerLockTest {
|
||||
// (no gateway probe gating) — keeps refreshLastSessionForProfile from
|
||||
// bailing early on Unknown.
|
||||
streamingEndpointProvider = { streamingEndpoint },
|
||||
gatewayAvailabilityProvider = { gatewayAvailability },
|
||||
automaticTransportProvider = { SessionTransport.GATEWAY },
|
||||
setLastSessionId = { lastSessionIds += it },
|
||||
legacyDefaultSessionId = { null },
|
||||
rebuildChatApiClient = { },
|
||||
@@ -208,13 +208,16 @@ class ProfileControllerLockTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoUnknownRestoresGatewayBucketUntilDefinitiveFallback() {
|
||||
fun autoGatewayOwnerDoesNotChangeRestoreBucketAfterOutage() {
|
||||
streamingEndpoint = "auto"
|
||||
gatewayAvailability = GatewayAvailability.Unknown
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
gatewayAvailability = GatewayAvailability.Unreachable
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
streamingEndpoint = "sessions"
|
||||
assertEquals(SessionTransport.SSE, controller.activeSessionTransport())
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 71 KiB After Width: | Height: | Size: 662 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 201 KiB |
@@ -26,17 +26,23 @@ Check recent runs before dispatching so another task does not duplicate the
|
||||
same SHA and preset:
|
||||
|
||||
```powershell
|
||||
gh run list --workflow android-on-demand.yml --event workflow_dispatch --limit 20
|
||||
$base = git merge-base origin/dev HEAD
|
||||
$sha = git rev-parse HEAD
|
||||
gh workflow run android-on-demand.yml --ref dev -f head_sha=$sha -f preset=focused
|
||||
gh run list --workflow android-on-demand.yml --event workflow_dispatch --limit 5
|
||||
gh run list --workflow ci-required.yml --event workflow_dispatch --limit 20
|
||||
gh workflow run ci-required.yml --ref dev `
|
||||
-f base_sha=$base `
|
||||
-f head_sha=$sha `
|
||||
-f android_preset=focused
|
||||
gh run list --workflow ci-required.yml --event workflow_dispatch --limit 5
|
||||
```
|
||||
|
||||
The SHA must already exist on GitHub. Do not push solely to obtain cloud compute
|
||||
without push authorization. On-demand jobs read shared Gradle cache state but
|
||||
do not write it, so task commits cannot replace the cache populated by trusted
|
||||
`dev`/`main` CI. The on-demand result supplements rather than replaces required
|
||||
PR checks.
|
||||
PR checks. `Required checks` is the registered dispatcher because GitHub only
|
||||
registers manual workflow entry points from the default branch; it calls the
|
||||
Android workflow from the selected `dev` ref.
|
||||
|
||||
## Local use
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Android emulator testing
|
||||
|
||||
Hermes-Relay Android uses individually selected Gradle Managed Devices for
|
||||
repeatable, on-demand instrumentation. The routine virtual baseline is API 36.
|
||||
There is deliberately no aggregate matrix task and no scheduled emulator job:
|
||||
choose the smallest lane that can prove the behavior under review.
|
||||
|
||||
## Lanes
|
||||
|
||||
| Evidence lane | Gradle device | Hardware profile | Use it for |
|
||||
|---|---|---|---|
|
||||
| Real Device | None | Explicitly selected physical hardware | Firmware, radio, audio, camera, biometrics, background limits, accessibility, and release-candidate claims |
|
||||
| Compact Phone | `compactPhoneApi36` | Pixel 2 | Narrow phone layouts, compact height, keyboard pressure |
|
||||
| Standard Phone | `standardPhoneApi36` | Pixel 6 | Default functional and regression instrumentation |
|
||||
| Large Phone | `largePhoneApi36` | Pixel 7 Pro | Large handset layout and reachability |
|
||||
| Foldable | `foldableApi36` | Pixel Fold | Fold/unfold, posture, continuity, and width-class changes |
|
||||
| Tablet | `tabletApi36` | Pixel Tablet | Expanded layout, panes, and large-window behavior |
|
||||
| Future platform / native canary | `futureApi37Ps16k` | Pixel 7 Pro, API 37, forced 16 KB pages | On-demand platform and native-library compatibility only |
|
||||
|
||||
Routine API 36 lanes use the AOSP x86_64 image so deterministic app tests do not
|
||||
spend host capacity on unrelated Google-service startup. The API 37/16 KB device
|
||||
is not a screen-size lane and is not part of routine testing. Gradle Managed
|
||||
Devices may download a missing image on first use; that setup can be large and
|
||||
slow.
|
||||
|
||||
## Commands
|
||||
|
||||
List the registered tasks:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle :app:tasks --all |
|
||||
Select-String 'Api36|Ps16k'
|
||||
```
|
||||
|
||||
Compile the app and instrumentation APK without starting an emulator:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:assembleSideloadDebug `
|
||||
:app:assembleSideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run one complete lane, normally Standard Phone first:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:standardPhoneApi36SideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run one test class on one lane:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:standardPhoneApi36SideloadDebugAndroidTest `
|
||||
'-Pandroid.testInstrumentationRunnerArguments.class=com.hermesandroid.relay.viewmodel.GatewayForegroundRecoveryInstrumentedTest'
|
||||
```
|
||||
|
||||
Run the other virtual lanes only when their form factor is relevant:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle :app:compactPhoneApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:largePhoneApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:foldableApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:tabletApi36SideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run the future-platform/native canary explicitly:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:futureApi37Ps16kSideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
All Windows commands use the repository's machine-wide build lane; see
|
||||
[`docs/android-build-lane.md`](android-build-lane.md). Check the lane without
|
||||
starting work with:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 status
|
||||
```
|
||||
|
||||
Do not invoke every device task as one command. Run lanes serially, record each
|
||||
result, and stop when the relevant evidence is complete or the host reaches a
|
||||
capacity limit.
|
||||
|
||||
## Configuration coverage
|
||||
|
||||
Form factor is only one axis. Select additional states according to the change:
|
||||
|
||||
- Test dark mode first; also cover light mode when colors, contrast, system bars,
|
||||
or theme persistence changed.
|
||||
- Cover portrait and landscape when layout, keyboard, media, drawers, or panes
|
||||
changed. Foldable work must include a posture or width-class transition.
|
||||
- Check default font scale and at least one enlarged scale for text-heavy or
|
||||
accessibility-sensitive UI.
|
||||
- Use the default locale for functional regressions; add a long-string locale
|
||||
and an RTL locale when copy, formatting, or layout direction changed.
|
||||
- Record gesture versus three-button navigation when bottom insets, edge-to-edge,
|
||||
back handling, sheets, or overlays changed.
|
||||
|
||||
These dimensions are selected test conditions, not permanent duplicated device
|
||||
definitions. Record any non-default setting in the evidence.
|
||||
|
||||
## Deterministic fixtures and live servers
|
||||
|
||||
Embedded MockWebServer tests own deterministic transport regressions. They use
|
||||
production clients and view models against loopback HTTP/WebSocket boundaries,
|
||||
require no credentials, mutate no real sessions, and are the correct lane for
|
||||
authentication loss, reconnect gaps, malformed frames, profile isolation, and
|
||||
repeatable lifecycle assertions.
|
||||
|
||||
Live-server testing is separate and on demand. Use a disposable test or staging
|
||||
Hermes server with disposable profiles and sessions. Normally run only the
|
||||
Standard Phone emulator plus one explicitly selected real device when physical
|
||||
evidence is required. Never multiply live mutation testing across the full size
|
||||
matrix, use a production server, or use personal conversation data. Sanitize
|
||||
logs and exports before attaching them to a pull request.
|
||||
|
||||
## Evidence
|
||||
|
||||
For each executed lane, record:
|
||||
|
||||
```text
|
||||
Commit: <exact SHA>
|
||||
Artifact/variant: sideloadDebug app + androidTest
|
||||
Lane: Standard Phone (standardPhoneApi36), API 36
|
||||
Test selection: <class or package>
|
||||
Configuration: dark/light, orientation/posture, font scale, locale, navigation
|
||||
Result: pass/fail/blocked, test count, report path
|
||||
Notes: retries, emulator/image limitation, relevant sanitized observation
|
||||
```
|
||||
|
||||
Keep claims lane-specific. Emulator proof is not physical-device proof. A
|
||||
passing API 37/16 KB canary proves only that selected platform/native lane; it
|
||||
does not replace API 36 form-factor coverage or physical firmware evidence.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user