Compare commits
111
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb2f1e6c0c | ||
|
|
ff23d54332 | ||
|
|
a4a0575688 | ||
|
|
0509ac8377 | ||
|
|
3fdc2260dd | ||
|
|
1800bee7b1 | ||
|
|
4317b7c2b3 | ||
|
|
93fb30150e | ||
|
|
faf4281486 | ||
|
|
11dcafc2fe | ||
|
|
a57b2b66a1 | ||
|
|
f4acd351f5 | ||
|
|
8ee772f5fb | ||
|
|
6c27bc9cda | ||
|
|
460d6cd198 | ||
|
|
ce63030bcf | ||
|
|
bd9c077599 | ||
|
|
92f99a4120 | ||
|
|
85ba13bd04 | ||
|
|
81347e9c28 | ||
|
|
8d260c0eeb | ||
|
|
ea982c60d4 | ||
|
|
8f394e8b18 | ||
|
|
841e237905 | ||
|
|
6aad90144f | ||
|
|
c5df87cd28 | ||
|
|
01533337eb | ||
|
|
a4a0fb5741 | ||
|
|
a2ed48ab20 | ||
|
|
ef280979e9 | ||
|
|
0bb0a1e3e2 | ||
|
|
6421d47c96 | ||
|
|
523794995a | ||
|
|
1c9af237fb | ||
|
|
ea7c7cd3e2 | ||
|
|
41fa23a7f9 | ||
|
|
c6ad31972c | ||
|
|
7091fd7a4a | ||
|
|
9b903c87dc | ||
|
|
a05cc3c941 | ||
|
|
6dfa94b65e | ||
|
|
cef0771980 | ||
|
|
b900148f7f | ||
|
|
291fe2e88b | ||
|
|
e629cb4947 | ||
|
|
74100fb249 | ||
|
|
8aa27d6084 | ||
|
|
a894da5fda | ||
|
|
17446f13d0 | ||
|
|
89f2f772e2 | ||
|
|
3ae19758e4 | ||
|
|
734f8074d5 | ||
|
|
46502c1785 | ||
|
|
70b9c4e4e3 | ||
|
|
5e10864795 | ||
|
|
c8351e03c1 | ||
|
|
808dfd12a5 | ||
|
|
9ce41e366a | ||
|
|
4884d077b3 | ||
|
|
f47ca00998 | ||
|
|
e23ab3fbdf | ||
|
|
b862a0a875 | ||
|
|
318a02db49 | ||
|
|
80e636bc30 | ||
|
|
578c074797 | ||
|
|
23fa69e8d1 | ||
|
|
d688043a52 | ||
|
|
10f62d798c | ||
|
|
d80b3db329 | ||
|
|
d1e78f7e1c | ||
|
|
a1d8419dcd | ||
|
|
258e6f5390 | ||
|
|
76ead50c60 | ||
|
|
3bddb6fc70 | ||
|
|
729d9ea620 | ||
|
|
0ef67814cf | ||
|
|
ee3b31d8ea | ||
|
|
6e95f6fe83 | ||
|
|
08ef5cd08e | ||
|
|
e483617c09 | ||
|
|
95aca51bd5 | ||
|
|
eb94bc92f2 | ||
|
|
4c0b3038de | ||
|
|
380a604ba5 | ||
|
|
20d7bfe633 | ||
|
|
68520549a1 | ||
|
|
711b2f945b | ||
|
|
526c5be5ae | ||
|
|
8e2f7d7084 | ||
|
|
ee98432095 | ||
|
|
b432e90dc0 | ||
|
|
aab1555004 | ||
|
|
a5ec94f669 | ||
|
|
7621b762e7 | ||
|
|
78b0f8c10c | ||
|
|
bb47acd8f6 | ||
|
|
7d4a0b6096 | ||
|
|
d3ff0ef3f7 | ||
|
|
0c5d61dfc1 | ||
|
|
ab8a300e8d | ||
|
|
5fa2416cf3 | ||
|
|
f350fe0b82 | ||
|
|
7ce0825f69 | ||
|
|
47b471acb4 | ||
|
|
3465b0b2a9 | ||
|
|
44d8fea138 | ||
|
|
3ff307ac6d | ||
|
|
26c8658eb7 | ||
|
|
6e2b2d6ca6 | ||
|
|
d8fbcd6b16 | ||
|
|
0c6edb3fe5 |
@@ -84,6 +84,11 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
production tags are cut only from `main`.
|
||||
- **Android:** Jetpack Compose only (no XML), kotlinx.serialization (no Gson),
|
||||
OkHttp (no Ktor), `wss://` only. Run `./gradlew lint` before pushing Kotlin.
|
||||
For interactive device-review loops, run focused tests plus the affected
|
||||
assemble/install task; run the full affected-variant lint once when the
|
||||
combined candidate is final, or earlier only for lint-sensitive resource,
|
||||
manifest, dependency, or build-configuration changes. Do not repeat full
|
||||
variant lint after every small Kotlin iteration.
|
||||
- **Plugin (Python 3.11+):** aiohttp + asyncio (no threading), type hints
|
||||
everywhere, structured `logging` (no `print`). **Desktop CLI (Node ≥21):**
|
||||
zero runtime deps, strict TS + ES modules, ship compiled `dist/`. Full
|
||||
|
||||
+44
-3
@@ -6,24 +6,65 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [Android 1.14.0] - 2026-08-30
|
||||
|
||||
### Added
|
||||
|
||||
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden.
|
||||
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
|
||||
- **Android can preview delegated agent work without leaving the parent chat.** The current-chat activity sheet shows bounded lifecycle, progress, and tool previews for concurrent children, opens vanilla Hermes child history read-only when the Gateway exposes it, and stays explicit when reconnect gaps or older routes leave details unavailable. (#447)
|
||||
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden. An updated optional Hermes-Relay Plugin is required for Git operations.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Connections now explain and recover each Dashboard, Relay, and optional API route independently.** LAN, Tailscale, and public HTTPS can fail over without allowing an unauthenticated or different-origin Relay route to borrow Dashboard credentials. Protected same-origin Relay health challenges are recognized as authentication boundaries instead of outages. An updated optional Hermes-Relay Plugin is required for same-origin Relay ingress. (Related: #399)
|
||||
- **Android What's New leads with one curated release highlight without interrupting startup.** A timed post-update toast can be swiped or closed, previews additional feature/fix counts when a release has meaningful secondary items, expands into the centered highlight view on request, and keeps the full technical history available. Each release can present one plain-language summary, up to three primary benefits, and up to two quieter improvements, while release checks keep the structured entry, fallback, Play copy, and public release records aligned.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android wake-word detection now loads a compatible native ONNX Runtime.** Packaged sherpa and Java JNI consumers are checked against the shared runtime for every supported ABI before release.
|
||||
- **Android wake-word detection now loads a compatible native ONNX Runtime.** Packaged sherpa and Java JNI consumers are checked against the shared runtime for every supported ABI before release. (#444)
|
||||
- **Android Continuous voice waits for barge-in microphone teardown before listening again.** Multi-turn hands-free conversations no longer lose the microphone after a response finishes with barge-in enabled. (#464)
|
||||
- **Opening Android no longer claims or interrupts a turn already running in Hermes Desktop/TUI.** Passive foreground and session browsing now use read-only Gateway status plus profile-scoped history; live-session resume remains reserved for explicit Android actions and exact Android-owned recovery. (Related: #365)
|
||||
- **Android provisional Threads can be removed without touching server history.** The drawer now offers a local-only removal action, reconciles promoted phone sessions without duplicate rows, and keeps Thread routing isolated to the active saved connection. (#461)
|
||||
- **Android Clarify cards make custom answers explicit and keyboard-friendly.** Choice prompts label their Other answer field, submit trimmed text from the keyboard, and do not restore an authoritatively expired prompt after session navigation. (#446)
|
||||
- **The visible Android Sphere keeps its smooth procedural motion across startup and chat.** Backgrounded and motion-disabled surfaces remain still without reducing foreground animation to a stepped ambient pulse.
|
||||
- **Android Voice Focus keeps Stop and immediate spoken steering available across every interaction mode.** Hold-to-talk now interrupts Thinking and Transcribing turns before capturing the replacement direction, remains operable through TalkBack, Switch Access, and keyboard controls, preserves pointer press-and-release behavior across floating controls, and Google Play no longer offers the sideload-only system overlay action.
|
||||
- **Android Assistant sessions explain when no speech was captured instead of appearing stuck at Ready.** Retry feedback survives the separate system overlay process, recreated session UI requests the current turn state, and locked sessions keep transcript, response, and technical error text private. (Related: #424)
|
||||
- **Android New Chat keeps the current profile and stays fresh across profile switches.** Starting from All Profiles no longer forces the literal default profile, choosing another profile from an empty draft no longer reopens that profile's previous session after route settlement or restart, and leaving a provisional phone Thread cannot route the next turn to its old chat under the new profile. (#436)
|
||||
- **Android Dashboard connections and profile drawers no longer wait on unavailable optional routes.** Dashboard, API fallback, and Relay probes run independently; API/Relay never gate a normal Dashboard connection, Gateway auth/ticket failures are not blindly retried, and authenticated session history remains available without a live Gateway socket. Concurrent route probes are shared and generation-safe, healthy same-priority routes win immediately, superseded session reads cancel their HTTP calls, and optional PR decoration stays outside the session-list critical path.
|
||||
|
||||
### Removed
|
||||
|
||||
- **Android Chat no longer includes the hidden clean-focus presentation.** The long-press gesture, overlapping instructional pill, reduced composer, and alternate fading transcript were removed so Chat keeps one complete interaction model. Voice Focus remains available.
|
||||
|
||||
## [Plugin 1.11.0] - 2026-08-30
|
||||
|
||||
### Added
|
||||
|
||||
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
|
||||
- **Relay extensions can use the authenticated Dashboard origin as one network ingress.** Fixed allowlisted HTTP and WebSocket paths proxy to the local Relay while Dashboard admission and Relay session authentication remain separate. (Related: #399)
|
||||
|
||||
### Changed
|
||||
|
||||
- **Hermes-Relay Dashboard management is organized around operator tasks.** Overview, Devices, Activity, Remote Access, Git, and Settings now have separate native Dashboard surfaces; pairing is QR-first, paired clients use responsive cards, and token-backed media is labeled as a bounded diagnostic instead of a health counter. (#486)
|
||||
- **Dashboard, CLI, and TUI pairing advertise the same explicit route set.** Recommended Tailscale uses dedicated HTTPS `:10443` for local Dashboard `:9119`, public HTTPS and LAN stay visible fallbacks, and old `:443`/`:9119` plus direct `:8767` remain migration compatibility.
|
||||
- **Pairing receipts explain transport protection before exposing an invite.** Per-surface probes distinguish application TLS, tailnet encryption, optional API fallback, and authenticated Relay ingress.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Public and roaming pairing no longer invent closed direct Relay or Dashboard ports.** Exact Dashboard origins own their same-origin Relay paths, ambiguous or plaintext public candidates fail closed, and inactive optional API routes are omitted.
|
||||
- **Dense pairing QRs scan reliably.** Dashboard, CLI, and TUI render integer-sized modules with a full quiet zone.
|
||||
- **Remote-access migration keeps existing listeners safe.** Recommended setup avoids taking over `:443`, explicit legacy cleanup remains available, and default disable actions remove only the listeners they own.
|
||||
|
||||
## [0.4.0-beta.6] - 2026-08-30
|
||||
|
||||
### Changed
|
||||
|
||||
- **Hermes-Relay CLI+UI preserves the complete multi-route pairing topology.** Dashboard, Relay, optional API, priorities, and transport protection remain attached to one saved host across LAN, Tailscale, and public routes. (Related: #399)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Desktop rejects Dashboard-ingress Relay dials until it can mint Dashboard WebSocket tickets.** The daemon and host selector choose a compatible direct Relay fallback instead of attempting an unauthenticated same-origin ingress.
|
||||
- **API-less pairing remains valid.** Dashboard and direct Relay routes can pair without inventing an optional API server, while secure-first ranking keeps plain LAN as the final fallback.
|
||||
|
||||
## [Android 1.13.2] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
+6
-22
@@ -1,33 +1,22 @@
|
||||
# Hermes-Relay CLI+UI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-25
|
||||
**Release Date:** 2026-08-30
|
||||
|
||||
This beta makes the Desktop connector resilient through Relay interruptions,
|
||||
aligns Windows computer control with current CUA Driver releases, adds a native
|
||||
Linux ARM64 build, and hardens installation and update discovery.
|
||||
This beta preserves complete multi-route pairing while preventing Desktop from dialing Dashboard-ingress Relay routes before Dashboard WebSocket ticket support is available. (Related: #399)
|
||||
|
||||
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64/arm64, and macOS x64/arm64; the management UI is Windows-only.
|
||||
|
||||
## What's changed
|
||||
|
||||
### Added
|
||||
|
||||
- **Linux ARM64 is a first-class release target.** The one-line installer,
|
||||
updater, checksums, and release artifacts now cover both Linux x64 and arm64.
|
||||
- **The public site shows the real Windows CLI UI.** Deterministic screenshots
|
||||
cover connections, host access, activity, computer control, and updates.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Public naming is aligned.** Releases use `Hermes-Relay CLI+UI` while the
|
||||
beta keeps its existing `desktop-v*` tag and updater contract.
|
||||
- **Saved hosts retain the full route topology.** Dashboard, Relay, optional API, route priority, transport protection, certificate pins, and the selected host survive LAN, Tailscale, and public-route changes without creating duplicate hosts.
|
||||
- **API-less pairing is first-class.** Dashboard plus direct Relay can pair without inventing an optional API server, while secure-first ranking retains plain LAN as the final fallback.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The daemon reconnects instead of exiting after an interrupted Relay socket.** Relay restarts and repeated transient replacement failures stay on bounded automatic backoff, and terminal failures persist an accurate stopped reason for the UI.
|
||||
- **Oversized desktop-tool output no longer closes the shared connection.** PowerShell output and every serialized desktop response stay inside the Relay WebSocket budget.
|
||||
- **Current CUA Driver releases remain compatible by contract.** Driver 0.20 and newer are accepted when their manifest and required tools match Hermes, and Windows uses the manifest-declared direct standard-mode runtime instead of a stale machine-wide daemon.
|
||||
- **Install and update discovery paginates the multi-surface release history.** Desktop releases remain discoverable after more Android and Server releases, Windows cooperative updates clean their released backup, and unsigned installers retain the normal SmartScreen warning.
|
||||
- **Dashboard-ingress Relay routes fail closed on Desktop.** The daemon, host selector, and Relay transport reject ingress that requires a Dashboard WebSocket ticket and choose a compatible direct Relay fallback instead of attempting an unauthenticated dial.
|
||||
- **Pairing accepts the current v3 candidate shape.** Optional API records, same-origin Dashboard/Relay routes, and legacy top-level payloads remain compatible without collapsing route ownership.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -58,9 +47,4 @@ hermes-relay --version
|
||||
hermes-relay hosts list --json
|
||||
hermes-relay daemon start
|
||||
hermes-relay daemon status --json
|
||||
hermes-relay computer-use status --json
|
||||
```
|
||||
|
||||
On Windows, click the Hermes-Relay CLI UI notification-area icon to open the management popup directly above it.
|
||||
|
||||
See the [CLI and tray guide](https://hermes-relay.dev/docs/desktop/) for installation, access modes, grants, and troubleshooting.
|
||||
|
||||
@@ -30,6 +30,56 @@ turn every surface into a mandatory test lane, does not replace CI or maintainer
|
||||
review, and keeps normal work targeting `dev` while preserving the documented
|
||||
release/hotfix exceptions.
|
||||
|
||||
## 2026-08-26 — Android OIDC origin continuity and route latency
|
||||
|
||||
Dashboard authentication now follows upstream `/api/status.auth_flows`:
|
||||
interactive redirect and password providers use native PKCE when advertised,
|
||||
with exact-host cookies retained only for older gateways or client-local native
|
||||
failure. A different provider-declared callback is fenced by installation
|
||||
identity and explicit review before becoming the authenticated Dashboard/Gateway
|
||||
origin. Public origins require HTTPS; reviewed literal LAN, Tailscale, and
|
||||
loopback HTTP retains upstream compatibility. Cookies are never copied between
|
||||
hosts, API and Relay ownership remain separate, unsafe callbacks are rejected,
|
||||
and third-party cookies are enabled only for the short-lived compatibility
|
||||
WebView.
|
||||
|
||||
The saved authenticated origin is now modeled as connection-level
|
||||
Dashboard/Gateway state rather than as a synthetic network candidate. The
|
||||
Routes screen presents a dedicated Dashboard & Gateway card with edit and
|
||||
re-check actions, keeps LAN, Tailscale, API, and Relay under Network routes, and
|
||||
does not expose internal role keys or describe arbitrary routes as VPNs. Changing
|
||||
the Dashboard origin clears origin-bound cookies and bearer state before the new
|
||||
address is verified. The compact footer shows the active surface and transport
|
||||
without allowing long model or profile names to displace the route label.
|
||||
|
||||
For self-hosted OIDC, authorization and callback use one exact Dashboard
|
||||
address. Split DNS remains the preferred public-HTTPS/local-performance shape,
|
||||
but a second public URL is not a universal onboarding field. Android does not
|
||||
treat the identity origin as ownership of optional API or Relay paths.
|
||||
|
||||
Optional API discovery no longer blocks a healthy Dashboard/Gateway route.
|
||||
Concurrent probes are shared, negative results are cached for a bounded window,
|
||||
same-priority routes race by completion, and connection generations prevent a
|
||||
late old route from overwriting a new one. Invalidated probes cannot publish a
|
||||
stale unreachable result or diagnostic. Dashboard session and message reads
|
||||
now cancel with their coroutine, one bounded budget covers the complete session
|
||||
list, WebSocket-ticket minting is bounded, and optional pull-request decoration
|
||||
falls off the critical path while preserving exact profile-scoped rows.
|
||||
Gateway ticket/auth failures receive one bounded classified attempt rather than
|
||||
two serialized waits. A pre-ready WebSocket close settles immediately, while
|
||||
optional API and Relay work remains background capability discovery.
|
||||
|
||||
Focused auth, Dashboard, resolver, route, and native-sign-in coverage passed
|
||||
135 tests on the final `origin/dev` merge, followed by Android lint and sideload
|
||||
assembly. The matching Android 16 sideload was installed in place with app data
|
||||
preserved. Cold-route evidence showed Dashboard selection completing in hundreds
|
||||
of milliseconds, unavailable API fallback work continuing in the background,
|
||||
and unauthenticated ticket failures returning immediately instead of stalling.
|
||||
An upstream-compatible live-writer certification separately kept five full
|
||||
profile-roster RPCs below one second while concurrent ticket mints stayed in
|
||||
single-digit milliseconds. Final interactive provider consent/callback remains
|
||||
a human gate because the test device was locked after deployment.
|
||||
|
||||
## 2026-08-26 — Bounded public issue triage contract
|
||||
|
||||
New GitHub issues may receive one clearly identified Hermes-Relay automated
|
||||
|
||||
+14
-9
@@ -1,26 +1,29 @@
|
||||
# Hermes-Relay Plugin v__VERSION__
|
||||
|
||||
**Release Date:** August 25, 2026
|
||||
**Release Date:** August 30, 2026
|
||||
|
||||
## Summary
|
||||
|
||||
This release adds a provider-neutral account-usage surface for Android and Dashboard clients. Relay resolves Codex credential pools, structured Nous balances, and OpenCode Go windows on the Hermes host without returning provider credentials.
|
||||
|
||||
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
|
||||
This release lets one authenticated Hermes Dashboard origin carry Gateway plus optional Relay extensions, adds a bounded Git workspace, and reorganizes the Dashboard plugin around operator tasks. Standard chat, session history, profiles, Manage, and standard voice remain upstream-owned and do not require this plugin.
|
||||
|
||||
## Added
|
||||
|
||||
- **Provider-neutral usage snapshots.** Authenticated Dashboard clients can resolve the exact active Codex pool entry, Nous balances, and OpenCode Go account windows through one normalized schema.
|
||||
- **Bounded paired-client fallback.** Operators may explicitly enable the Relay usage route for paired standalone clients while credentials remain host-side.
|
||||
- **Dashboard same-origin Relay ingress.** Fixed allowlisted HTTP and WebSocket routes proxy to the local Relay while Dashboard admission and Relay session authentication remain independent. (Related: #399)
|
||||
- **Bounded Git workspace.** Configured roots, path containment, line totals, diffs, branches, staging, commits, remotes, grants, and explicit confirmations protect repository operations.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Usage capabilities are explicit.** Responses identify Relay-enhanced credential pools, structured balances, and provider adapters instead of implying unsupported upstream data.
|
||||
- **Public product naming is aligned.** Releases use `Hermes-Relay Plugin` while retaining the `server-v*` tag and installation contract.
|
||||
- **Task-oriented Dashboard UI.** Overview, Devices, Activity, Remote Access, Git, and Settings now have dedicated surfaces with QR-first pairing, responsive device cards, and honest media diagnostics. (#486)
|
||||
- **One explicit route topology.** Dashboard, CLI, and TUI pairing advertise Dashboard, Relay, and optional API surfaces with stable priorities across Tailscale, public HTTPS, and LAN.
|
||||
- **Dedicated Tailscale listener.** Recommended setup uses tailnet HTTPS `:10443` to local Dashboard `:9119`, avoiding ownership of a reverse proxy's `:443`. Existing `:443`, `:9119`, and direct `:8767` routes remain migration compatibility.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **Custom Hermes homes resolve correctly.** Relay profile discovery and session persistence follow `HERMES_HOME` by default while preserving the explicit `RELAY_HERMES_CONFIG` override.
|
||||
- Public and roaming invites no longer synthesize closed direct Relay `:8767` or wrong Dashboard `:9119` routes.
|
||||
- Ambiguous, credential-bearing, or plaintext public candidates fail closed before an invite is exposed.
|
||||
- Dense pairing QRs use integer-sized modules and a full quiet zone.
|
||||
- Inactive optional API routes are omitted; protected Dashboard-ingress `401/403` responses display as authentication-required while direct Relay and API failures remain failures.
|
||||
- Default Tailscale disable actions remove only owned listeners, and explicit migration cleanup accepts only the bounded supported ports.
|
||||
|
||||
## Install / update
|
||||
|
||||
@@ -32,6 +35,8 @@ Standard chat, session history, and Vanilla Hermes voice remain upstream-owned a
|
||||
# or, if already installed:
|
||||
hermes-relay-update
|
||||
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest, routes, and committed Dashboard bundle are active.
|
||||
|
||||
## Verify
|
||||
|
||||
hermes relay doctor
|
||||
|
||||
@@ -105,7 +105,7 @@ The wizard probes everything and finishes with a capability card:
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
the whole Vanilla Hermes setup.
|
||||
|
||||
> **Going places?** Add the Dashboard's Tailscale address — for example `http://100.x.y.z:9119` or a separately published `https://host.ts.net` URL — under **Settings → Connections → Routes**. Android tests it as a Dashboard route; no API server or API key is required. The app uses LAN at home and switches routes automatically when you leave. See [Remote access](https://hermes-relay.dev/docs/guide/remote-access).
|
||||
> **Going places?** Add the Dashboard's Tailscale address — for example `http://100.x.y.z:9119` or a separately published `https://host.ts.net` URL — under **Settings → Gateways → Routes**. Android tests it as a Dashboard route; no API server or API key is required. The app uses LAN at home and switches routes automatically when you leave. See [Remote access](https://hermes-relay.dev/docs/guide/remote-access).
|
||||
|
||||
### 4 · Recommended: pair Relay for the complete experience
|
||||
|
||||
@@ -124,7 +124,7 @@ Use `--no-ssl` only on a trusted LAN or VPN. Use the
|
||||
exposing any Hermes surface beyond that network.
|
||||
|
||||
Refresh or restart the Dashboard/Gateway, open **Relay → Pair new device**, and
|
||||
scan the one-time QR from Android **Settings → Connections → Pair Hermes Relay**.
|
||||
scan the one-time QR from Android **Settings → Gateways → Access → Pair Relay**.
|
||||
Leave mode on **Auto** for the recommended route discovery. The same dialog
|
||||
shows a copyable invite for Desktop CLI clients:
|
||||
|
||||
@@ -154,7 +154,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
<tr>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/05_themes.png" alt="App themes" width="100%"><br><sub><b>App themes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/06_manage.png" alt="Manage your agent" width="100%"><br><sub><b>Manage your agent</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/07_connections.png" alt="Connections and routes" width="100%"><br><sub><b>Connections & routes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/07_connections.png" alt="Gateways and routes" width="100%"><br><sub><b>Gateways & routes</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/08_appearance.png" alt="Agent avatar & skins" width="100%"><br><sub><b>Avatars & skins</b></sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+24
-11
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.13.2
|
||||
# Hermes-Relay Android v1.14.0
|
||||
|
||||
**Release Date:** August 25, 2026
|
||||
**Release Date:** August 30, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.13.2-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.14.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,20 +12,33 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This release adds a parent-configured Supervised Mode and improves its return from full settings. It also keeps session rows neutral until live activity is confirmed.
|
||||
This release makes saved Hermes connections reliable across LAN, Tailscale, and public HTTPS while keeping Dashboard authentication bound to its exact trusted origin. It also adds delegated-agent previews and an optional native Git workspace, and improves Voice, Assistant, Threads, profile drafts, and Clarify interactions.
|
||||
|
||||
## Added
|
||||
|
||||
- Use a profile-pinned Supervised Mode with parent-controlled attachments, Standard voice, generated media, history, actions, and technical details. Device authentication protects full settings; this remains a client-side restricted view rather than a server-enforced account boundary.
|
||||
- **Delegated-agent previews.** Follow bounded lifecycle, progress, tool previews, and available read-only child history without leaving the parent chat. Partial history and reconnect gaps remain explicit. (#447)
|
||||
- **Native Git workspace.** Review repository state, diffs, branches, staging, commits, and remotes from Chat or Settings. Git operations require Hermes-Relay Plugin v1.11.0 and retain confirmation and grant boundaries.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Route-aware connections.** Dashboard, Relay, and optional API health are evaluated independently across LAN, Tailscale, and public HTTPS. Same-origin Relay ingress stays on the Dashboard origin that owns authentication, while direct compatibility routes keep separate credentials. (Related: #399)
|
||||
- **Voice Focus controls.** Stop and immediate spoken steering remain accessible while Hermes is Thinking, Transcribing, or Speaking, including TalkBack, Switch Access, keyboard, and sideload overlay surfaces.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Keep session rows neutral while optional live activity is unavailable or still loading, and reserve full-row activity borders for actual Starting or Working turns.
|
||||
- Keep Supervised Chat rendered when parent access relocks after visiting full settings.
|
||||
- Wake-word detection packages one compatible ONNX Runtime for sherpa and Java JNI on every supported ABI. (#444)
|
||||
- Continuous voice waits for barge-in microphone teardown before listening again. (#464)
|
||||
- Fresh chats retain their selected profile without reopening a previous session or carrying a proactive Thread route across profiles. (#436)
|
||||
- Provisional Threads can be removed locally and reconcile with promoted sessions without deleting server history. (#461)
|
||||
- Clarify cards expose a reachable Other answer, keyboard Send, and authoritative expiry behavior. (#446)
|
||||
- Passive Android browsing no longer claims or interrupts a turn owned by another client. (Related: #365)
|
||||
- Assistant sessions show retryable no-speech feedback, recover their active state after recreation, and redact conversation details behind the keyguard. (Related: #424)
|
||||
- Protected Relay ingress `401/403` responses are recognized as authentication boundaries rather than outages; malformed, different-origin, and direct unauthorized routes still fail closed.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.13.2** (versionCode **51**).
|
||||
- Standard Chat, sessions, Manage, sharing, profile switching, and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
|
||||
- Granular Device Control remains sideload-only; the Google Play build continues to ship Hermes Bridge Core without AccessibilityService Device Control.
|
||||
- The optional Relay plugin remains unnecessary for standard Android chat, sessions, Manage, and Vanilla Hermes voice.
|
||||
- App version: **1.14.0** (versionCode **52**).
|
||||
- Standard Chat, sessions, profiles, Manage, and standard voice continue to work against unmodified upstream Hermes without the optional Relay plugin.
|
||||
- Install Hermes-Relay Plugin v1.11.0 for same-origin Relay extensions, Git workspace actions, Bridge, media, proactive features, and enhanced voice.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
|
||||
- Existing connections, drafts, sessions, profile ownership, and legacy direct Relay routes remain data-preserving compatibility paths.
|
||||
|
||||
@@ -6,6 +6,20 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Upstream a public Dashboard plugin WebSocket admission seam
|
||||
|
||||
The same-origin Relay ingress follows current upstream's bundled Dashboard
|
||||
plugin pattern but must feature-detect private
|
||||
`hermes_cli.web_server._ws_request_is_allowed` and `_ws_auth_ok` helpers.
|
||||
Propose one public helper that combines Host/Origin policy, single-use ticket
|
||||
authentication, and runtime plugin-enabled gating for `APIRouter` WebSockets.
|
||||
After it is available in the supported Hermes baseline, replace the private
|
||||
imports and remove the Relay plugin's local runtime-disable polling. Until
|
||||
then, missing helpers fail closed and direct Relay remains an advanced
|
||||
compatibility route.
|
||||
|
||||
---
|
||||
|
||||
## Certify Android session activity across lifecycle and profile boundaries
|
||||
|
||||
The contract fixture now covers every upstream live status, complete-snapshot
|
||||
@@ -26,6 +40,9 @@ model device-certified:
|
||||
renders as Working.
|
||||
- Run a background process that outlives its parent turn and verify Background
|
||||
work remains separate from the conversation's Idle state.
|
||||
- On a physical phone, open and repeatedly foreground Android while the same
|
||||
session is working in official Desktop/TUI; verify Android sends no live
|
||||
attach/interrupt RPC, the producer completes, and final history appears.
|
||||
- Pursue an upstream `session.active_list` profile field/filter or an aggregate
|
||||
activity route with explicit profile ownership so multi-profile clients do
|
||||
not need to resolve process-wide rows from durable keys.
|
||||
@@ -1148,16 +1165,19 @@ The gateway-platform model is the *correct + sufficient architecture* (the phone
|
||||
|
||||
### Session drawer audit follow-ups
|
||||
|
||||
- **Persist and server-back Pin/Archive behavior.** The drawer currently keeps
|
||||
both sets in composable memory. They reset when the drawer/app is recreated,
|
||||
and Archive does not call the existing upstream profile-scoped archive API or
|
||||
load archived rows. Either wire Archive end to end and persist Pin locally,
|
||||
or remove the misleading actions until those contracts are complete.
|
||||
- **Paginate large session stores.** Android requests only the 200 most-recent
|
||||
rows and filters/searches them locally. Older sessions are therefore
|
||||
undiscoverable on long-lived profiles even though upstream list APIs support
|
||||
`offset`. Add incremental paging (and server search where capability-backed)
|
||||
without regressing profile scoping or compression-tip projection.
|
||||
- **Certify first-open latency against a large profile store.** Verify a cold
|
||||
launch, immediate drawer open, repeated close/open, and profile switches on a
|
||||
real high-row-count Dashboard. The first bounded page must not wait on
|
||||
Gateway socket readiness; cached rows must remain visible; a timeout must end
|
||||
without another long automatic read; and the final failure must be retryable
|
||||
**Unavailable**, never "No sessions." Capture both client timing and the
|
||||
server's session-list request duration before calling the path fixed.
|
||||
- **Certify progressive paging on large stores.** Android loads 50 visible-source
|
||||
recents first and appends 50-row `offset` pages near the end of the drawer.
|
||||
Exercise repeated near-end triggers, a profile/route switch during page load,
|
||||
hidden-source preference changes, terminal short pages, and server search
|
||||
without regressing ownership, cached rows, pin/archive state, or compression
|
||||
tips.
|
||||
|
||||
The client-side mitigations shipped (see DEVLOG 2026-06-27): the `updateSessions` clobber guard, the post-turn title reconcile (gateway), and the subtle "not auto-named here" drawer note on SSE. These two are the larger follow-ups:
|
||||
|
||||
@@ -1300,7 +1320,12 @@ and whether the agent is waiting on the user.
|
||||
permissions; exercise compact, expanded, collapsed, and full-Voice handoff
|
||||
states, background tap-through, rotation and insets, cancel/back, microphone
|
||||
denial, network failure, process kill/recreation, and wake→voice→wake
|
||||
resumption. Measure idle battery drain because third-party assistants do not
|
||||
resumption. For background and keyguard capture, record `AudioRecord`, AppOps,
|
||||
and foreground-service state: the user-installed app owns capture outside the
|
||||
separate session process, so confirm whether the selected Assistant role is
|
||||
sufficient on each target OS or whether activation needs an explicit,
|
||||
activation-scoped microphone foreground-service lease. Measure idle battery
|
||||
drain because third-party assistants do not
|
||||
receive Google's dedicated low-power hotword hardware.
|
||||
|
||||
- **Audio quality guardrails** — normalize output volume across realtime and
|
||||
|
||||
+13
-7
@@ -95,7 +95,7 @@ class OnboardingFlowTest {
|
||||
composeTestRule.onNodeWithText("Connect").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Connect to Hermes").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Add gateway").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,16 +121,22 @@ class OnboardingFlowTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectPage_recommendsGeneralSetupQr() {
|
||||
fun addGatewayPage_leadsWithStandardGatewayMethods() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes nearby")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Remote gateway")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Scan Hermes setup QR")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Recommended")
|
||||
.assertIsDisplayed()
|
||||
.assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -138,7 +144,7 @@ class OnboardingFlowTest {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Server or VPS").performClick()
|
||||
composeTestRule.onNodeWithText("Remote gateway").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
@@ -151,7 +157,7 @@ class OnboardingFlowTest {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Server or VPS").performClick()
|
||||
composeTestRule.onNodeWithText("Remote gateway").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
@@ -176,7 +182,7 @@ class OnboardingFlowTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectPage_keepsPairingOptional() {
|
||||
fun addGatewayPage_keepsPairingOptional() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
@@ -203,7 +209,7 @@ class OnboardingFlowTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipButton_visibleOnIntroPages_andWizardSkipOnConnectPage() {
|
||||
fun skipButton_visibleOnIntroPages_andWizardSkipOnAddGatewayPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
repeat(4) {
|
||||
|
||||
+83
@@ -239,6 +239,60 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
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(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = okHttp,
|
||||
),
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.setChatVisible(true)
|
||||
fixture.awaitRpcCount("session.active_list", baselineActiveList + 1)
|
||||
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"passive lifecycle sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
assertEquals(
|
||||
"observer teardown interrupted the Desktop turn",
|
||||
baseline.getValue("session.interrupt"),
|
||||
fixture.rpcCount("session.interrupt"),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
@@ -263,6 +317,9 @@ internal class AndroidGatewayContractFixture {
|
||||
@Volatile
|
||||
var recoveryRunning = false
|
||||
|
||||
@Volatile
|
||||
var activeSessionStatus: String? = null
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
@@ -282,6 +339,18 @@ internal class AndroidGatewayContractFixture {
|
||||
"session.activate" -> sessionSnapshot(
|
||||
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "fixture-live-1",
|
||||
)
|
||||
"session.active_list" -> buildJsonObject {
|
||||
put("sessions", kotlinx.serialization.json.buildJsonArray {
|
||||
activeSessionStatus?.let { status ->
|
||||
add(buildJsonObject {
|
||||
put("id", LIVE_SESSION_ID)
|
||||
put("session_key", STORED_SESSION_ID)
|
||||
put("status", status)
|
||||
put("last_active", 1.0)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
"prompt.submit", "session.interrupt" -> buildJsonObject { put("ok", true) }
|
||||
else -> JsonObject(emptyMap())
|
||||
}
|
||||
@@ -345,6 +414,15 @@ internal class AndroidGatewayContractFixture {
|
||||
error("Gateway RPC $method not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun awaitRpcCount(method: String, count: Int) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (rpcCount(method) >= count) return
|
||||
Thread.sleep(20)
|
||||
}
|
||||
error("Gateway RPC $method count $count not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
@@ -353,4 +431,9 @@ internal class AndroidGatewayContractFixture {
|
||||
allSockets.forEach { socket -> runCatching { socket.close(1001, "teardown") } }
|
||||
runCatching { server.shutdown() }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
v1.13.2 - Supervised Mode and clearer activity
|
||||
v1.14.0 - Connections that follow you
|
||||
|
||||
Supervised Mode creates a simpler, profile-focused chat with device-protected parent settings and control over attachments, Standard voice, generated media, history, actions, and technical details. Activity indicators now appear only while Hermes is genuinely working, and returning from parent settings keeps Supervised Chat open.
|
||||
Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
{
|
||||
"schema": 2,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.14.0",
|
||||
"title": "Connections that follow you",
|
||||
"date": "2026-08-30",
|
||||
"highlight": {
|
||||
"title": "Reliable routes",
|
||||
"summary": "Move between LAN, Tailscale, and public HTTPS without mixing Dashboard or Relay authentication.",
|
||||
"bullets": [
|
||||
"Keep Chat and sessions on the trusted Dashboard while optional Relay routes recover independently.",
|
||||
"Preview delegated agent work and use the optional native Git workspace.",
|
||||
"Use more reliable Continuous voice, Voice Focus, Assistant, Threads, profiles, and Clarify controls."
|
||||
]
|
||||
},
|
||||
"improvements": [
|
||||
"Wake-word detection now packages a compatible native runtime for every supported ABI.",
|
||||
"Protected Relay health checks no longer appear as broken routes."
|
||||
],
|
||||
"toastDigest": {
|
||||
"additionalFeatureCount": 2,
|
||||
"fixCount": 10,
|
||||
"preview": [
|
||||
"delegated-agent previews",
|
||||
"safer voice and sessions"
|
||||
]
|
||||
},
|
||||
"playNotes": "Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Use the best available route",
|
||||
"bullets": [
|
||||
"Resolve Dashboard, Relay, and optional API health independently across LAN, Tailscale, and public HTTPS.",
|
||||
"Keep same-origin Relay ingress on the exact Dashboard origin that owns authentication."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Follow active work",
|
||||
"bullets": [
|
||||
"Preview delegated-agent lifecycle, progress, tools, and available read-only child history from the parent chat.",
|
||||
"Review Git status, diffs, branches, staging, commits, and remotes through the optional Relay plugin."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Keep voice and conversations owned correctly",
|
||||
"bullets": [
|
||||
"Serialize microphone handoff and keep Voice Focus Stop and steering accessible across active phases.",
|
||||
"Preserve fresh profile drafts, provisional Thread ownership, Clarify answers, passive observation, and Assistant privacy through reconnects."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.13.2",
|
||||
"title": "Supervised Mode and clearer activity",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
v1.13.2 - Supervised Mode and clearer activity
|
||||
v1.14.0 - Connections that follow you
|
||||
|
||||
Supervised Mode
|
||||
* Protect parent settings with your phone's device authentication.
|
||||
* Choose access to attachments, Standard voice, generated media, history, actions, and technical details.
|
||||
* Keep Supervised Chat open when returning from parent settings.
|
||||
Reliable routes
|
||||
* Keep Chat and sessions on the trusted Dashboard while optional Relay routes recover independently.
|
||||
* Preview delegated agent work and use the optional native Git workspace.
|
||||
* Use more reliable Continuous voice, Voice Focus, Assistant, Threads, profiles, and Clarify controls.
|
||||
|
||||
Also improved
|
||||
* Activity indicators now appear only while Hermes is genuinely working.
|
||||
* Wake-word detection now packages a compatible native runtime for every supported ABI.
|
||||
* Protected Relay health checks no longer appear as broken routes.
|
||||
|
||||
@@ -39,14 +39,38 @@ enum class AssistantSessionPhase {
|
||||
Closed,
|
||||
}
|
||||
|
||||
enum class AssistantSessionNotice {
|
||||
NoSpeech,
|
||||
}
|
||||
|
||||
data class AssistantSessionSnapshot(
|
||||
val phase: AssistantSessionPhase = AssistantSessionPhase.Launching,
|
||||
val transcript: String? = null,
|
||||
val response: String = "",
|
||||
val notice: AssistantSessionNotice? = null,
|
||||
val error: String? = null,
|
||||
val screenContextSupported: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun assistantSnapshotForPresentation(
|
||||
snapshot: AssistantSessionSnapshot,
|
||||
locked: Boolean,
|
||||
): AssistantSessionSnapshot = if (locked) {
|
||||
snapshot.copy(
|
||||
transcript = null,
|
||||
response = "",
|
||||
error = null,
|
||||
screenContextSupported = false,
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
}
|
||||
|
||||
internal fun assistantSnapshotMatchesActivation(
|
||||
expectedActivationId: String?,
|
||||
receivedActivationId: String?,
|
||||
): Boolean = expectedActivationId != null && expectedActivationId == receivedActivationId
|
||||
|
||||
object AssistantRole {
|
||||
fun status(context: Context): AssistantRoleStatus {
|
||||
val component = ComponentName(context, HermesVoiceInteractionService::class.java)
|
||||
@@ -209,6 +233,7 @@ object AssistantSessionProtocol {
|
||||
onFailure = { failure ->
|
||||
publish(
|
||||
application,
|
||||
activation.id,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = failure.message ?: "Hermes voice could not start",
|
||||
@@ -219,13 +244,19 @@ object AssistantSessionProtocol {
|
||||
return true
|
||||
}
|
||||
|
||||
fun publish(context: Context, snapshot: AssistantSessionSnapshot) {
|
||||
fun publish(
|
||||
context: Context,
|
||||
activationId: String,
|
||||
snapshot: AssistantSessionSnapshot,
|
||||
) {
|
||||
context.sendBroadcast(
|
||||
Intent(context, AssistantSessionStateReceiver::class.java).apply {
|
||||
action = ACTION_STATUS
|
||||
putExtra(EXTRA_ACTIVATION_ID, activationId)
|
||||
putExtra(EXTRA_PHASE, snapshot.phase.name)
|
||||
putExtra(EXTRA_TRANSCRIPT, snapshot.transcript)
|
||||
putExtra(EXTRA_RESPONSE, snapshot.response)
|
||||
putExtra(EXTRA_NOTICE, snapshot.notice?.name)
|
||||
putExtra(EXTRA_ERROR, snapshot.error)
|
||||
putExtra(EXTRA_SCREEN_CONTEXT_SUPPORTED, snapshot.screenContextSupported)
|
||||
}
|
||||
@@ -238,10 +269,6 @@ object AssistantSessionProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(context: Context, state: VoiceUiState) {
|
||||
publish(context, snapshotFromVoiceState(state))
|
||||
}
|
||||
|
||||
internal fun snapshotFromVoiceState(state: VoiceUiState): AssistantSessionSnapshot {
|
||||
val phase = when {
|
||||
!state.voiceMode -> AssistantSessionPhase.Closed
|
||||
@@ -256,7 +283,10 @@ object AssistantSessionProtocol {
|
||||
phase = phase,
|
||||
transcript = state.transcribedText?.take(MAX_SESSION_TEXT_CHARS),
|
||||
response = state.responseText.take(MAX_SESSION_TEXT_CHARS),
|
||||
error = state.error?.take(MAX_SESSION_ERROR_CHARS),
|
||||
notice = state.assistantNotice,
|
||||
error = state.error
|
||||
?.takeIf { phase == AssistantSessionPhase.Error }
|
||||
?.take(MAX_SESSION_ERROR_CHARS),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -350,6 +380,9 @@ object AssistantSessionProtocol {
|
||||
phase = phase,
|
||||
transcript = intent.getStringExtra(EXTRA_TRANSCRIPT),
|
||||
response = intent.getStringExtra(EXTRA_RESPONSE).orEmpty(),
|
||||
notice = intent.getStringExtra(EXTRA_NOTICE)?.let { raw ->
|
||||
runCatching { AssistantSessionNotice.valueOf(raw) }.getOrNull()
|
||||
},
|
||||
error = intent.getStringExtra(EXTRA_ERROR),
|
||||
screenContextSupported = intent.getBooleanExtra(
|
||||
EXTRA_SCREEN_CONTEXT_SUPPORTED,
|
||||
@@ -360,24 +393,33 @@ object AssistantSessionProtocol {
|
||||
|
||||
private const val MAX_SESSION_TEXT_CHARS = 4_000
|
||||
private const val MAX_SESSION_ERROR_CHARS = 1_000
|
||||
private const val EXTRA_NOTICE = "notice"
|
||||
}
|
||||
|
||||
object AssistantSessionState {
|
||||
private val _snapshot = MutableStateFlow(AssistantSessionSnapshot())
|
||||
val snapshot: StateFlow<AssistantSessionSnapshot> = _snapshot.asStateFlow()
|
||||
@Volatile private var activationId: String? = null
|
||||
|
||||
internal fun update(snapshot: AssistantSessionSnapshot) {
|
||||
internal fun update(receivedActivationId: String?, snapshot: AssistantSessionSnapshot) {
|
||||
if (!assistantSnapshotMatchesActivation(activationId, receivedActivationId)) return
|
||||
_snapshot.value = snapshot
|
||||
}
|
||||
|
||||
internal fun reset() {
|
||||
internal fun reset(activationId: String) {
|
||||
this.activationId = activationId
|
||||
_snapshot.value = AssistantSessionSnapshot()
|
||||
}
|
||||
}
|
||||
|
||||
class AssistantSessionStateReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
AssistantSessionState.update(AssistantSessionProtocol.readSnapshot(intent))
|
||||
AssistantSessionState.update(
|
||||
receivedActivationId = intent.getStringExtra(
|
||||
AssistantSessionProtocol.EXTRA_ACTIVATION_ID
|
||||
),
|
||||
snapshot = AssistantSessionProtocol.readSnapshot(intent),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,6 +465,7 @@ class AssistantSessionLifecycleReceiver : BroadcastReceiver() {
|
||||
onFailure = { failure ->
|
||||
AssistantSessionProtocol.publish(
|
||||
application,
|
||||
id,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = failure.message ?: "Hermes voice could not start",
|
||||
@@ -430,6 +473,7 @@ class AssistantSessionLifecycleReceiver : BroadcastReceiver() {
|
||||
)
|
||||
},
|
||||
)
|
||||
application.runtime.republishAssistantSnapshot(id)
|
||||
return
|
||||
}
|
||||
if (AssistantSessionProtocol.isStartAction(intent.action)) {
|
||||
|
||||
+73
-3
@@ -3,6 +3,11 @@ package com.hermesandroid.relay.assistant
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.app.KeyguardManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
@@ -67,6 +72,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
@@ -108,6 +114,11 @@ internal fun shouldCancelVoiceWhenSessionUiEnds(
|
||||
presentation: AssistantSessionPresentation,
|
||||
): Boolean = presentation == AssistantSessionPresentation.Overlay
|
||||
|
||||
internal fun assistantPresentationLocked(
|
||||
currentKeyguardLocked: Boolean?,
|
||||
fallbackLocked: Boolean,
|
||||
): Boolean = currentKeyguardLocked ?: fallbackLocked
|
||||
|
||||
private class HermesVoiceInteractionSession(
|
||||
private val service: HermesVoiceInteractionSessionService,
|
||||
) : VoiceInteractionSession(service) {
|
||||
@@ -118,12 +129,19 @@ private class HermesVoiceInteractionSession(
|
||||
private var surfaceExpanded by mutableStateOf(false)
|
||||
private var activationId: String? = null
|
||||
private var manualMic = false
|
||||
private var keyguardLocked by mutableStateOf(false)
|
||||
private var expectScreenContext: Boolean? = null
|
||||
private var pendingSemantic = AssistantSemanticContext()
|
||||
private var pendingScreenshot: ByteArray? = null
|
||||
private var screenContextUi by mutableStateOf(AssistantScreenContextUi())
|
||||
private val contextStore = assistantContextStore(service)
|
||||
private var heartbeatJob: Job? = null
|
||||
private var keyguardReceiverRegistered = false
|
||||
private val keyguardReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
refreshKeyguardState()
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
@@ -139,6 +157,17 @@ private class HermesVoiceInteractionSession(
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
ContextCompat.registerReceiver(
|
||||
service,
|
||||
keyguardReceiver,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
keyguardReceiverRegistered = true
|
||||
window.window?.apply {
|
||||
setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
|
||||
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
|
||||
@@ -155,6 +184,7 @@ private class HermesVoiceInteractionSession(
|
||||
PersistedHermesRelayTheme {
|
||||
AssistantSessionSurface(
|
||||
expanded = surfaceExpanded,
|
||||
locked = keyguardLocked,
|
||||
screenContext = screenContextUi,
|
||||
onExpandedChange = { surfaceExpanded = it },
|
||||
onCancel = { finishSession(cancelVoice = true) },
|
||||
@@ -183,11 +213,22 @@ private class HermesVoiceInteractionSession(
|
||||
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
if (args?.getBoolean(HermesVoiceInteractionService.EXTRA_FROM_KEYGUARD, false) == true) {
|
||||
refreshKeyguardState(
|
||||
fallbackLocked = args?.getBoolean(
|
||||
HermesVoiceInteractionService.EXTRA_FROM_KEYGUARD,
|
||||
false,
|
||||
) == true,
|
||||
)
|
||||
if (keyguardLocked) {
|
||||
window.window?.addFlags(
|
||||
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
|
||||
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
|
||||
)
|
||||
} else {
|
||||
window.window?.clearFlags(
|
||||
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
|
||||
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
|
||||
)
|
||||
}
|
||||
setUiEnabled(true)
|
||||
val startsNewLifecycle = presentation == AssistantSessionPresentation.Inactive
|
||||
@@ -195,10 +236,10 @@ private class HermesVoiceInteractionSession(
|
||||
if (!startsNewLifecycle) return
|
||||
|
||||
surfaceExpanded = false
|
||||
AssistantSessionState.reset()
|
||||
screenContextUi = AssistantScreenContextUi()
|
||||
activationId = args?.getString(AssistantSessionProtocol.EXTRA_ACTIVATION_ID)
|
||||
?: UUID.randomUUID().toString()
|
||||
AssistantSessionState.reset(activationId!!)
|
||||
manualMic = args?.getBoolean(AssistantSessionProtocol.EXTRA_MANUAL_MIC, false) ?: false
|
||||
expectScreenContext = args?.getBoolean(
|
||||
AssistantSessionProtocol.EXTRA_EXPECT_SCREEN_CONTEXT,
|
||||
@@ -300,6 +341,10 @@ private class HermesVoiceInteractionSession(
|
||||
pendingSemantic = AssistantSemanticContext()
|
||||
pendingScreenshot = null
|
||||
screenContextUi = AssistantScreenContextUi()
|
||||
if (keyguardReceiverRegistered) {
|
||||
runCatching { service.unregisterReceiver(keyguardReceiver) }
|
||||
keyguardReceiverRegistered = false
|
||||
}
|
||||
viewOwner.stop()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
@@ -319,6 +364,7 @@ private class HermesVoiceInteractionSession(
|
||||
)
|
||||
}.onFailure {
|
||||
AssistantSessionState.update(
|
||||
activationId,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = it.message ?: "Hermes could not open the voice session.",
|
||||
@@ -337,6 +383,7 @@ private class HermesVoiceInteractionSession(
|
||||
setUiEnabled(false)
|
||||
}.onFailure {
|
||||
AssistantSessionState.update(
|
||||
activationId,
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
error = it.message ?: "Hermes could not open full voice.",
|
||||
@@ -377,6 +424,14 @@ private class HermesVoiceInteractionSession(
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshKeyguardState(fallbackLocked: Boolean = keyguardLocked) {
|
||||
keyguardLocked = assistantPresentationLocked(
|
||||
currentKeyguardLocked = service.getSystemService(KeyguardManager::class.java)
|
||||
?.isKeyguardLocked,
|
||||
fallbackLocked = fallbackLocked,
|
||||
)
|
||||
}
|
||||
|
||||
@RequiresApi(android.os.Build.VERSION_CODES.Q)
|
||||
private fun stageAssistState(state: AssistState) {
|
||||
stageAssistData(state.assistStructure, state.assistContent)
|
||||
@@ -463,6 +518,7 @@ private class AssistantSessionViewOwner :
|
||||
@Composable
|
||||
private fun AssistantSessionSurface(
|
||||
expanded: Boolean,
|
||||
locked: Boolean,
|
||||
screenContext: AssistantScreenContextUi,
|
||||
onExpandedChange: (Boolean) -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
@@ -471,7 +527,8 @@ private fun AssistantSessionSurface(
|
||||
onOpenFullVoice: () -> Unit,
|
||||
onSurfaceBoundsChanged: (android.graphics.Rect) -> Unit,
|
||||
) {
|
||||
val snapshot by AssistantSessionState.snapshot.collectAsState()
|
||||
val rawSnapshot by AssistantSessionState.snapshot.collectAsState()
|
||||
val snapshot = assistantSnapshotForPresentation(rawSnapshot, locked)
|
||||
val status = assistantStatus(snapshot.phase)
|
||||
val transmittedScreenContext = if (snapshot.screenContextSupported) {
|
||||
screenContext
|
||||
@@ -650,6 +707,13 @@ private fun ExpandedAssistantSurface(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
snapshot.notice?.let { notice ->
|
||||
Text(
|
||||
text = assistantNoticeText(notice),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
snapshot.error?.let { error ->
|
||||
Text(
|
||||
text = error,
|
||||
@@ -896,5 +960,11 @@ private fun assistantStatus(phase: AssistantSessionPhase): String = when (phase)
|
||||
private fun compactAssistantText(snapshot: AssistantSessionSnapshot): String =
|
||||
snapshot.transcript?.takeIf { it.isNotBlank() }
|
||||
?: snapshot.response.takeIf { it.isNotBlank() }
|
||||
?: snapshot.notice?.let { assistantNoticeText(it) }
|
||||
?: snapshot.error?.takeIf { it.isNotBlank() }
|
||||
?: assistantStatus(snapshot.phase)
|
||||
|
||||
@Composable
|
||||
private fun assistantNoticeText(notice: AssistantSessionNotice): String = when (notice) {
|
||||
AssistantSessionNotice.NoSpeech -> stringResource(R.string.voice_no_speech_try_again)
|
||||
}
|
||||
|
||||
@@ -994,7 +994,7 @@ class AuthManager(
|
||||
val serverSource = if (serverIssuedCode != null) "QR" else "local-fallback"
|
||||
Log.i(
|
||||
TAG,
|
||||
"authenticate: sending pairing_code=$codeToSend source=$serverSource " +
|
||||
"authenticate: sending pairing credential source=$serverSource " +
|
||||
"ttl=$pendingTtlSeconds grants=${pendingGrants?.keys}"
|
||||
)
|
||||
buildJsonObject {
|
||||
@@ -1063,7 +1063,8 @@ class AuthManager(
|
||||
_currentPairedSession.value = null
|
||||
Log.i(
|
||||
TAG,
|
||||
"applyServerIssuedCodeAndReset: code=$normalized relayUrl=$relayUrl " +
|
||||
"applyServerIssuedCodeAndReset: credential=present " +
|
||||
"relayConfigured=${!relayUrl.isNullOrBlank()} " +
|
||||
"prevState=${prevState::class.simpleName} → Unpaired"
|
||||
)
|
||||
scope.launch {
|
||||
|
||||
@@ -10,6 +10,16 @@ package com.hermesandroid.relay.data
|
||||
*/
|
||||
object AgentDisplay {
|
||||
const val SERVER_DEFAULT_PROFILE_KEY: String = "__server_default__"
|
||||
private const val PROFILE_CONTEXT_SEPARATOR = "::"
|
||||
|
||||
data class ProfileContextIdentity(
|
||||
val connectionId: String,
|
||||
val profileKey: String,
|
||||
) {
|
||||
/** Null means the upstream request must inherit Server Default. */
|
||||
val requestProfileName: String?
|
||||
get() = profileRequestName(profileKey)
|
||||
}
|
||||
private val GENERIC_MODEL_ALIASES = setOf(
|
||||
"hermes-agent",
|
||||
"hermes_agent",
|
||||
@@ -163,7 +173,25 @@ object AgentDisplay {
|
||||
profileRequestName(profileName) ?: SERVER_DEFAULT_PROFILE_KEY
|
||||
|
||||
fun profileContextKey(connectionId: String?, profileName: String?): String =
|
||||
"${connectionId.orEmpty()}::${profileSessionKey(profileName)}"
|
||||
"${connectionId.orEmpty()}$PROFILE_CONTEXT_SEPARATOR${profileSessionKey(profileName)}"
|
||||
|
||||
/**
|
||||
* Parse the canonical profile/context identity used by persisted chat state.
|
||||
*
|
||||
* Legacy or malformed opaque keys deliberately return null: recovery may
|
||||
* still use the exact key for ownership, but must not invent an upstream
|
||||
* profile override from it. The first separator is authoritative so legal
|
||||
* profile names containing `::` remain round-trippable.
|
||||
*/
|
||||
fun parseProfileContextKey(contextKey: String?): ProfileContextIdentity? {
|
||||
val raw = contextKey?.trim().orEmpty()
|
||||
val separator = raw.indexOf(PROFILE_CONTEXT_SEPARATOR)
|
||||
if (separator <= 0 || separator + PROFILE_CONTEXT_SEPARATOR.length >= raw.length) return null
|
||||
val connectionId = raw.substring(0, separator).trim()
|
||||
val profileKey = raw.substring(separator + PROFILE_CONTEXT_SEPARATOR.length).trim()
|
||||
if (connectionId.isEmpty() || profileKey.isEmpty()) return null
|
||||
return ProfileContextIdentity(connectionId, profileKey)
|
||||
}
|
||||
|
||||
fun localDisplayAlias(value: String?): String? =
|
||||
value
|
||||
|
||||
@@ -23,6 +23,8 @@ import kotlinx.serialization.json.Json
|
||||
data class ChatTurnCheckpoint(
|
||||
val schemaVersion: Int = CURRENT_SCHEMA,
|
||||
val contextKey: String,
|
||||
/** Explicit persisted profile identity; null only for legacy checkpoints. */
|
||||
val profileKey: String? = null,
|
||||
val sessionId: String,
|
||||
val liveSessionId: String? = null,
|
||||
val transport: String,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.net.Inet6Address
|
||||
import java.net.InetAddress
|
||||
import java.net.URI
|
||||
|
||||
@Serializable
|
||||
@@ -65,6 +67,14 @@ data class Connection(
|
||||
* "derive from [apiServerUrl] using the conventional same-host :9119".
|
||||
*/
|
||||
val dashboardUrl: String? = null,
|
||||
/**
|
||||
* Credential-free origin that most recently completed Dashboard
|
||||
* authentication for this connection. Public origins require HTTPS;
|
||||
* loopback/private-overlay HTTP retains upstream's trusted-network mode.
|
||||
* Dashboard/Gateway consumers prefer this origin, while [routeCandidates]
|
||||
* continue to own only network route selection for API and Relay.
|
||||
*/
|
||||
val authenticatedDashboardOrigin: String? = null,
|
||||
val dashboardAuthRequired: Boolean? = null,
|
||||
val dashboardAuthProviders: List<String> = emptyList(),
|
||||
val dashboardLastStatus: DashboardConnectionStatus? = null,
|
||||
@@ -77,6 +87,11 @@ data class Connection(
|
||||
val routeCandidates: List<EndpointCandidate> = emptyList(),
|
||||
/** Optional user preference such as "lan" or "tailscale"; null means Auto. */
|
||||
val preferredRouteRole: String? = null,
|
||||
/**
|
||||
* Explicit per-installation consent for Relay Git repository discovery.
|
||||
* Missing legacy values remain off; route/profile changes do not broaden it.
|
||||
*/
|
||||
val gitRepoScanningEnabled: Boolean = false,
|
||||
/** Epoch milliseconds. Pass `System.currentTimeMillis()`; do not pass seconds. */
|
||||
val pairedAt: Long? = null,
|
||||
/** Last time the user explicitly selected this connection. */
|
||||
@@ -86,21 +101,27 @@ data class Connection(
|
||||
/** Epoch milliseconds. The auth.ok `expires_at` field is seconds — multiply by 1000 at the call site. */
|
||||
val expiresAt: Long? = null,
|
||||
) {
|
||||
/**
|
||||
* Effective Dashboard/Gateway endpoint. Legacy records did not persist a
|
||||
* dashboard URL, so they retain the conventional same-host `:9119`
|
||||
* derivation from the API server. Dashboard-only records persist an
|
||||
* explicit URL and may leave [apiServerUrl] and [relayUrl] blank.
|
||||
*/
|
||||
val resolvedDashboardUrl: String
|
||||
/** Saved Dashboard/Gateway route before any authenticated-origin override. */
|
||||
val configuredDashboardUrl: String
|
||||
get() = dashboardUrl
|
||||
?.trim()
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: deriveDefaultDashboardUrl(apiServerUrl).orEmpty()
|
||||
|
||||
/**
|
||||
* Effective Dashboard/Gateway endpoint. A verified authenticated origin
|
||||
* wins without rewriting the saved network route. Legacy records retain
|
||||
* the conventional same-host `:9119` derivation through
|
||||
* [configuredDashboardUrl].
|
||||
*/
|
||||
val resolvedDashboardUrl: String
|
||||
get() = authenticatedDashboardOrigin
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
?: configuredDashboardUrl
|
||||
|
||||
/** Stable display/host identity that does not depend on the API surface. */
|
||||
val primaryEndpointUrl: String
|
||||
get() = resolvedDashboardUrl.takeIf { it.isNotBlank() }
|
||||
get() = configuredDashboardUrl.takeIf { it.isNotBlank() }
|
||||
?: apiServerUrl.trim().takeIf { it.isNotBlank() }
|
||||
?: relayUrl.trim()
|
||||
|
||||
@@ -506,6 +527,12 @@ data class Connection(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a hand-typed Dashboard/Gateway address. Bare private,
|
||||
* LAN, and Tailscale hosts use upstream's `http://…:9119` default;
|
||||
* bare public hosts use `https://` on the standard HTTPS port.
|
||||
* Explicit schemes and ports are preserved for precise validation.
|
||||
*/
|
||||
fun normalizeDashboardUrlInput(
|
||||
raw: String,
|
||||
defaultPort: Int = DEFAULT_DASHBOARD_PORT,
|
||||
@@ -513,7 +540,10 @@ data class Connection(
|
||||
val trimmed = raw.trim().trimEnd('/')
|
||||
if (trimmed.isEmpty()) return trimmed
|
||||
if (SCHEME_REGEX.containsMatchIn(trimmed)) return trimmed
|
||||
val withScheme = "http://$trimmed"
|
||||
val provisionalHttpUrl = "http://$trimmed"
|
||||
val publicAddress = inferRouteRole(provisionalHttpUrl) == "public"
|
||||
val withScheme = if (publicAddress) "https://$trimmed" else provisionalHttpUrl
|
||||
if (publicAddress) return withScheme
|
||||
val uri = runCatching { URI(withScheme) }.getOrNull()
|
||||
val canAppendPort = uri != null &&
|
||||
!uri.host.isNullOrBlank() &&
|
||||
@@ -528,16 +558,41 @@ data class Connection(
|
||||
.getOrNull()
|
||||
?.lowercase()
|
||||
?: return "custom"
|
||||
val normalizedHost = host.removePrefix("[").removeSuffix("]")
|
||||
if (normalizedHost.contains(':')) {
|
||||
val address = runCatching { InetAddress.getByName(normalizedHost) }
|
||||
.getOrNull() as? Inet6Address
|
||||
?: return "public"
|
||||
return when {
|
||||
isTailscaleIpv6(address) -> "tailscale"
|
||||
address.isAnyLocalAddress ||
|
||||
address.isLoopbackAddress ||
|
||||
address.isLinkLocalAddress ||
|
||||
isUniqueLocalIpv6(address) -> "lan"
|
||||
else -> "public"
|
||||
}
|
||||
}
|
||||
return when {
|
||||
host.endsWith(".ts.net") || isTailscaleIpv4(host) -> "tailscale"
|
||||
host == "localhost" ||
|
||||
host == "127.0.0.1" ||
|
||||
host == "::1" ||
|
||||
isPrivateLanIpv4(host) -> "lan"
|
||||
normalizedHost.endsWith(".ts.net") || isTailscaleIpv4(normalizedHost) -> "tailscale"
|
||||
normalizedHost == "localhost" ||
|
||||
normalizedHost == "127.0.0.1" ||
|
||||
normalizedHost.endsWith(".local") ||
|
||||
normalizedHost.endsWith(".lan") ||
|
||||
!normalizedHost.contains('.') ||
|
||||
isPrivateLanIpv4(normalizedHost) -> "lan"
|
||||
else -> "public"
|
||||
}
|
||||
}
|
||||
|
||||
private fun isTailscaleIpv6(address: Inet6Address): Boolean {
|
||||
val bytes = address.address
|
||||
val prefix = intArrayOf(0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0)
|
||||
return prefix.indices.all { index -> bytes[index].toInt() and 0xff == prefix[index] }
|
||||
}
|
||||
|
||||
private fun isUniqueLocalIpv6(address: Inet6Address): Boolean =
|
||||
address.address.first().toInt() and 0xfe == 0xfc
|
||||
|
||||
private fun isTailscaleIpv4(host: String): Boolean {
|
||||
val parts = host.split('.').mapNotNull { it.toIntOrNull() }
|
||||
if (parts.size != 4) return false
|
||||
@@ -557,3 +612,45 @@ data class Connection(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Normalize an absolute, credential-free HTTPS origin for authenticated Dashboard use. */
|
||||
internal fun normalizeCredentialFreeHttpsOrigin(raw: String): String? {
|
||||
val parsed = runCatching { URI(raw.trim()) }.getOrNull() ?: return null
|
||||
if (!parsed.scheme.equals("https", ignoreCase = true)) return null
|
||||
if (parsed.host.isNullOrBlank() || parsed.userInfo != null) return null
|
||||
if (parsed.query != null || parsed.fragment != null) return null
|
||||
if (parsed.port > 65_535) return null
|
||||
return parsed.normalize().toASCIIString().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a reviewed Dashboard credential owner. Public origins require
|
||||
* HTTPS; cleartext is accepted only for literal loopback, RFC1918/link-local,
|
||||
* or Tailscale CGNAT addresses.
|
||||
*/
|
||||
internal fun normalizeCredentialFreeAuthenticatedDashboardOrigin(raw: String): String? {
|
||||
normalizeCredentialFreeHttpsOrigin(raw)?.let { return it }
|
||||
val parsed = runCatching { URI(raw.trim()) }.getOrNull() ?: return null
|
||||
if (!parsed.scheme.equals("http", ignoreCase = true)) return null
|
||||
val host = parsed.host
|
||||
?.lowercase()
|
||||
?.removePrefix("[")
|
||||
?.removeSuffix("]")
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: return null
|
||||
if (parsed.userInfo != null || parsed.query != null || parsed.fragment != null) return null
|
||||
if (parsed.port > 65_535) return null
|
||||
val trustedHost = host == "localhost" || host == "127.0.0.1" || host == "::1" ||
|
||||
host.split('.').mapNotNull(String::toIntOrNull).let { octets ->
|
||||
octets.size == 4 && octets.all { it in 0..255 } && when {
|
||||
octets[0] == 10 -> true
|
||||
octets[0] == 172 && octets[1] in 16..31 -> true
|
||||
octets[0] == 192 && octets[1] == 168 -> true
|
||||
octets[0] == 169 && octets[1] == 254 -> true
|
||||
octets[0] == 100 && octets[1] in 64..127 -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
if (!trustedHost) return null
|
||||
return parsed.normalize().toASCIIString().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ package com.hermesandroid.relay.data
|
||||
*/
|
||||
enum class SurfaceSecurityKind { Tls, Overlay, Plain }
|
||||
|
||||
/** Whether a configured surface currently contributes traffic to the connection. */
|
||||
enum class SurfaceUseState { InUse, Available, Unavailable }
|
||||
|
||||
/** Connection-level rollup across the surfaces actually in use. */
|
||||
enum class ConnectionSecurityLevel { Tls, Overlay, Mixed, Plain, Unknown }
|
||||
|
||||
@@ -28,6 +31,7 @@ data class SurfaceSecurity(
|
||||
/** Human mechanism: "TLS", "Tailscale", "WireGuard", "Proxy", "Plain". */
|
||||
val mechanism: String,
|
||||
val url: String,
|
||||
val useState: SurfaceUseState = SurfaceUseState.InUse,
|
||||
)
|
||||
|
||||
data class ConnectionSecurity(
|
||||
@@ -86,6 +90,7 @@ fun classifySurfaceSecurity(
|
||||
url: String,
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
useState: SurfaceUseState = SurfaceUseState.InUse,
|
||||
): SurfaceSecurity {
|
||||
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
|
||||
val (kind, mechanism) = when {
|
||||
@@ -96,7 +101,13 @@ fun classifySurfaceSecurity(
|
||||
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
|
||||
else -> SurfaceSecurityKind.Plain to "Plain"
|
||||
}
|
||||
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
|
||||
return SurfaceSecurity(
|
||||
label = label,
|
||||
kind = kind,
|
||||
mechanism = mechanism,
|
||||
url = url,
|
||||
useState = useState,
|
||||
)
|
||||
}
|
||||
|
||||
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
|
||||
@@ -112,8 +123,8 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
} ?: return false
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage" -> "dashboard"
|
||||
"API / sessions" -> "api"
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -137,23 +148,67 @@ fun computeConnectionSecurity(
|
||||
relayConfigured: Boolean,
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
dashboardInUse: Boolean = true,
|
||||
apiInUse: Boolean = true,
|
||||
apiAvailable: Boolean = apiInUse,
|
||||
relayInUse: Boolean = relayConfigured,
|
||||
apiEndpoint: EndpointCandidate? = activeEndpoint,
|
||||
relayEndpoint: EndpointCandidate? = activeEndpoint,
|
||||
): ConnectionSecurity {
|
||||
val surfaces = buildList {
|
||||
dashboardUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("Chat & Manage", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "Dashboard & Gateway",
|
||||
url = it,
|
||||
activeEndpoint = activeEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = if (dashboardInUse) SurfaceUseState.InUse else SurfaceUseState.Unavailable,
|
||||
)
|
||||
)
|
||||
}
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("API / sessions", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "API fallback",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = when {
|
||||
apiInUse -> SurfaceUseState.InUse
|
||||
apiAvailable -> SurfaceUseState.Available
|
||||
else -> SurfaceUseState.Unavailable
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
if (relayConfigured) {
|
||||
relayUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(classifySurfaceSecurity("Relay tools", it, activeEndpoint, isTailscaleDetected))
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "Relay tools",
|
||||
url = it,
|
||||
activeEndpoint = relayEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
useState = if (relayInUse) SurfaceUseState.InUse else SurfaceUseState.Unavailable,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (surfaces.isEmpty()) return ConnectionSecurity.UNKNOWN
|
||||
|
||||
val kinds = surfaces.map { it.kind }.toSet()
|
||||
// Configured-but-unavailable fallbacks remain visible in the breakdown,
|
||||
// but do not make the active transport look insecure.
|
||||
val activeSurfaces = surfaces.filter { it.useState == SurfaceUseState.InUse }
|
||||
if (activeSurfaces.isEmpty()) {
|
||||
return ConnectionSecurity(
|
||||
level = ConnectionSecurityLevel.Unknown,
|
||||
mechanism = "",
|
||||
surfaces = surfaces,
|
||||
)
|
||||
}
|
||||
val kinds = activeSurfaces.map { it.kind }.toSet()
|
||||
val hasPlain = SurfaceSecurityKind.Plain in kinds
|
||||
val hasSecure = kinds.any { it != SurfaceSecurityKind.Plain }
|
||||
|
||||
@@ -167,7 +222,7 @@ fun computeConnectionSecurity(
|
||||
val mechanism = when (level) {
|
||||
ConnectionSecurityLevel.Tls -> "TLS"
|
||||
ConnectionSecurityLevel.Overlay ->
|
||||
surfaces.firstOrNull { it.kind == SurfaceSecurityKind.Overlay }?.mechanism ?: "Encrypted"
|
||||
activeSurfaces.firstOrNull { it.kind == SurfaceSecurityKind.Overlay }?.mechanism ?: "Encrypted"
|
||||
ConnectionSecurityLevel.Mixed -> "Mixed"
|
||||
ConnectionSecurityLevel.Plain -> when (activeEndpoint?.role?.lowercase()) {
|
||||
"lan" -> "LAN"
|
||||
|
||||
@@ -149,15 +149,15 @@ class ConnectionStore private constructor(
|
||||
// between the two names — `{"id": ..., "label": ..., ...}` —
|
||||
// so no per-record migration is needed.
|
||||
if (newJson == null && oldJson != null) {
|
||||
val restored = decodeConnections(oldJson)
|
||||
dataStore.edit { p ->
|
||||
p[KEY_CONNECTIONS] = oldJson
|
||||
p[KEY_CONNECTIONS] = encodeConnections(restored)
|
||||
p.remove(KEY_LEGACY_PROFILES)
|
||||
if (activeNew == null && activeOld != null) {
|
||||
p[KEY_ACTIVE_CONNECTION_ID] = activeOld
|
||||
p.remove(KEY_LEGACY_ACTIVE_PROFILE_ID)
|
||||
}
|
||||
}
|
||||
val restored = decodeConnections(oldJson)
|
||||
val validStartupId = startupId?.takeIf { id -> restored.any { it.id == id } }
|
||||
_connections.value = restored
|
||||
_startupConnectionId.value = validStartupId
|
||||
@@ -168,6 +168,12 @@ class ConnectionStore private constructor(
|
||||
)
|
||||
} else {
|
||||
val restored = decodeConnections(newJson)
|
||||
if (newJson != null) {
|
||||
val normalizedJson = encodeConnections(restored)
|
||||
if (normalizedJson != newJson) {
|
||||
dataStore.edit { p -> p[KEY_CONNECTIONS] = normalizedJson }
|
||||
}
|
||||
}
|
||||
val validStartupId = startupId?.takeIf { id -> restored.any { it.id == id } }
|
||||
_connections.value = restored
|
||||
_startupConnectionId.value = validStartupId
|
||||
@@ -571,7 +577,17 @@ class ConnectionStore private constructor(
|
||||
internal fun Connection.withDashboardDefaults(): Connection {
|
||||
val derivedDashboardUrl = Connection.deriveDefaultDashboardUrl(apiServerUrl)
|
||||
val effectiveDashboardUrl = dashboardUrl?.takeIf { it.isNotBlank() } ?: derivedDashboardUrl
|
||||
val storedOrDefaultRoutes = routeCandidates.ifEmpty {
|
||||
val legacyAuthenticatedRoute = routeCandidates.firstOrNull {
|
||||
it.role.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true)
|
||||
}
|
||||
val migratedAuthenticatedOrigin = authenticatedDashboardOrigin
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
?: legacyAuthenticatedRoute?.dashboard?.url
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
val routesWithoutLegacyAuthentication = routeCandidates.filterNot {
|
||||
it.role.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true)
|
||||
}
|
||||
val storedOrDefaultRoutes = routesWithoutLegacyAuthentication.ifEmpty {
|
||||
Connection.buildRouteCandidates(
|
||||
apiServerUrl = apiServerUrl,
|
||||
relayUrl = relayUrl,
|
||||
@@ -582,16 +598,18 @@ internal fun Connection.withDashboardDefaults(): Connection {
|
||||
dashboardUrl = effectiveDashboardUrl,
|
||||
candidates = storedOrDefaultRoutes,
|
||||
)
|
||||
val normalizedPreferredRouteRole = preferredRouteRole?.takeIf { preferred ->
|
||||
normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) }
|
||||
}
|
||||
val normalizedPreferredRouteRole = preferredRouteRole
|
||||
?.takeUnless { it.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true) }
|
||||
?.takeIf { preferred -> normalizedRoutes.any { it.role.equals(preferred, ignoreCase = true) } }
|
||||
return if (
|
||||
dashboardUrl != effectiveDashboardUrl ||
|
||||
authenticatedDashboardOrigin != migratedAuthenticatedOrigin ||
|
||||
normalizedRoutes != routeCandidates ||
|
||||
normalizedPreferredRouteRole != preferredRouteRole
|
||||
) {
|
||||
copy(
|
||||
dashboardUrl = effectiveDashboardUrl,
|
||||
authenticatedDashboardOrigin = migratedAuthenticatedOrigin,
|
||||
routeCandidates = normalizedRoutes,
|
||||
preferredRouteRole = normalizedPreferredRouteRole,
|
||||
)
|
||||
@@ -599,3 +617,5 @@ internal fun Connection.withDashboardDefaults(): Connection {
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
internal const val LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE = "authenticated_dashboard"
|
||||
|
||||
@@ -25,7 +25,7 @@ import java.net.URI
|
||||
*
|
||||
* **Semantics (locked by ADR 24):**
|
||||
* - [role] is an open string. Known values `lan` / `tailscale` / `public`
|
||||
* get styled labels; anything else renders generically (`Custom VPN (<role>)`).
|
||||
* get styled labels; anything else renders generically (`Custom route (<role>)`).
|
||||
* No enum, no normalization — the raw role string must round-trip exactly
|
||||
* so HMAC canonicalization holds.
|
||||
* - [priority] is strict, `0 = highest`. Reachability never promotes a lower
|
||||
@@ -145,18 +145,19 @@ data class BrokerEndpoint(
|
||||
*
|
||||
* Unknown roles (`"wireguard"`, `"zerotier"`, `"netbird-eu"`, operator-defined
|
||||
* labels) return false so the UI can fall back to [displayLabel]'s generic
|
||||
* "Custom VPN" treatment.
|
||||
* "Custom route" treatment.
|
||||
*/
|
||||
fun EndpointCandidate.isKnownRole(): Boolean {
|
||||
return when (role.lowercase()) {
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
|
||||
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https",
|
||||
"dashboard", "authenticated_dashboard" -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable label for the UI. Known roles get fixed-case styled labels;
|
||||
* unknown roles render as `"Custom VPN (<role>)"` with the raw role preserved
|
||||
* unknown roles render as `"Custom route (<role>)"` with the raw role preserved
|
||||
* so an operator can see exactly what they labeled it.
|
||||
*
|
||||
* The raw [role] on the [EndpointCandidate] is NOT modified — it stays in its
|
||||
@@ -172,12 +173,27 @@ fun EndpointCandidate.displayLabel(): String {
|
||||
"Public"
|
||||
}
|
||||
"https" -> "HTTPS"
|
||||
"dashboard", "authenticated_dashboard" -> if (
|
||||
primaryRouteUrl()?.startsWith("https://", ignoreCase = true) == true
|
||||
) {
|
||||
"HTTPS Dashboard"
|
||||
} else {
|
||||
"Dashboard"
|
||||
}
|
||||
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
|
||||
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
|
||||
else -> "Custom VPN ($role)"
|
||||
else -> displayName?.trim()?.takeIf { it.isNotBlank() } ?: "Custom route ($role)"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a route created only to keep Dashboard/Gateway authentication on
|
||||
* its canonical origin. It is a service address, not another selectable
|
||||
* whole-connection or VPN route.
|
||||
*/
|
||||
fun EndpointCandidate.isDashboardOnlyRoute(): Boolean =
|
||||
api == null && relay == null && proxy == null && broker == null && dashboard != null
|
||||
|
||||
/** Dashboard-first URL identity for routing, diagnostics, and UI labels. */
|
||||
fun EndpointCandidate.primaryRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
@@ -185,6 +201,11 @@ fun EndpointCandidate.primaryRouteUrl(): String? =
|
||||
?: relay?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxy?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
|
||||
/** Dashboard/Gateway identity only; Relay and broker transports are extensions. */
|
||||
fun EndpointCandidate.gatewayRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
|
||||
/** Stable host/port identity without assuming that an API surface exists. */
|
||||
fun EndpointCandidate.routeAuthority(): String? {
|
||||
val rawUrl = primaryRouteUrl() ?: return null
|
||||
|
||||
@@ -38,6 +38,8 @@ data class ProactiveInboxEntry(
|
||||
val connectionId: String? = null,
|
||||
/** Relay proved this row came from its bounded offline queue. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
/** Exact Android notification slot, when recorded by the receiving build. */
|
||||
val notificationId: Int? = null,
|
||||
)
|
||||
|
||||
private val Context.proactiveInboxStore: DataStore<Preferences> by
|
||||
@@ -58,15 +60,19 @@ private const val MAX_ENTRIES = 100
|
||||
* bounded store also backs the provisional Thread until the user's first reply
|
||||
* promotes it to a real `source=phone` session.
|
||||
*/
|
||||
class ProactiveInboxRepository(private val context: Context) {
|
||||
class ProactiveInboxRepository internal constructor(
|
||||
private val store: DataStore<Preferences>,
|
||||
) {
|
||||
|
||||
constructor(context: Context) : this(context.proactiveInboxStore)
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
val entries: Flow<List<ProactiveInboxEntry>> =
|
||||
context.proactiveInboxStore.data.map { prefs -> decode(prefs[INBOX_JSON]) }
|
||||
store.data.map { prefs -> decode(prefs[INBOX_JSON]) }
|
||||
|
||||
suspend fun add(entry: ProactiveInboxEntry) {
|
||||
context.proactiveInboxStore.edit { prefs ->
|
||||
store.edit { prefs ->
|
||||
val current = decode(prefs[INBOX_JSON]).toMutableList()
|
||||
current.removeAll { it.id == entry.id }
|
||||
current.add(0, entry)
|
||||
@@ -76,7 +82,40 @@ class ProactiveInboxRepository(private val context: Context) {
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
context.proactiveInboxStore.edit { it.remove(INBOX_JSON) }
|
||||
store.edit { it.remove(INBOX_JSON) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one provisional Thread owned by one saved connection.
|
||||
*
|
||||
* This only edits the bounded local inbox. A promoted Thread is server
|
||||
* history and is deliberately outside this repository, so this operation
|
||||
* can never delete it. Legacy entries without a connection owner are
|
||||
* removed with the active row because they are rendered in that row; rows
|
||||
* explicitly owned by another connection remain isolated.
|
||||
*/
|
||||
suspend fun removeThread(
|
||||
chatId: String,
|
||||
connectionId: String,
|
||||
): List<ProactiveInboxEntry> {
|
||||
val normalizedChatId = chatId.ifBlank { "phone" }
|
||||
var removed = emptyList<ProactiveInboxEntry>()
|
||||
store.edit { prefs ->
|
||||
val current = decode(prefs[INBOX_JSON])
|
||||
removed = current.filter {
|
||||
(it.connectionId == null || it.connectionId == connectionId) &&
|
||||
(it.chatId ?: "phone") == normalizedChatId
|
||||
}
|
||||
if (removed.isNotEmpty()) {
|
||||
val retained = current.filterNot { it in removed }
|
||||
if (retained.isEmpty()) {
|
||||
prefs.remove(INBOX_JSON)
|
||||
} else {
|
||||
prefs[INBOX_JSON] = json.encodeToString(retained)
|
||||
}
|
||||
}
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): List<ProactiveInboxEntry> {
|
||||
|
||||
@@ -11,6 +11,29 @@ data class RelayEndpoints(
|
||||
val healthUrl: String,
|
||||
)
|
||||
|
||||
/** Dashboard plugin namespace used when Relay rides the Dashboard origin. */
|
||||
const val DASHBOARD_RELAY_INGRESS_PATH: String =
|
||||
"/api/plugins/hermes-relay/transport"
|
||||
|
||||
/**
|
||||
* True when [raw] points at the Dashboard-mounted Relay transport rather than
|
||||
* a directly exposed Relay listener. The distinction is authentication
|
||||
* relevant: the outer Dashboard request keeps its cookie/bearer credential,
|
||||
* while Relay's independently scoped session travels in
|
||||
* `X-Hermes-Relay-Session`.
|
||||
*/
|
||||
fun isDashboardRelayIngressUrl(raw: String?): Boolean {
|
||||
val endpoints = RelayEndpointContract.parseOrNull(raw) ?: return false
|
||||
val path = runCatching { URI(endpoints.httpBaseUrl).rawPath.orEmpty() }
|
||||
.getOrDefault("")
|
||||
.trimEnd('/')
|
||||
val marker = path.indexOf(DASHBOARD_RELAY_INGRESS_PATH)
|
||||
if (marker < 0) return false
|
||||
val markerEndsAt = marker + DASHBOARD_RELAY_INGRESS_PATH.length
|
||||
val suffixBoundary = markerEndsAt == path.length || path[markerEndsAt] == '/'
|
||||
return suffixBoundary
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the accepted Relay URL forms and derives every route from one base.
|
||||
*
|
||||
|
||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import com.hermesandroid.relay.reliability.ReliabilityCenter
|
||||
import com.hermesandroid.relay.reliability.ReliabilityRedactor
|
||||
import java.time.Instant
|
||||
|
||||
enum class DiagnosticCategory(val label: String) {
|
||||
Api("API"),
|
||||
@@ -83,6 +84,8 @@ data class StatusCheck(
|
||||
object DiagnosticsLog {
|
||||
private const val MAX_ENTRIES = 200
|
||||
private const val MAX_TEXT_LENGTH = 180
|
||||
const val SUPPORT_ENTRY_LIMIT = 80
|
||||
private const val MAX_SUPPORT_TEXT_LENGTH = 32_000
|
||||
|
||||
/** Cap for the full stacktrace kept on an error entry — a few KB is plenty. */
|
||||
private const val MAX_TRACE_LENGTH = 8000
|
||||
@@ -204,6 +207,46 @@ object DiagnosticsLog {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact, bounded diagnostics section used by the review-before-sharing
|
||||
* support export. Entries were already sanitized at record time; the final
|
||||
* redaction pass protects legacy entries and keeps this safe to compose with
|
||||
* persistent reliability reports.
|
||||
*/
|
||||
fun supportText(entries: List<DiagnosticLogEntry>): String {
|
||||
val selected = entries.takeLast(SUPPORT_ENTRY_LIMIT)
|
||||
if (selected.isEmpty()) return ""
|
||||
return ReliabilityRedactor.redact(
|
||||
buildString {
|
||||
appendLine("Recent in-app diagnostics")
|
||||
appendLine("Diagnostics: ${selected.size}")
|
||||
selected.forEachIndexed { index, entry ->
|
||||
appendLine()
|
||||
appendLine("===== Diagnostic ${index + 1} =====")
|
||||
appendLine("Time: ${Instant.ofEpochMilli(entry.timestampMs)}")
|
||||
appendLine("Category: ${entry.category.label}")
|
||||
appendLine("Severity: ${entry.severity.name}")
|
||||
appendLine("Title: ${entry.title}")
|
||||
entry.operation?.let { appendLine("Operation: $it") }
|
||||
entry.endpointRole?.let { appendLine("Route: $it") }
|
||||
entry.configuredUrl?.let { appendLine("Configured URL: $it") }
|
||||
entry.requestUrl?.let { appendLine("Request: $it") }
|
||||
if (entry.configuredUrl == null && entry.requestUrl == null) {
|
||||
entry.url?.let { appendLine("URL: $it") }
|
||||
}
|
||||
entry.elapsedMs?.let { appendLine("Elapsed: ${it}ms") }
|
||||
entry.detail?.let { appendLine("Detail: $it") }
|
||||
entry.suggestion?.let { appendLine("Next: $it") }
|
||||
entry.stacktrace?.let {
|
||||
appendLine("Technical detail (redacted)")
|
||||
appendLine(it)
|
||||
}
|
||||
}
|
||||
},
|
||||
MAX_SUPPORT_TEXT_LENGTH,
|
||||
)
|
||||
}
|
||||
|
||||
fun sanitizeUrl(value: String?): String? {
|
||||
val trimmed = value?.trim()?.takeIf { it.isNotBlank() } ?: return null
|
||||
val noQuery = trimmed.substringBefore('?').substringBefore('#')
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.auth.CertPinStore
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.isDashboardRelayIngressUrl
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.PairingPreferences
|
||||
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
|
||||
@@ -43,6 +44,7 @@ import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
enum class ConnectionState {
|
||||
Disconnected,
|
||||
@@ -138,6 +140,12 @@ class ConnectionManager(
|
||||
* back to the legacy per-device PairingPreferences source below.
|
||||
*/
|
||||
private val endpointCandidatesProvider: (suspend () -> List<EndpointCandidate>)? = null,
|
||||
/**
|
||||
* Dynamic ownership fence for Relay-only resolution. Production uses it
|
||||
* to keep Dashboard ingress on the exact origin that owns Dashboard auth,
|
||||
* while direct Relay and proxy routes remain independently eligible.
|
||||
*/
|
||||
private val relayCandidateEligibility: (EndpointCandidate) -> Boolean = { true },
|
||||
/**
|
||||
* Suspending supplier for the active device id. Used to key into
|
||||
* [PairingPreferences.getDeviceEndpoints] during resolution. `null`
|
||||
@@ -151,6 +159,14 @@ class ConnectionManager(
|
||||
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Test seam for observing lifecycle teardown without opening a socket. */
|
||||
private val okHttpClientFactory: (() -> OkHttpClient)? = null,
|
||||
/**
|
||||
* Builds a Dashboard-authorized WebSocket request for plugin ingress.
|
||||
* Implementations mint a fresh single-use Dashboard WS ticket on every
|
||||
* invocation. Direct Relay listeners never call this provider.
|
||||
*/
|
||||
private val dashboardRelayRequestProvider: (suspend (String) -> Request?)? = null,
|
||||
/** Deterministic race seam immediately before an ingress failure may poison route state. */
|
||||
private val beforeIngressFailureCommit: suspend () -> Unit = {},
|
||||
) {
|
||||
private val supervisorJob = SupervisorJob()
|
||||
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
|
||||
@@ -191,6 +207,9 @@ class ConnectionManager(
|
||||
|
||||
@Volatile
|
||||
private var webSocket: WebSocket? = null
|
||||
private val socketGeneration = AtomicLong(0L)
|
||||
@Volatile
|
||||
private var activeSocketGeneration: Long = 0L
|
||||
|
||||
@Volatile
|
||||
private var serverUrl: String? = null
|
||||
@@ -273,6 +292,11 @@ class ConnectionManager(
|
||||
@Volatile
|
||||
private var networkResolveJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
/** Optional API discovery is never part of Dashboard/Gateway readiness. */
|
||||
@Volatile
|
||||
private var apiResolveJob: Job? = null
|
||||
private var apiResolveRevision: Long = 0L
|
||||
|
||||
/** Deferred reaction to a network loss — cancelled if a network returns within the grace. */
|
||||
private var networkLossJob: kotlinx.coroutines.Job? = null
|
||||
|
||||
@@ -363,13 +387,12 @@ class ConnectionManager(
|
||||
// the synthesized list just collapses to the same URL anyway.
|
||||
scope.launch {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
|
||||
_activeRelayEndpoint.value = relayResolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (resolved != null) {
|
||||
_activeEndpoint.value = resolved
|
||||
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
|
||||
@@ -407,6 +430,18 @@ class ConnectionManager(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the exact QR-advertised socket for a fresh pair. Relay health probes
|
||||
* require an established Relay session, so running the normal resolver
|
||||
* before `auth.ok` is circular and can consume the entire pairing window.
|
||||
* Post-pair reconnects continue to use [connect] and full route resolution.
|
||||
*/
|
||||
fun connectPairing(url: String) {
|
||||
ensureNetworkCallbackRegistered()
|
||||
_activeRelayEndpoint.value = null
|
||||
connectToUrlOnMainPath(url, replaceReason = "Fresh Relay pairing")
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an ordinary scheduled reconnect with an immediate attempt.
|
||||
*
|
||||
@@ -577,10 +612,17 @@ class ConnectionManager(
|
||||
*/
|
||||
suspend fun resolveBestEndpoint(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
|
||||
private suspend fun resolveLegacyStandardFallbackSafe(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(EndpointSurface.Standard) { candidate ->
|
||||
candidate.dashboard?.url.isNullOrBlank() &&
|
||||
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl == null
|
||||
}
|
||||
|
||||
private suspend fun resolveBestEndpointSafe(
|
||||
surface: EndpointSurface,
|
||||
candidateFilter: (EndpointCandidate) -> Boolean = { true },
|
||||
): EndpointCandidate? {
|
||||
val resolver = endpointResolver ?: return null
|
||||
val ctx = context ?: return null
|
||||
@@ -609,13 +651,14 @@ class ConnectionManager(
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
if (endpoints.isEmpty()) return null
|
||||
val eligibleEndpoints = endpoints.filter(candidateFilter)
|
||||
if (eligibleEndpoints.isEmpty()) return null
|
||||
|
||||
// Manual override: if the user pinned a role in the Endpoints card,
|
||||
// try that one first; fall through to the strict-priority algorithm
|
||||
// if it isn't reachable.
|
||||
_manualRoleOverride.value?.let { preferredRole ->
|
||||
val preferred = endpoints.firstOrNull {
|
||||
val preferred = eligibleEndpoints.firstOrNull {
|
||||
it.role.equals(preferredRole, ignoreCase = true)
|
||||
}
|
||||
if (preferred != null) {
|
||||
@@ -627,7 +670,54 @@ class ConnectionManager(
|
||||
}
|
||||
}
|
||||
|
||||
return resolver.resolve(endpoints, surface)
|
||||
return resolver.resolve(eligibleEndpoints, surface)
|
||||
}
|
||||
|
||||
/** Every Relay selection path must apply the same live ownership fence. */
|
||||
private suspend fun resolveBestRelayEndpointSafe(): EndpointCandidate? =
|
||||
resolveBestEndpointSafe(
|
||||
surface = EndpointSurface.Relay,
|
||||
candidateFilter = relayCandidateEligibility,
|
||||
)
|
||||
|
||||
/**
|
||||
* Discover the optional API fallback without holding up the standard
|
||||
* Dashboard/Gateway route. A single manager-level job coalesces lifecycle
|
||||
* callers; [EndpointResolver] additionally shares an in-flight request per
|
||||
* route/surface. The negative cache keeps ordinary profile changes cheap,
|
||||
* while network callbacks and explicit probes still invalidate it.
|
||||
*/
|
||||
private fun scheduleApiResolution() {
|
||||
synchronized(this) {
|
||||
apiResolveRevision += 1L
|
||||
if (apiResolveJob?.isActive != true) {
|
||||
startApiResolutionLocked(apiResolveRevision)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Caller must hold this manager's monitor. */
|
||||
private fun startApiResolutionLocked(revision: Long) {
|
||||
apiResolveJob = scope.launch {
|
||||
try {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
synchronized(this@ConnectionManager) {
|
||||
// A route/connection refresh may have arrived while this
|
||||
// optional probe was waiting. Never publish its stale
|
||||
// winner over the newer connection's API ownership.
|
||||
if (revision == apiResolveRevision) {
|
||||
_activeApiEndpoint.value = resolved
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized(this@ConnectionManager) {
|
||||
apiResolveJob = null
|
||||
if (revision != apiResolveRevision && supervisorJob.isActive) {
|
||||
startApiResolutionLocked(apiResolveRevision)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -656,9 +746,9 @@ class ConnectionManager(
|
||||
endpointResolver?.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
|
||||
// Transient probe miss while the relay socket is demonstrably up
|
||||
// — keep the live route published rather than downgrading every
|
||||
@@ -666,7 +756,6 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
|
||||
val normalizedTarget = normalizeRelayUrl(targetUrl)
|
||||
@@ -706,8 +795,8 @@ class ConnectionManager(
|
||||
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
|
||||
if (clearProbeCache) endpointResolver?.clearCache()
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
|
||||
// Transient probe miss while the relay socket is demonstrably up
|
||||
// (slow resume, mid-handoff blip) — keep publishing the live
|
||||
@@ -716,7 +805,6 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -738,6 +826,46 @@ class ConnectionManager(
|
||||
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
|
||||
}
|
||||
|
||||
/** Admission is stronger evidence than `/transport/health`: reject this ingress and retain direct fallback. */
|
||||
private suspend fun fallbackFromBrokenDashboardIngress(
|
||||
url: String,
|
||||
reason: String,
|
||||
failingSocket: WebSocket? = null,
|
||||
failingGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (!isDashboardRelayIngressUrl(url)) return false
|
||||
if (failingGeneration != null) {
|
||||
beforeIngressFailureCommit()
|
||||
if (activeSocketGeneration != failingGeneration || webSocket !== failingSocket) {
|
||||
Log.i(TAG, "Ignoring stale Dashboard ingress failure ($reason)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
val failed = _activeRelayEndpoint.value ?: return false
|
||||
val failedUrl = failed.relayWebSocketUrl()?.let(::normalizeRelayUrl)
|
||||
if (failedUrl != normalizeRelayUrl(url)) return false
|
||||
endpointResolver?.markUnreachable(failed, EndpointSurface.Relay) ?: return false
|
||||
val replacement = resolveBestRelayEndpointSafe() ?: return false
|
||||
val replacementUrl = replacement.relayWebSocketUrl()?.takeIf(String::isNotBlank) ?: return false
|
||||
if (normalizeRelayUrl(replacementUrl) == normalizeRelayUrl(url)) return false
|
||||
_activeRelayEndpoint.value = replacement
|
||||
Log.i(TAG, "Dashboard Relay ingress rejected; switching to ${replacement.role} ($reason)")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = "Relay ingress unavailable",
|
||||
detail = "Dashboard admission failed; using retained direct Relay route.",
|
||||
operation = "Select Relay transport after admission failure",
|
||||
endpointRole = failed.role,
|
||||
requestUrl = url,
|
||||
)
|
||||
connectToUrlOnMainPath(
|
||||
replacementUrl,
|
||||
replaceReason = "Dashboard Relay ingress admission failed",
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Debounced network-change re-resolution, shared by both NetworkCallback
|
||||
* events. Re-runs the resolver and publishes the winner to
|
||||
@@ -760,8 +888,8 @@ class ConnectionManager(
|
||||
if (wipeCache) endpointResolver.clearCache()
|
||||
val current = serverUrl
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
|
||||
?: resolveBestEndpointSafe(EndpointSurface.Standard)
|
||||
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
|
||||
?: resolveLegacyStandardFallbackSafe()
|
||||
scheduleApiResolution()
|
||||
if (resolved == null) {
|
||||
// Hysteresis for the AUTOMATIC (network-callback) path. A
|
||||
// transient cold-route probe miss must NOT null the published
|
||||
@@ -798,7 +926,6 @@ class ConnectionManager(
|
||||
}
|
||||
sustainedLossDeclared = false
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
if (current == null) return@launch
|
||||
// After an explicit disconnect() the route still publishes above
|
||||
// (HTTP surfaces keep roaming), but no socket action: without
|
||||
@@ -807,7 +934,7 @@ class ConnectionManager(
|
||||
// (connectToUrlOnMainPath force-sets shouldReconnect = true, so
|
||||
// the swap path never re-checked it.)
|
||||
if (!shouldReconnect) return@launch
|
||||
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val relayResolved = resolveBestRelayEndpointSafe()
|
||||
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
|
||||
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
|
||||
?: return@launch
|
||||
@@ -974,7 +1101,8 @@ class ConnectionManager(
|
||||
webSocket?.send(text)
|
||||
}
|
||||
|
||||
private fun isActiveSocket(socket: WebSocket): Boolean = webSocket === socket
|
||||
private fun isActiveSocket(socket: WebSocket, generation: Long): Boolean =
|
||||
webSocket === socket && activeSocketGeneration == generation
|
||||
|
||||
private fun doConnect(
|
||||
url: String,
|
||||
@@ -1010,7 +1138,7 @@ class ConnectionManager(
|
||||
scope.launch { doConnectInternal(url, previousSocketToClose, replaceReason) }
|
||||
}
|
||||
|
||||
private fun doConnectInternal(
|
||||
private suspend fun doConnectInternal(
|
||||
url: String,
|
||||
previousSocketToClose: WebSocket? = null,
|
||||
replaceReason: String = "Relay socket replaced",
|
||||
@@ -1035,22 +1163,49 @@ class ConnectionManager(
|
||||
buildClient(url)
|
||||
}
|
||||
|
||||
val request = buildRelayRequestOrNull(url)
|
||||
val request = if (isDashboardRelayIngressUrl(url)) {
|
||||
dashboardRelayRequestProvider?.invoke(url)
|
||||
} else {
|
||||
buildRelayRequestOrNull(url)
|
||||
}
|
||||
if (request == null) {
|
||||
// A malformed relay URL (an invalid/empty host from a corrupt or
|
||||
// hand-edited pairing payload) can't be built into a request. This
|
||||
// runs on a background coroutine, so letting OkHttp's url() throw
|
||||
// would crash the app — the #131 "Invalid URL host" class, relay-
|
||||
// socket half. Route it through the same path onFailure uses.
|
||||
Log.e(TAG, "doConnect: malformed relay URL '$url' — not connecting")
|
||||
Log.e(
|
||||
TAG,
|
||||
if (isDashboardRelayIngressUrl(url)) {
|
||||
"doConnect: Dashboard Relay ticket/request unavailable for '$url'"
|
||||
} else {
|
||||
"doConnect: malformed relay URL '$url' — not connecting"
|
||||
},
|
||||
)
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = "Invalid relay URL",
|
||||
detail = "The relay address could not be parsed; re-pair to refresh it.",
|
||||
operation = "Build Relay WebSocket request",
|
||||
title = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Dashboard Relay authorization unavailable"
|
||||
} else {
|
||||
"Invalid relay URL"
|
||||
},
|
||||
detail = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Dashboard authorization could not prepare the Relay WebSocket request."
|
||||
} else {
|
||||
"The relay address could not be parsed; re-pair to refresh it."
|
||||
},
|
||||
operation = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Mint Dashboard Relay WebSocket ticket"
|
||||
} else {
|
||||
"Build Relay WebSocket request"
|
||||
},
|
||||
configuredUrl = url,
|
||||
suggestion = "Edit or re-pair the Relay route to replace the invalid address.",
|
||||
suggestion = if (isDashboardRelayIngressUrl(url)) {
|
||||
"Sign in to the matching Dashboard route, then recheck Relay routes."
|
||||
} else {
|
||||
"Edit or re-pair the Relay route to replace the invalid address."
|
||||
},
|
||||
)
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
@@ -1058,14 +1213,18 @@ class ConnectionManager(
|
||||
runCatching { stale.close(1000, replaceReason) }
|
||||
stale.cancel()
|
||||
}
|
||||
scheduleReconnect()
|
||||
if (!fallbackFromBrokenDashboardIngress(url, "request provider or ticket unavailable")) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Log.i(TAG, "doConnect: opening WSS to $url")
|
||||
val generation = socketGeneration.incrementAndGet()
|
||||
activeSocketGeneration = generation
|
||||
val newSocket = client.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onOpen: stale WSS handshake ignored ($url)")
|
||||
runCatching { webSocket.close(1000, "Stale relay socket") }
|
||||
webSocket.cancel()
|
||||
@@ -1108,7 +1267,7 @@ class ConnectionManager(
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onMessage: stale WSS envelope ignored ($url)")
|
||||
return
|
||||
}
|
||||
@@ -1135,7 +1294,7 @@ class ConnectionManager(
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onClosed: stale WSS close ignored ($url code=$code reason=$reason)")
|
||||
return
|
||||
}
|
||||
@@ -1149,13 +1308,28 @@ class ConnectionManager(
|
||||
requestUrl = url,
|
||||
suggestion = if (code == 1000) null else "Check the Relay server logs for the matching close code and reason.",
|
||||
)
|
||||
val admitted = authenticated
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
scheduleReconnect()
|
||||
if (isDashboardRelayIngressUrl(url) && !admitted && code != 1000) {
|
||||
scope.launch {
|
||||
if (!fallbackFromBrokenDashboardIngress(
|
||||
url,
|
||||
"pre-auth close $code",
|
||||
webSocket,
|
||||
generation,
|
||||
) && activeSocketGeneration == generation
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
if (!isActiveSocket(webSocket)) {
|
||||
if (!isActiveSocket(webSocket, generation)) {
|
||||
Log.i(TAG, "onFailure: stale WSS failure ignored ($url ${t.javaClass.simpleName}: ${t.message})")
|
||||
return
|
||||
}
|
||||
@@ -1177,6 +1351,22 @@ class ConnectionManager(
|
||||
} ?: NetworkDiagnosticGuidance.forThrowable(t, "Relay"),
|
||||
)
|
||||
lastUpgradeResponseCode = code
|
||||
if (isDashboardRelayIngressUrl(url) && response != null) {
|
||||
authenticated = false
|
||||
_connectionState.value = ConnectionState.Disconnected
|
||||
scope.launch {
|
||||
if (!fallbackFromBrokenDashboardIngress(
|
||||
url,
|
||||
"HTTP admission ${response.code}",
|
||||
webSocket,
|
||||
generation,
|
||||
) && activeSocketGeneration == generation
|
||||
) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (response == null) {
|
||||
// Transport-level failure (no HTTP upgrade response): on a
|
||||
// remote (Tailscale) link the first handshake can fail cold.
|
||||
@@ -1290,7 +1480,7 @@ class ConnectionManager(
|
||||
// expires, auth state may have changed (e.g., user hit Revoke
|
||||
// during the retry window).
|
||||
if (shouldReconnect && reconnectGate()) {
|
||||
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
|
||||
val resolved = resolveBestRelayEndpointSafe()
|
||||
val targetUrl = resolved?.relayWebSocketUrl()
|
||||
if (resolved != null) {
|
||||
// Mirror scheduleNetworkReResolve: clear the sustained-loss
|
||||
|
||||
+10
-9
@@ -102,22 +102,18 @@ class ProactiveMessageHandler(
|
||||
/** Route a parsed message: into the open Thread if it belongs there, else
|
||||
* the durable inbox log + the surface its hint selects. */
|
||||
private fun dispatch(msg: ProactiveMessage) {
|
||||
// Persist first even when the currently open Thread consumes the live
|
||||
// message. Agent-initiated outbound sends do not create a gateway
|
||||
// session until the phone replies, so this cache is the provisional
|
||||
// Thread transcript during that gap.
|
||||
toInbox?.invoke(msg)
|
||||
// The surfacing hint selects the additional surface. Thread injection
|
||||
// is best-effort presentation of the persisted row, not itself a reason
|
||||
// to suppress an explicitly requested notification.
|
||||
when (msg.surfacing?.lowercase()) {
|
||||
val notificationId = when (msg.surfacing?.lowercase()) {
|
||||
"inbox" -> {
|
||||
injectIntoThread?.invoke(msg)
|
||||
null
|
||||
}
|
||||
"session" -> {
|
||||
val delivered = injectIntoThread?.invoke(msg) == true ||
|
||||
toSession?.invoke(msg) == true
|
||||
if (!delivered) notify(msg)
|
||||
if (delivered) null else notify(msg)
|
||||
}
|
||||
// null / "default" / "notification" / anything unrecognized.
|
||||
else -> {
|
||||
@@ -125,9 +121,13 @@ class ProactiveMessageHandler(
|
||||
notify(msg)
|
||||
}
|
||||
}
|
||||
// Every message remains in the bounded local cache. Persist the exact
|
||||
// posted notification slot as part of that row so a later local Thread
|
||||
// removal can cancel only its own notification.
|
||||
toInbox?.invoke(msg.copy(notificationId = notificationId))
|
||||
}
|
||||
|
||||
private fun notify(msg: ProactiveMessage) {
|
||||
private fun notify(msg: ProactiveMessage): Int? =
|
||||
ProactiveMessageNotifier.notify(
|
||||
context = context,
|
||||
title = msg.title,
|
||||
@@ -135,7 +135,6 @@ class ProactiveMessageHandler(
|
||||
messageId = msg.messageId,
|
||||
chatId = msg.chatId,
|
||||
)
|
||||
}
|
||||
|
||||
private fun parse(payload: JsonObject): ProactiveMessage? {
|
||||
val text = payload["text"]?.jsonPrimitive?.contentOrNull
|
||||
@@ -172,4 +171,6 @@ data class ProactiveMessage(
|
||||
val replyTo: String? = null,
|
||||
/** True only when Relay explicitly marked this as a reconnect queue flush. */
|
||||
val arrivedWhileAway: Boolean = false,
|
||||
/** Exact Android notification slot when this delivery posted one. */
|
||||
val notificationId: Int? = null,
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.util.Log
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.auth.PairedDeviceInfo
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.isDashboardRelayIngressUrl
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||
@@ -28,6 +29,18 @@ import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
|
||||
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
||||
|
||||
/** Keep Dashboard outer auth and Relay capability auth in separate headers. */
|
||||
internal fun Request.Builder.relaySessionCredential(
|
||||
token: String,
|
||||
dashboardIngress: Boolean,
|
||||
): Request.Builder = if (dashboardIngress) {
|
||||
header(RELAY_SESSION_HEADER, token)
|
||||
} else {
|
||||
header("Authorization", "Bearer $token")
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP client for the Hermes relay media endpoint.
|
||||
*
|
||||
@@ -59,11 +72,20 @@ class RelayHttpClient(
|
||||
/** Application context for localized string resources. Nullable for
|
||||
* backwards-compat with call sites that don't need localization. */
|
||||
private val context: Context? = null,
|
||||
/** Dashboard-authenticated client for same-origin plugin ingress calls. */
|
||||
private val dashboardHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
) {
|
||||
|
||||
private fun relayHttpBaseOrNull(url: String): String? =
|
||||
RelayEndpointContract.parseOrNull(url)?.httpBaseUrl
|
||||
|
||||
private fun callClient(relayUrl: String): OkHttpClient =
|
||||
if (isDashboardRelayIngressUrl(relayUrl)) {
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: okHttpClient
|
||||
} else {
|
||||
okHttpClient
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayHttpClient"
|
||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||
@@ -199,10 +221,10 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
val activityClient = okHttpClient.newBuilder()
|
||||
val activityClient = callClient(relayUrl).newBuilder()
|
||||
.callTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
@@ -261,12 +283,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "*/*")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val reason = when (response.code) {
|
||||
401, 403 -> "Unauthorized — re-pair with the relay"
|
||||
@@ -369,12 +391,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "*/*")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val reason = when (response.code) {
|
||||
401 -> "Unauthorized — re-pair with the relay"
|
||||
@@ -456,12 +478,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "image/*")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val errorCode = runCatching {
|
||||
sessionsJson.parseToJsonElement(response.body.string())
|
||||
@@ -554,11 +576,11 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
val auditClient = okHttpClient.newBuilder()
|
||||
val auditClient = callClient(relayUrl).newBuilder()
|
||||
.callTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
@@ -640,10 +662,10 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
val client = okHttpClient.newBuilder()
|
||||
val client = callClient(relayUrl).newBuilder()
|
||||
.callTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
try {
|
||||
@@ -753,10 +775,10 @@ class RelayHttpClient(
|
||||
return@withContext Result.failure(IOException("Invalid relay URL: ${e.message}"))
|
||||
}
|
||||
val request = Request.Builder().url(url).get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json").build()
|
||||
try {
|
||||
okHttpClient.newBuilder().callTimeout(4, java.util.concurrent.TimeUnit.SECONDS).build()
|
||||
callClient(relayUrl).newBuilder().callTimeout(4, java.util.concurrent.TimeUnit.SECONDS).build()
|
||||
.newCall(request).execute().use { response ->
|
||||
if (response.code == 404) return@withContext Result.success(null)
|
||||
if (!response.isSuccessful) return@withContext Result.failure(IOException("HTTP ${response.code}"))
|
||||
@@ -807,11 +829,11 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.post(sessionsJson.encodeToString(payload).toRequestBody("application/json".toMediaType()))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
okHttpClient.newBuilder().callTimeout(4, java.util.concurrent.TimeUnit.SECONDS).build()
|
||||
callClient(relayUrl).newBuilder().callTimeout(4, java.util.concurrent.TimeUnit.SECONDS).build()
|
||||
.newCall(request).execute().use { response ->
|
||||
if (response.code == 404) return@withContext Result.success(null)
|
||||
if (!response.isSuccessful) return@withContext Result.failure(IOException("HTTP ${response.code}"))
|
||||
@@ -857,12 +879,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
// Slightly longer than the other reads — a cache-miss on the relay does a
|
||||
// GitHub round-trip in an executor before responding.
|
||||
val client = okHttpClient.newBuilder()
|
||||
val client = callClient(relayUrl).newBuilder()
|
||||
.callTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
try {
|
||||
@@ -941,12 +963,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (response.code == 404) {
|
||||
// Server hasn't shipped the endpoint yet — degrade to
|
||||
// empty list so the UI can render "No paired devices"
|
||||
@@ -1028,12 +1050,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.delete()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (response.code == 404) {
|
||||
// Already gone — treat as success so the UI can just
|
||||
// drop the row on the next refresh.
|
||||
@@ -1145,12 +1167,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.patch(bodyJson.toRequestBody("application/json".toMediaType()))
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val reason = when (response.code) {
|
||||
400 -> "Invalid extend request (check TTL/grants)"
|
||||
@@ -1242,7 +1264,7 @@ class RelayHttpClient(
|
||||
|
||||
// Fast-timeout client — we don't want Save & Test to hang the UI
|
||||
// for 10 seconds on a dead URL.
|
||||
val fastClient = okHttpClient.newBuilder()
|
||||
val fastClient = callClient(relayUrl).newBuilder()
|
||||
.connectTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.writeTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
|
||||
@@ -1484,12 +1506,12 @@ class RelayHttpClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (response.code == 404) {
|
||||
// Older or operator-disabled hosts simply do not expose
|
||||
// account usage. This is capability absence, not an error.
|
||||
|
||||
+17
-8
@@ -10,6 +10,7 @@ import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
|
||||
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
|
||||
import com.hermesandroid.relay.data.RelaySkillToggleResult
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.isDashboardRelayIngressUrl
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.SerializationException
|
||||
@@ -51,11 +52,19 @@ class RelayProfileInspectorClient(
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val relayUrlProvider: () -> String?,
|
||||
private val sessionTokenProvider: suspend () -> String?,
|
||||
private val dashboardHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
) : LegacyProfileInspectorClient {
|
||||
|
||||
private fun relayHttpBaseOrNull(url: String): String? =
|
||||
RelayEndpointContract.parseOrNull(url)?.httpBaseUrl
|
||||
|
||||
private fun callClient(relayUrl: String): OkHttpClient =
|
||||
if (isDashboardRelayIngressUrl(relayUrl)) {
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: okHttpClient
|
||||
} else {
|
||||
okHttpClient
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayProfileInspector"
|
||||
|
||||
@@ -211,12 +220,12 @@ class RelayProfileInspectorClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.put(body.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val reason = when (response.code) {
|
||||
400 -> {
|
||||
@@ -314,12 +323,12 @@ class RelayProfileInspectorClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.put(bodyJson.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
when (response.code) {
|
||||
in 200..299 -> Result.success(RelaySkillToggleResult.Ok)
|
||||
501 -> Result.success(RelaySkillToggleResult.NotImplemented)
|
||||
@@ -374,11 +383,11 @@ class RelayProfileInspectorClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.method("OPTIONS", null)
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
when (response.code) {
|
||||
501 -> false
|
||||
404, 405 -> false
|
||||
@@ -464,12 +473,12 @@ class RelayProfileInspectorClient(
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header("Authorization", "Bearer $sessionToken")
|
||||
.relaySessionCredential(sessionToken, isDashboardRelayIngressUrl(relayUrl))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
callClient(relayUrl).newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val reason = when (response.code) {
|
||||
401, 403 -> "Unauthorized — re-pair with the relay"
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.hermesandroid.relay.data.EnhancedVoiceOverrides
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.RealtimeConversationContextMessage
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.isDashboardRelayIngressUrl
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -89,7 +90,7 @@ import java.util.concurrent.atomic.AtomicReference
|
||||
*/
|
||||
class RelayVoiceClient(
|
||||
private val context: Context,
|
||||
private val okHttpClient: OkHttpClient,
|
||||
okHttpClient: OkHttpClient,
|
||||
private val relayUrlProvider: () -> String?,
|
||||
private val sessionTokenProvider: suspend () -> String?,
|
||||
private val profileNameProvider: () -> String? = { null },
|
||||
@@ -100,8 +101,26 @@ class RelayVoiceClient(
|
||||
private val realtimeResumeRetryIntervalMs: Long = REALTIME_RESUME_RETRY_INTERVAL_MS,
|
||||
private val realtimeResumeRetryWindowMs: Long = REALTIME_RESUME_RETRY_WINDOW_MS,
|
||||
private val voiceOutputFirstAudioTimeoutMs: Long = VOICE_OUTPUT_FIRST_AUDIO_TIMEOUT_MS,
|
||||
/** Dashboard-authenticated transport for same-origin plugin ingress. */
|
||||
private val dashboardHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Fresh Dashboard ticket request for every ingress voice socket dial. */
|
||||
private val dashboardIngressWebSocketRequestProvider:
|
||||
(suspend (String) -> Request?)? = null,
|
||||
) {
|
||||
|
||||
private val directOkHttpClient: OkHttpClient = okHttpClient
|
||||
|
||||
/** Resolve lazily so a Dashboard route/client handoff is observed. */
|
||||
private val okHttpClient: OkHttpClient
|
||||
get() {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
return if (isDashboardRelayIngressUrl(relayUrl)) {
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: directOkHttpClient
|
||||
} else {
|
||||
directOkHttpClient
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayVoiceClient"
|
||||
private val json = Json { ignoreUnknownKeys = true; isLenient = true }
|
||||
@@ -144,13 +163,36 @@ class RelayVoiceClient(
|
||||
}
|
||||
}
|
||||
|
||||
private fun callClient(url: String): OkHttpClient =
|
||||
if (isDashboardRelayIngressUrl(url)) {
|
||||
dashboardHttpClientProvider?.invoke(url) ?: directOkHttpClient
|
||||
} else {
|
||||
directOkHttpClient
|
||||
}
|
||||
|
||||
private fun sessionClient(): OkHttpClient =
|
||||
okHttpClient.newBuilder()
|
||||
.callTimeout(SESSION_CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
private fun openWebSocket(request: Request, listener: WebSocketListener): WebSocket =
|
||||
webSocketFactory?.invoke(request, listener) ?: okHttpClient.newWebSocket(request, listener)
|
||||
webSocketFactory?.invoke(request, listener)
|
||||
?: callClient(request.url.toString()).newWebSocket(request, listener)
|
||||
|
||||
private suspend fun voiceWebSocketRequest(url: String, relayToken: String): Request {
|
||||
val dashboardIngress = isDashboardRelayIngressUrl(url)
|
||||
val outerRequest = if (dashboardIngress) {
|
||||
val provider = dashboardIngressWebSocketRequestProvider
|
||||
?: throw IOException("Dashboard Relay voice authorization is unavailable")
|
||||
provider(url)
|
||||
?: throw IOException("Dashboard Relay voice ticket could not be minted")
|
||||
} else {
|
||||
Request.Builder().url(url).build()
|
||||
}
|
||||
return outerRequest.newBuilder()
|
||||
.relaySessionCredential(relayToken, dashboardIngress)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun requestRouteProbeOnce(
|
||||
surface: String,
|
||||
@@ -196,7 +238,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/transcribe"))
|
||||
.post(body)
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -278,7 +320,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url("$httpBase/voice/synthesize")
|
||||
.post(bodyJson.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "audio/mpeg")
|
||||
.build()
|
||||
|
||||
@@ -333,7 +375,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/config"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -375,7 +417,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/realtime/config"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -414,7 +456,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/realtime/providers/${pathSegment(provider)}/options"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -462,7 +504,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/realtime/providers/${pathSegment(provider)}/validate"))
|
||||
.post(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -515,7 +557,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/realtime/config"))
|
||||
.patch(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -618,7 +660,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/realtime-agent/config"))
|
||||
.patch(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
@@ -650,7 +692,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/output/config"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -689,7 +731,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/output/providers/${pathSegment(provider)}/options"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -741,7 +783,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/output/providers/${pathSegment(provider)}/validate"))
|
||||
.post(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -812,7 +854,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase/voice/output/config"))
|
||||
.patch(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
|
||||
@@ -845,6 +887,7 @@ class RelayVoiceClient(
|
||||
onHandoff: (VoiceHandoffEvent) -> Unit = {},
|
||||
onEvent: (RealtimeVoiceEvent) -> Unit,
|
||||
): Result<VoiceOutputSummary> = withContext(Dispatchers.IO) {
|
||||
val owningScope = this
|
||||
val httpBase = resolveHttpBase()
|
||||
?: return@withContext Result.failure(IllegalStateException("Relay URL not configured"))
|
||||
val token = resolveBearerToken()
|
||||
@@ -869,6 +912,7 @@ class RelayVoiceClient(
|
||||
val completed = AtomicBoolean(false)
|
||||
val resumeAttempted = AtomicBoolean(false)
|
||||
val routeProbeRequested = AtomicBoolean(false)
|
||||
val resumeDialPending = AtomicBoolean(false)
|
||||
val currentSocket = AtomicReference<WebSocket?>()
|
||||
val firstAudioSeen = AtomicBoolean(false)
|
||||
val socketGeneration = AtomicLong(0L)
|
||||
@@ -907,14 +951,14 @@ class RelayVoiceClient(
|
||||
}
|
||||
}
|
||||
|
||||
fun openSocket(resume: Boolean, overrideWsBase: String? = null): WebSocket {
|
||||
suspend fun openSocket(resume: Boolean, overrideWsBase: String? = null): WebSocket {
|
||||
val generation = socketGeneration.incrementAndGet()
|
||||
val currentWsBase = overrideWsBase ?: resolveWebSocketBase()
|
||||
?: throw IOException("Relay URL not configured")
|
||||
val request = Request.Builder()
|
||||
.url("$currentWsBase${session.websocketPath}")
|
||||
.header("Authorization", "Bearer $token")
|
||||
.build()
|
||||
val request = voiceWebSocketRequest(
|
||||
"$currentWsBase${session.websocketPath}",
|
||||
token,
|
||||
)
|
||||
Log.i(
|
||||
TAG,
|
||||
"Voice output websocket opening resume=$resume url=${request.url}",
|
||||
@@ -1044,23 +1088,28 @@ class RelayVoiceClient(
|
||||
return
|
||||
}
|
||||
if (session.resumeSupported && !session.resumeToken.isNullOrBlank() && resumeAttempted.compareAndSet(false, true)) {
|
||||
try {
|
||||
Log.i(TAG, "Voice output websocket failed; attempting resume: ${t.message}")
|
||||
requestRouteProbeOnce("Voice output", t.message, routeProbeRequested)
|
||||
onHandoff(
|
||||
VoiceHandoffEvent(
|
||||
label = context.getString(R.string.voice_diag_connection_changed),
|
||||
detail = t.message,
|
||||
route = routeLabel(webSocket.request().url.toString()),
|
||||
active = true,
|
||||
)
|
||||
Log.i(TAG, "Voice output websocket failed; scheduling resume: ${t.message}")
|
||||
requestRouteProbeOnce("Voice output", t.message, routeProbeRequested)
|
||||
onHandoff(
|
||||
VoiceHandoffEvent(
|
||||
label = context.getString(R.string.voice_diag_connection_changed),
|
||||
detail = t.message,
|
||||
route = routeLabel(webSocket.request().url.toString()),
|
||||
active = true,
|
||||
)
|
||||
openSocket(resume = true)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Voice output resume failed: ${e.message ?: "network error"}", e)
|
||||
return
|
||||
)
|
||||
if (resumeDialPending.compareAndSet(false, true)) {
|
||||
owningScope.launch {
|
||||
try {
|
||||
openSocket(resume = true)
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Voice output resume failed: ${e.message ?: "network error"}", e)
|
||||
} finally {
|
||||
resumeDialPending.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
completeFailure("Voice output websocket failed: ${t.message}", t)
|
||||
}
|
||||
@@ -1090,23 +1139,28 @@ class RelayVoiceClient(
|
||||
return
|
||||
}
|
||||
if (session.resumeSupported && !session.resumeToken.isNullOrBlank() && resumeAttempted.compareAndSet(false, true)) {
|
||||
try {
|
||||
Log.i(TAG, "Voice output websocket closed code=$code; attempting resume")
|
||||
requestRouteProbeOnce("Voice output", "Closed $code $reason", routeProbeRequested)
|
||||
onHandoff(
|
||||
VoiceHandoffEvent(
|
||||
label = context.getString(R.string.voice_diag_connection_changed),
|
||||
detail = "Closed $code $reason",
|
||||
route = routeLabel(webSocket.request().url.toString()),
|
||||
active = true,
|
||||
)
|
||||
Log.i(TAG, "Voice output websocket closed code=$code; scheduling resume")
|
||||
requestRouteProbeOnce("Voice output", "Closed $code $reason", routeProbeRequested)
|
||||
onHandoff(
|
||||
VoiceHandoffEvent(
|
||||
label = context.getString(R.string.voice_diag_connection_changed),
|
||||
detail = "Closed $code $reason",
|
||||
route = routeLabel(webSocket.request().url.toString()),
|
||||
active = true,
|
||||
)
|
||||
openSocket(resume = true)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Voice output resume failed: ${e.message ?: "network error"}", e)
|
||||
return
|
||||
)
|
||||
if (resumeDialPending.compareAndSet(false, true)) {
|
||||
owningScope.launch {
|
||||
try {
|
||||
openSocket(resume = true)
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Voice output resume failed: ${e.message ?: "network error"}", e)
|
||||
} finally {
|
||||
resumeDialPending.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
completeFailure("Voice output websocket closed before completion: $code $reason")
|
||||
}
|
||||
@@ -1178,10 +1232,7 @@ class RelayVoiceClient(
|
||||
var audioChunks = 0
|
||||
var audioBytes = 0
|
||||
|
||||
val request = Request.Builder()
|
||||
.url("$wsBase${session.websocketPath}")
|
||||
.header("Authorization", "Bearer $token")
|
||||
.build()
|
||||
val request = voiceWebSocketRequest("$wsBase${session.websocketPath}", token)
|
||||
|
||||
val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
@@ -1306,6 +1357,7 @@ class RelayVoiceClient(
|
||||
prewarm: Boolean = false,
|
||||
onEvent: (RealtimeVoiceEvent, RealtimeAgentSessionControl) -> Unit,
|
||||
): Result<RealtimeVoiceSummary> = withContext(Dispatchers.IO) {
|
||||
val owningScope = this
|
||||
val persistent = turnInputs != null
|
||||
val httpBase = resolveHttpBase()
|
||||
?: return@withContext Result.failure(IllegalStateException("Relay URL not configured"))
|
||||
@@ -1649,7 +1701,7 @@ class RelayVoiceClient(
|
||||
}
|
||||
}
|
||||
|
||||
fun openSocket(
|
||||
suspend fun openSocket(
|
||||
resume: Boolean,
|
||||
overrideWsBase: String? = null,
|
||||
expectedResumeEpisode: Long? = null,
|
||||
@@ -1673,10 +1725,10 @@ class RelayVoiceClient(
|
||||
val (currentWsBase, request) = try {
|
||||
val base = overrideWsBase ?: resolveWebSocketBase()
|
||||
?: throw IOException("Relay URL not configured")
|
||||
val socketRequest = Request.Builder()
|
||||
.url("$base${session.websocketPath}")
|
||||
.header("Authorization", "Bearer $token")
|
||||
.build()
|
||||
val socketRequest = voiceWebSocketRequest(
|
||||
"$base${session.websocketPath}",
|
||||
token,
|
||||
)
|
||||
Log.i(
|
||||
TAG,
|
||||
"Realtime agent websocket opening resume=$resume url=${socketRequest.url}",
|
||||
@@ -1765,12 +1817,20 @@ class RelayVoiceClient(
|
||||
// A synchronous failure callback can replace this
|
||||
// socket while setup sends are still unwinding. A
|
||||
// stale attempt must not terminate the newer route.
|
||||
if (currentSocket.get() !== webSocket || completed.get()) return
|
||||
if (
|
||||
terminalCallbackSeen.get() ||
|
||||
currentSocket.get() !== webSocket ||
|
||||
completed.get()
|
||||
) return
|
||||
completeFailure("Realtime agent websocket rejected session setup")
|
||||
webSocket.close(1011, "session setup failed")
|
||||
return
|
||||
}
|
||||
if (currentSocket.get() !== webSocket || completed.get()) return
|
||||
if (
|
||||
terminalCallbackSeen.get() ||
|
||||
currentSocket.get() !== webSocket ||
|
||||
completed.get()
|
||||
) return
|
||||
if (resume) {
|
||||
Log.i(TAG, "Realtime agent resume sent; awaiting relay confirmation")
|
||||
} else {
|
||||
@@ -1984,16 +2044,17 @@ class RelayVoiceClient(
|
||||
)
|
||||
)
|
||||
if (!claim.openImmediately) return
|
||||
try {
|
||||
openSocket(
|
||||
resume = true,
|
||||
expectedResumeEpisode = claim.waiting.episode,
|
||||
)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Realtime agent resume failed: ${e.message ?: "network error"}", e)
|
||||
return
|
||||
owningScope.launch {
|
||||
try {
|
||||
openSocket(
|
||||
resume = true,
|
||||
expectedResumeEpisode = claim.waiting.episode,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Realtime agent resume failed: ${e.message ?: "network error"}", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val transitionRevision = claimTerminalSocket(
|
||||
webSocket,
|
||||
@@ -2097,16 +2158,17 @@ class RelayVoiceClient(
|
||||
)
|
||||
)
|
||||
if (!claim.openImmediately) return
|
||||
try {
|
||||
openSocket(
|
||||
resume = true,
|
||||
expectedResumeEpisode = claim.waiting.episode,
|
||||
)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Realtime agent resume failed: ${e.message ?: "network error"}", e)
|
||||
return
|
||||
owningScope.launch {
|
||||
try {
|
||||
openSocket(
|
||||
resume = true,
|
||||
expectedResumeEpisode = claim.waiting.episode,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
completeFailure("Realtime agent resume failed: ${e.message ?: "network error"}", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val transitionRevision = claimTerminalSocket(
|
||||
webSocket,
|
||||
@@ -2294,9 +2356,7 @@ class RelayVoiceClient(
|
||||
null
|
||||
}
|
||||
|
||||
val socket = openSocket(resume = false)
|
||||
?: currentSocket.get()
|
||||
?: throw IOException("Realtime agent websocket handshake was already pending")
|
||||
val initialSocket = openSocket(resume = false) ?: currentSocket.get()
|
||||
val routeWatcherResumeEpisode = AtomicLong(0L)
|
||||
val routeWatcher = startRouteResumeWatcher(
|
||||
surface = "Realtime agent",
|
||||
@@ -2378,7 +2438,7 @@ class RelayVoiceClient(
|
||||
awaitRealtimeAgentCompletion()
|
||||
} catch (e: Exception) {
|
||||
currentSocket.get()?.close(1001, "timeout")
|
||||
socket.close(1001, "timeout")
|
||||
initialSocket?.close(1001, "timeout")
|
||||
Result.failure(IOException(e.message ?: "Realtime agent timed out", e))
|
||||
} finally {
|
||||
routeWatcher?.cancel()
|
||||
@@ -2394,7 +2454,7 @@ class RelayVoiceClient(
|
||||
resumeSupported: Boolean,
|
||||
resumeToken: String?,
|
||||
currentSocket: AtomicReference<WebSocket?>,
|
||||
openResumeSocket: (String?) -> WebSocket?,
|
||||
openResumeSocket: suspend (String?) -> WebSocket?,
|
||||
onHandoff: (VoiceHandoffEvent) -> Unit,
|
||||
completeFailure: (String, Throwable?) -> Unit,
|
||||
): Job? {
|
||||
@@ -2454,7 +2514,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase$path"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
@@ -2493,7 +2553,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase$pathPrefix/${pathSegment(provider)}/options"))
|
||||
.get()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
@@ -2541,7 +2601,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase$pathPrefix/${pathSegment(provider)}/validate"))
|
||||
.post(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
@@ -2593,7 +2653,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url(urlWithProfile("$httpBase$path"))
|
||||
.patch(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
try {
|
||||
@@ -2678,7 +2738,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url("$httpBase/voice/realtime/session")
|
||||
.post(body.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
return try {
|
||||
@@ -2763,7 +2823,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url("$httpBase/voice/realtime-agent/session")
|
||||
.post(body.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
return try {
|
||||
@@ -2804,7 +2864,7 @@ class RelayVoiceClient(
|
||||
val request = Request.Builder()
|
||||
.url("$httpBase/voice/output/session")
|
||||
.post(body.toRequestBody(JSON_MEDIA_TYPE))
|
||||
.header("Authorization", "Bearer $token")
|
||||
.relaySessionCredential(token, isDashboardRelayIngressUrl(httpBase))
|
||||
.header("Accept", "application/json")
|
||||
.build()
|
||||
return try {
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.util.Log
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpointContract
|
||||
import com.hermesandroid.relay.data.isDashboardRelayIngressUrl
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
|
||||
@@ -12,16 +13,24 @@ import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||
import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Deferred
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.TimeoutCancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
@@ -43,7 +52,7 @@ import javax.net.ssl.SSLException
|
||||
*/
|
||||
data class RouteProbeOutcome(
|
||||
val reachable: Boolean,
|
||||
/** Short human-readable failure reason; null when [reachable]. */
|
||||
/** Short result detail; protected ingress may be reachable but require authorization. */
|
||||
val detail: String? = null,
|
||||
/** Resolver-clock timestamp of when the probe finished. */
|
||||
val atMillis: Long,
|
||||
@@ -68,12 +77,15 @@ enum class EndpointSurface {
|
||||
*
|
||||
* ### Semantics (locked by ADR 24)
|
||||
*
|
||||
* * **Strict priority.** `priority = 0` is highest. If a priority-0
|
||||
* candidate is reachable we use it; reachability never promotes a lower
|
||||
* priority over a higher one. Reachability is **only** the tiebreaker
|
||||
* among candidates that share the same priority.
|
||||
* * **Reachability probe.** Dashboard-first routes use `GET
|
||||
* ${dashboard.url}/api/status`; legacy API routes use `GET
|
||||
* * **Strict selection priority with speculative probes.** `priority = 0`
|
||||
* is highest. All supported priority groups start probing together so one
|
||||
* dead route cannot add its full timeout before the fallback even starts,
|
||||
* but a lower-priority result is considered only after every higher group
|
||||
* has failed. Reachability is **only** the tiebreaker among candidates that
|
||||
* share the same priority.
|
||||
* * **Reachability probe.** Dashboard-first routes use lightweight `GET
|
||||
* ${dashboard.url}/api/health` and fall back to `/api/status` only for a
|
||||
* confirmed legacy host without the health route. Legacy API routes use `GET
|
||||
* ${api.url}/health`. Relay-only routes use `GET ${relay.httpUrl}/health`.
|
||||
* Each request has a 4-second
|
||||
* per-candidate timeout. Positive results are cached longer than negative
|
||||
@@ -126,9 +138,21 @@ class EndpointResolver(
|
||||
val baseUrl: String,
|
||||
val requestUrl: String,
|
||||
val path: String,
|
||||
val legacyFallbackRequestUrl: String? = null,
|
||||
val legacyFallbackPath: String? = null,
|
||||
)
|
||||
|
||||
private data class ProbeHttpResult(
|
||||
val code: Int,
|
||||
val successful: Boolean,
|
||||
val bodyPreview: String,
|
||||
)
|
||||
|
||||
private val probeCache = ConcurrentHashMap<String, CacheEntry>()
|
||||
private val inFlightProbes = ConcurrentHashMap<String, Deferred<Boolean>>()
|
||||
private val probeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val probeStateLock = Any()
|
||||
private var probeGeneration = 0L
|
||||
|
||||
private val _probeOutcomes = MutableStateFlow<Map<String, RouteProbeOutcome>>(emptyMap())
|
||||
|
||||
@@ -140,6 +164,12 @@ class EndpointResolver(
|
||||
*/
|
||||
val probeOutcomes: StateFlow<Map<String, RouteProbeOutcome>> = _probeOutcomes.asStateFlow()
|
||||
|
||||
/** Last independently observed verdict for one configured route surface. */
|
||||
fun outcomeFor(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
): RouteProbeOutcome? = probeOutcomes.value[outcomeKey(candidate, surface)]
|
||||
|
||||
private fun recordOutcome(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
@@ -177,41 +207,48 @@ class EndpointResolver(
|
||||
const val CACHE_TTL_MS = 60_000L
|
||||
|
||||
/**
|
||||
* Failed probe-result cache TTL. Keep this intentionally short:
|
||||
* Failed probe-result cache TTL. Keep this bounded but long enough
|
||||
* that ordinary screen/profile lifecycle work cannot repeatedly pay
|
||||
* the full probe timeout:
|
||||
* Android may report a new cellular/VPN network before Tailscale has
|
||||
* finished routing, so a single early ConnectException must not keep a
|
||||
* viable fallback route suppressed through the voice resume window.
|
||||
* viable fallback route suppressed for long. Network-change and
|
||||
* explicit-probe paths invalidate the cache immediately.
|
||||
*/
|
||||
const val NEGATIVE_CACHE_TTL_MS = 2_000L
|
||||
const val NEGATIVE_CACHE_TTL_MS = 15_000L
|
||||
|
||||
/** Shared timeout wording so HEAD-timeout and socket-timeout read the same. */
|
||||
private const val PROBE_TIMEOUT_DETAIL = "No answer (timed out)"
|
||||
|
||||
/**
|
||||
* Stable cache key for one candidate surface:
|
||||
* `"<surface>|<role>|<surface host>:<port>"`.
|
||||
* Stable outcome/cache key for one candidate surface:
|
||||
* `"<surface>|<role>|<normalized service base>"`.
|
||||
* Roles are preserved case-verbatim (HMAC canonicalization contract)
|
||||
* but hostnames are lowercased — two roles pointing at the same
|
||||
* host:port share reachability state.
|
||||
*/
|
||||
internal fun cacheKey(
|
||||
fun outcomeKey(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface = EndpointSurface.Standard,
|
||||
): String {
|
||||
val authority = when (surface) {
|
||||
val serviceIdentity = when (surface) {
|
||||
EndpointSurface.Standard ->
|
||||
candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()
|
||||
EndpointSurface.Dashboard ->
|
||||
routeAuthority(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url).orEmpty()
|
||||
routeIdentity(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url)
|
||||
EndpointSurface.Api ->
|
||||
routeAuthority(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url).orEmpty()
|
||||
routeIdentity(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url)
|
||||
EndpointSurface.Relay ->
|
||||
candidate.pluginProxyRoutesOrNull()?.authority
|
||||
?: routeAuthority(candidate.relay?.url).orEmpty()
|
||||
routeIdentity(candidate.pluginProxyRoutesOrNull()?.relayHttpUrl ?: candidate.relay?.url)
|
||||
}
|
||||
return "${surface.name.lowercase()}|${candidate.role}|$authority"
|
||||
return "${surface.name.lowercase()}|${candidate.role}|$serviceIdentity"
|
||||
}
|
||||
|
||||
internal fun cacheKey(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface = EndpointSurface.Standard,
|
||||
): String = outcomeKey(candidate, surface)
|
||||
|
||||
private fun routeAuthority(rawUrl: String?): String? {
|
||||
val candidate = rawUrl?.trim()?.takeIf { it.isNotBlank() } ?: return null
|
||||
val httpUrl = when {
|
||||
@@ -223,17 +260,31 @@ class EndpointResolver(
|
||||
}
|
||||
return httpUrl.toHttpUrlOrNull()?.let { url -> "${url.host}:${url.port}" }
|
||||
}
|
||||
|
||||
private fun routeIdentity(rawUrl: String?): String {
|
||||
val candidate = rawUrl?.trim()?.takeIf { it.isNotBlank() } ?: return ""
|
||||
val httpCandidate = when {
|
||||
candidate.startsWith("ws://", ignoreCase = true) ->
|
||||
"http://${candidate.substringAfter("://")}"
|
||||
candidate.startsWith("wss://", ignoreCase = true) ->
|
||||
"https://${candidate.substringAfter("://")}"
|
||||
else -> candidate
|
||||
}
|
||||
return httpCandidate.toHttpUrlOrNull()?.let { url ->
|
||||
val path = url.encodedPath.trimEnd('/').takeIf { it.isNotEmpty() }.orEmpty()
|
||||
"${url.scheme}://${url.host}:${url.port}$path"
|
||||
} ?: candidate.lowercase().trimEnd('/')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the resolver against [candidates].
|
||||
*
|
||||
* 1. Group by `priority` ascending.
|
||||
* 2. For each priority group, race the selected surface's health probe
|
||||
* against every candidate in the group. First 2xx wins; ties
|
||||
* broken by whichever response lands first.
|
||||
* 3. If the entire group is unreachable, fall through to the next
|
||||
* priority group.
|
||||
* 1. Group by `priority` ascending and by supported/experimental tier.
|
||||
* 2. Start every supported priority group speculatively, while awaiting
|
||||
* their results in strict priority order. Within a group, first 2xx
|
||||
* wins. If higher groups fail, a completed fallback is ready at once.
|
||||
* 3. Probe the experimental tier only when every supported group fails.
|
||||
* 4. If no candidate is reachable, return `null` — the caller falls back
|
||||
* to its legacy single-URL path.
|
||||
*
|
||||
@@ -254,14 +305,15 @@ class EndpointResolver(
|
||||
// last-resort fallback without displacing Tailscale or direct TLS.
|
||||
val supported = eligible.filterNot { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
|
||||
val experimental = eligible.filter { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
|
||||
val groups = (supported.groupBy { it.priority }.toSortedMap().values +
|
||||
experimental.groupBy { it.priority }.toSortedMap().values)
|
||||
val tiers = listOf(
|
||||
supported.groupBy { it.priority }.toSortedMap().values.toList(),
|
||||
experimental.groupBy { it.priority }.toSortedMap().values.toList(),
|
||||
)
|
||||
|
||||
for (group in groups) {
|
||||
val priority = group.first().priority
|
||||
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
|
||||
val winner = raceGroup(group, surface)
|
||||
for (groups in tiers) {
|
||||
val winner = racePriorityGroups(groups, surface)
|
||||
if (winner != null) {
|
||||
val priority = winner.priority
|
||||
val winnerUrl = probeTarget(winner, surface)?.baseUrl
|
||||
Log.i(TAG, "resolve winner: role=${winner.role} " +
|
||||
"surface=$surface route=$winnerUrl priority=$priority")
|
||||
@@ -287,6 +339,76 @@ class EndpointResolver(
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Start all groups in one stability tier together, but consume them in
|
||||
* strict priority order. Cancelling losing waiters never cancels the shared
|
||||
* physical probes, so their cache/outcome records still warm later calls.
|
||||
*/
|
||||
private suspend fun racePriorityGroups(
|
||||
groups: List<List<EndpointCandidate>>,
|
||||
surface: EndpointSurface,
|
||||
): EndpointCandidate? = coroutineScope {
|
||||
if (groups.isEmpty()) return@coroutineScope null
|
||||
val races = groups.map { group ->
|
||||
val priority = group.first().priority
|
||||
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
|
||||
group to async(Dispatchers.IO) { raceGroup(group, surface) }
|
||||
}
|
||||
for ((_, race) in races) {
|
||||
val winner = race.await()
|
||||
if (winner != null) {
|
||||
races.forEach { (_, other) -> if (other !== race) other.cancel() }
|
||||
return@coroutineScope winner
|
||||
}
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe every independently configured route surface in parallel.
|
||||
*
|
||||
* Dashboard/Gateway, optional API fallback, and Relay do not vouch for one
|
||||
* another even when they share a hostname. Unconfigured surfaces are
|
||||
* omitted. Invalidated probes publish no result, preserving the prior
|
||||
* outcome until a fresh physical probe completes.
|
||||
*/
|
||||
suspend fun probeSurfaces(
|
||||
candidate: EndpointCandidate,
|
||||
): Map<EndpointSurface, RouteProbeOutcome> = coroutineScope {
|
||||
val configuredSurfaces = listOf(
|
||||
EndpointSurface.Dashboard,
|
||||
EndpointSurface.Api,
|
||||
EndpointSurface.Relay,
|
||||
).filter { probeTarget(candidate, it) != null }
|
||||
|
||||
configuredSurfaces
|
||||
.map { surface ->
|
||||
async {
|
||||
isReachable(candidate, surface)
|
||||
surface to currentCachedOutcomeFor(candidate, surface)
|
||||
}
|
||||
}
|
||||
.mapNotNull { deferred ->
|
||||
val (surface, outcome) = deferred.await()
|
||||
outcome?.let { surface to it }
|
||||
}
|
||||
.toMap()
|
||||
}
|
||||
|
||||
/** Return only an outcome still backed by this generation's probe cache. */
|
||||
private fun currentCachedOutcomeFor(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
): RouteProbeOutcome? = synchronized(probeStateLock) {
|
||||
val key = cacheKey(candidate, surface)
|
||||
val cached = probeCache[key]
|
||||
if (cached != null && cached.expiresAt > clock()) {
|
||||
probeOutcomes.value[key]
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Race all candidates in [group] (same priority tier) in parallel. First
|
||||
* candidate that reports reachable — whether from cache or a fresh probe
|
||||
@@ -316,20 +438,23 @@ class EndpointResolver(
|
||||
}
|
||||
|
||||
return coroutineScope {
|
||||
val deferred = group.map { candidate ->
|
||||
async(Dispatchers.IO) {
|
||||
if (isReachable(candidate, surface)) candidate else null
|
||||
val completions = Channel<EndpointCandidate?>(group.size)
|
||||
val waiters = group.map { candidate ->
|
||||
launch(Dispatchers.IO) {
|
||||
completions.send(if (isReachable(candidate, surface)) candidate else null)
|
||||
}
|
||||
}
|
||||
// Collect results in arrival order: iterate through awaitAll +
|
||||
// pick the first non-null. awaitAll preserves input order, which
|
||||
// means a slow-but-reachable priority-0 candidate would block a
|
||||
// fast-and-reachable sibling. But HEAD /health against a healthy
|
||||
// API route replies in <100ms and the timeout caps stragglers at 2s,
|
||||
// so this is acceptable in practice. A true "first to arrive"
|
||||
// would need kotlinx.coroutines Channel plumbing that's not
|
||||
// worth the weight here.
|
||||
deferred.awaitAll().firstOrNull { it != null }
|
||||
repeat(group.size) {
|
||||
val completed = completions.receive()
|
||||
if (completed != null) {
|
||||
// Cancelling these waiters does not cancel the shared
|
||||
// physical probes below; their outcomes still populate
|
||||
// the cache for the next resolution.
|
||||
waiters.forEach { it.cancel() }
|
||||
return@coroutineScope completed
|
||||
}
|
||||
}
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,10 +475,33 @@ class EndpointResolver(
|
||||
return cached.reachable
|
||||
}
|
||||
|
||||
val reachable = probe(candidate, surface)
|
||||
val ttl = if (reachable) CACHE_TTL_MS else NEGATIVE_CACHE_TTL_MS
|
||||
probeCache[key] = CacheEntry(expiresAt = now + ttl, reachable = reachable)
|
||||
return reachable
|
||||
// Resolution is triggered from several independent lifecycle paths
|
||||
// (connection hydration, profile restoration, network callbacks, and
|
||||
// explicit probes). Share one physical request per route/surface so a
|
||||
// slow optional endpoint cannot accumulate duplicate 4-second probes.
|
||||
val shared = synchronized(probeStateLock) {
|
||||
inFlightProbes[key] ?: run {
|
||||
val generation = probeGeneration
|
||||
probeScope.async(start = CoroutineStart.LAZY) {
|
||||
probe(candidate, surface, generation)
|
||||
}.also { deferred ->
|
||||
inFlightProbes[key] = deferred
|
||||
deferred.invokeOnCompletion { inFlightProbes.remove(key, deferred) }
|
||||
deferred.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
return try {
|
||||
shared.await()
|
||||
} catch (_: CancellationException) {
|
||||
// clearCache() owns cancellation of the shared physical probe. A
|
||||
// still-active waiter treats that invalidated result as unknown so
|
||||
// same-priority races can publish their non-winning completion.
|
||||
// Genuine caller cancellation still propagates from ensureActive.
|
||||
currentCoroutineContext().ensureActive()
|
||||
Log.d(TAG, "probe invalidated for $key")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -367,6 +515,7 @@ class EndpointResolver(
|
||||
private suspend fun probe(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
generation: Long,
|
||||
): Boolean {
|
||||
val startedAtMs = clock()
|
||||
val operation = when (surface) {
|
||||
@@ -378,19 +527,25 @@ class EndpointResolver(
|
||||
val target = probeTarget(candidate, surface)
|
||||
val url = target?.requestUrl?.toHttpUrlOrNull()
|
||||
?: run {
|
||||
Log.w(TAG, "probe: invalid url for role=${candidate.role}")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_invalid) ?: "Endpoint probe invalid",
|
||||
detail = "No valid Dashboard, API, or Relay URL",
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = candidate.primaryRouteUrl(),
|
||||
suggestion = "Edit or re-pair this route so it contains a valid service URL.",
|
||||
)
|
||||
recordOutcome(candidate, surface, reachable = false, detail = "Invalid route URL")
|
||||
return false
|
||||
return completeProbe(
|
||||
candidate = candidate,
|
||||
surface = surface,
|
||||
generation = generation,
|
||||
reachable = false,
|
||||
detail = "Invalid route URL",
|
||||
) {
|
||||
Log.w(TAG, "probe: invalid url for role=${candidate.role}")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Error,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_invalid) ?: "Endpoint probe invalid",
|
||||
detail = "No valid Dashboard, API, or Relay URL",
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = candidate.primaryRouteUrl(),
|
||||
suggestion = "Edit or re-pair this route so it contains a valid service URL.",
|
||||
)
|
||||
}
|
||||
}
|
||||
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
|
||||
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
@@ -398,49 +553,96 @@ class EndpointResolver(
|
||||
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.callTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.build()
|
||||
val requestBuilder = Request.Builder()
|
||||
.url(url)
|
||||
.header("Accept", "*/*")
|
||||
// Hermes API's aiohttp health route accepts GET but returns 405 to
|
||||
// HEAD. That response proves connectivity while the old probe marked
|
||||
// the route unreachable. Health payloads are tiny, so follow the
|
||||
// endpoint's actual public contract on every surface.
|
||||
val request = requestBuilder.get().build()
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
withTimeoutOrNull(PROBE_TIMEOUT_MS + 200L) {
|
||||
fastClient.newCall(request).execute().use { resp ->
|
||||
val ok = resp.isSuccessful
|
||||
val probeTitle = if (ok) {
|
||||
val primary = executeProbeHttp(fastClient, url)
|
||||
val fallbackUrl = target.legacyFallbackRequestUrl
|
||||
?.takeIf { dashboardHealthNeedsLegacyFallback(primary) }
|
||||
?.toHttpUrlOrNull()
|
||||
val result = fallbackUrl?.let { executeProbeHttp(fastClient, it) } ?: primary
|
||||
val resultPath = if (fallbackUrl != null) {
|
||||
target.legacyFallbackPath ?: target.path
|
||||
} else {
|
||||
target.path
|
||||
}
|
||||
val resultUrl = fallbackUrl?.toString() ?: target.requestUrl
|
||||
result.let { response ->
|
||||
val authRequired = surface == EndpointSurface.Relay &&
|
||||
isDashboardRelayIngressUrl(candidate.relay?.url) &&
|
||||
response.code in setOf(401, 403)
|
||||
val reachable = response.successful || authRequired
|
||||
val probeTitle = if (reachable) {
|
||||
context?.getString(R.string.endpoint_diag_probe_ok) ?: "Endpoint probe ok"
|
||||
} else {
|
||||
context?.getString(R.string.endpoint_diag_probe_failed) ?: "Endpoint probe failed"
|
||||
}
|
||||
completeProbe(
|
||||
candidate = candidate,
|
||||
surface = surface,
|
||||
generation = generation,
|
||||
reachable = reachable,
|
||||
detail = when {
|
||||
authRequired -> "HTTP ${response.code} · Dashboard authorization required"
|
||||
reachable -> null
|
||||
else -> "HTTP ${response.code} from $resultPath"
|
||||
},
|
||||
) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = if (reachable) DiagnosticSeverity.Info else DiagnosticSeverity.Warning,
|
||||
title = probeTitle,
|
||||
detail = when {
|
||||
authRequired -> "HTTP ${response.code} · Dashboard authorization required"
|
||||
reachable -> null
|
||||
else -> "HTTP ${response.code}"
|
||||
},
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = target.baseUrl,
|
||||
requestUrl = resultUrl,
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = if (reachable) {
|
||||
null
|
||||
} else {
|
||||
NetworkDiagnosticGuidance.forHttpStatus(
|
||||
response.code,
|
||||
surface.diagnosticTarget(),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
} ?: run {
|
||||
completeProbe(
|
||||
candidate = candidate,
|
||||
surface = surface,
|
||||
generation = generation,
|
||||
reachable = false,
|
||||
detail = PROBE_TIMEOUT_DETAIL,
|
||||
) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = if (ok) DiagnosticSeverity.Info else DiagnosticSeverity.Warning,
|
||||
title = probeTitle,
|
||||
detail = if (ok) null else "HTTP ${resp.code}",
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_timeout) ?: "Endpoint probe timeout",
|
||||
detail = "No ${target.path} response in ${PROBE_TIMEOUT_MS}ms",
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = target.baseUrl,
|
||||
requestUrl = target.requestUrl,
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = if (ok) {
|
||||
null
|
||||
} else {
|
||||
NetworkDiagnosticGuidance.forHttpStatus(resp.code, surface.diagnosticTarget())
|
||||
},
|
||||
suggestion = "Check network routing or firewall rules between this device and ${surface.diagnosticTarget()}.",
|
||||
)
|
||||
recordOutcome(
|
||||
candidate,
|
||||
surface,
|
||||
reachable = ok,
|
||||
detail = if (ok) null else "HTTP ${resp.code} from ${target.path}",
|
||||
)
|
||||
ok
|
||||
}
|
||||
} ?: run {
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
completeProbe(
|
||||
candidate = candidate,
|
||||
surface = surface,
|
||||
generation = generation,
|
||||
reachable = false,
|
||||
detail = PROBE_TIMEOUT_DETAIL,
|
||||
) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
@@ -453,45 +655,81 @@ class EndpointResolver(
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = "Check network routing or firewall rules between this device and ${surface.diagnosticTarget()}.",
|
||||
)
|
||||
recordOutcome(candidate, surface, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
|
||||
false
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_timeout) ?: "Endpoint probe timeout",
|
||||
detail = "No ${target.path} response in ${PROBE_TIMEOUT_MS}ms",
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = target.baseUrl,
|
||||
requestUrl = target.requestUrl,
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = "Check network routing or firewall rules between this device and ${surface.diagnosticTarget()}.",
|
||||
)
|
||||
recordOutcome(candidate, surface, reachable = false, detail = PROBE_TIMEOUT_DETAIL)
|
||||
false
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "probe failed role=${candidate.role} " +
|
||||
"route=${target.baseUrl}: ${e.javaClass.simpleName}")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_failed) ?: "Endpoint probe failed",
|
||||
completeProbe(
|
||||
candidate = candidate,
|
||||
surface = surface,
|
||||
generation = generation,
|
||||
reachable = false,
|
||||
detail = humanProbeFailure(e),
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = target.baseUrl,
|
||||
requestUrl = target.requestUrl,
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = NetworkDiagnosticGuidance.forThrowable(e, surface.diagnosticTarget()),
|
||||
)
|
||||
recordOutcome(candidate, surface, reachable = false, detail = humanProbeFailure(e))
|
||||
false
|
||||
) {
|
||||
Log.d(TAG, "probe failed role=${candidate.role} " +
|
||||
"route=${target.baseUrl}: ${e.javaClass.simpleName}")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Endpoint,
|
||||
severity = DiagnosticSeverity.Warning,
|
||||
title = context?.getString(R.string.endpoint_diag_probe_failed) ?: "Endpoint probe failed",
|
||||
detail = humanProbeFailure(e),
|
||||
operation = operation,
|
||||
endpointRole = candidate.role,
|
||||
configuredUrl = target.baseUrl,
|
||||
requestUrl = target.requestUrl,
|
||||
elapsedMs = clock() - startedAtMs,
|
||||
suggestion = NetworkDiagnosticGuidance.forThrowable(e, surface.diagnosticTarget()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun executeProbeHttp(client: OkHttpClient, url: okhttp3.HttpUrl): ProbeHttpResult {
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.header("Accept", "application/json")
|
||||
.get()
|
||||
.build()
|
||||
return client.newCall(request).execute().use { response ->
|
||||
ProbeHttpResult(
|
||||
code = response.code,
|
||||
successful = response.isSuccessful,
|
||||
bodyPreview = response.peekBody(4_096L).string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Official Desktop compatibility for Hermes versions predating `/api/health`. */
|
||||
private fun dashboardHealthNeedsLegacyFallback(result: ProbeHttpResult): Boolean =
|
||||
result.code == 404 ||
|
||||
(result.code == 401 && result.bodyPreview.contains("no_cookie", ignoreCase = true))
|
||||
|
||||
/** Commit one physical probe only if it still belongs to the active cache generation. */
|
||||
private suspend fun completeProbe(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
generation: Long,
|
||||
reachable: Boolean,
|
||||
detail: String?,
|
||||
recordDiagnostic: () -> Unit,
|
||||
): Boolean {
|
||||
currentCoroutineContext().ensureActive()
|
||||
synchronized(probeStateLock) {
|
||||
if (generation != probeGeneration) {
|
||||
throw CancellationException("Endpoint probe invalidated")
|
||||
}
|
||||
recordDiagnostic()
|
||||
recordOutcome(candidate, surface, reachable, detail)
|
||||
val ttl = if (reachable) CACHE_TTL_MS else NEGATIVE_CACHE_TTL_MS
|
||||
probeCache[cacheKey(candidate, surface)] = CacheEntry(
|
||||
expiresAt = clock() + ttl,
|
||||
reachable = reachable,
|
||||
)
|
||||
}
|
||||
return reachable
|
||||
}
|
||||
|
||||
/** Choose the standard Dashboard/Gateway surface first when advertised. */
|
||||
private fun probeTarget(
|
||||
candidate: EndpointCandidate,
|
||||
@@ -499,10 +737,22 @@ class EndpointResolver(
|
||||
): ProbeTarget? {
|
||||
if (surface == EndpointSurface.Dashboard) {
|
||||
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { base ->
|
||||
return ProbeTarget(base, "$base/api/status", "/dashboard/api/status")
|
||||
return ProbeTarget(
|
||||
baseUrl = base,
|
||||
requestUrl = "$base/api/health",
|
||||
path = "/dashboard/api/health",
|
||||
legacyFallbackRequestUrl = "$base/api/status",
|
||||
legacyFallbackPath = "/dashboard/api/status",
|
||||
)
|
||||
}
|
||||
candidate.dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }?.let { base ->
|
||||
return ProbeTarget(base, "$base/api/status", "/api/status")
|
||||
return ProbeTarget(
|
||||
baseUrl = base,
|
||||
requestUrl = "$base/api/health",
|
||||
path = "/api/health",
|
||||
legacyFallbackRequestUrl = "$base/api/status",
|
||||
legacyFallbackPath = "/api/status",
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -530,8 +780,10 @@ class EndpointResolver(
|
||||
?.let { base ->
|
||||
return ProbeTarget(
|
||||
baseUrl = base,
|
||||
requestUrl = "$base/api/status",
|
||||
path = "/api/status",
|
||||
requestUrl = "$base/api/health",
|
||||
path = "/api/health",
|
||||
legacyFallbackRequestUrl = "$base/api/status",
|
||||
legacyFallbackPath = "/api/status",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -602,17 +854,19 @@ class EndpointResolver(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface = EndpointSurface.Standard,
|
||||
) {
|
||||
val key = cacheKey(candidate, surface)
|
||||
probeCache[key] = CacheEntry(
|
||||
expiresAt = clock() + NEGATIVE_CACHE_TTL_MS,
|
||||
reachable = false,
|
||||
)
|
||||
recordOutcome(
|
||||
candidate,
|
||||
surface,
|
||||
reachable = false,
|
||||
detail = "Network changed — assumed offline",
|
||||
)
|
||||
synchronized(probeStateLock) {
|
||||
val key = cacheKey(candidate, surface)
|
||||
probeCache[key] = CacheEntry(
|
||||
expiresAt = clock() + NEGATIVE_CACHE_TTL_MS,
|
||||
reachable = false,
|
||||
)
|
||||
recordOutcome(
|
||||
candidate,
|
||||
surface,
|
||||
reachable = false,
|
||||
detail = "Network changed — assumed offline",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -623,7 +877,17 @@ class EndpointResolver(
|
||||
* just-died route must not outlive the handoff.
|
||||
*/
|
||||
internal fun clearCache() {
|
||||
probeCache.clear()
|
||||
val staleProbes = synchronized(probeStateLock) {
|
||||
probeGeneration += 1L
|
||||
probeCache.clear()
|
||||
inFlightProbes.values.toList().also { inFlightProbes.clear() }
|
||||
}
|
||||
// An explicit re-probe must not join a request that began before the
|
||||
// invalidation signal. Cancellation is resolver-owned (not waiter-
|
||||
// owned), so ordinary lifecycle cancellation still leaves shared
|
||||
// probes alive for other callers. The generation check prevents a
|
||||
// late InterruptedIOException/response from publishing stale state.
|
||||
staleProbes.forEach { it.cancel() }
|
||||
}
|
||||
|
||||
/** Test-only: snapshot the current cache for assertion purposes. */
|
||||
|
||||
@@ -43,15 +43,16 @@ object HermesLanDiscovery {
|
||||
private const val TAG = "HermesLanDiscovery"
|
||||
private const val MAX_HOSTS = 254
|
||||
private const val MAX_CONCURRENT_PROBES = 32
|
||||
private const val PROBE_TIMEOUT_MS = 650L
|
||||
private const val PROBE_TIMEOUT_MS = 750L
|
||||
private const val IPV4_MASK = 0xFFFF_FFFFL
|
||||
|
||||
suspend fun scan(
|
||||
context: Context,
|
||||
apiPort: Int = 8642,
|
||||
dashboardPort: Int = 9119,
|
||||
dashboardOnly: Boolean = false,
|
||||
): List<HermesLanDiscoveryResult> = withContext(Dispatchers.IO) {
|
||||
val hosts = localLanHosts(context.applicationContext)
|
||||
val hosts = prioritizeHostSweep(localLanHosts(context.applicationContext))
|
||||
if (hosts.isEmpty()) return@withContext emptyList()
|
||||
|
||||
val client = OkHttpClient.Builder()
|
||||
@@ -66,7 +67,13 @@ object HermesLanDiscovery {
|
||||
hosts.map { host ->
|
||||
async {
|
||||
semaphore.withPermit {
|
||||
probeHost(client, host, apiPort, dashboardPort)?.let { result ->
|
||||
probeHost(
|
||||
client,
|
||||
host,
|
||||
apiPort,
|
||||
dashboardPort,
|
||||
dashboardOnly,
|
||||
)?.let { result ->
|
||||
result.copy(hostname = resolveHostname(host))
|
||||
}
|
||||
}
|
||||
@@ -88,6 +95,7 @@ object HermesLanDiscovery {
|
||||
host: String,
|
||||
apiPort: Int,
|
||||
dashboardPort: Int,
|
||||
dashboardOnly: Boolean,
|
||||
): HermesLanDiscoveryResult? {
|
||||
val apiUrl = "http://$host:$apiPort"
|
||||
val dashboardUrl = "http://$host:$dashboardPort"
|
||||
@@ -95,12 +103,18 @@ object HermesLanDiscovery {
|
||||
client = client,
|
||||
url = "$dashboardUrl/api/status",
|
||||
expectedBody = ::looksLikeDashboardStatus,
|
||||
attempts = 2,
|
||||
)
|
||||
val apiReachable = probe(
|
||||
client = client,
|
||||
url = "$apiUrl/health",
|
||||
expectedBody = ::looksLikeApiHealth,
|
||||
)
|
||||
if (dashboardOnly && !dashboardReachable) return null
|
||||
val apiReachable = if (dashboardOnly) {
|
||||
false
|
||||
} else {
|
||||
probe(
|
||||
client = client,
|
||||
url = "$apiUrl/health",
|
||||
expectedBody = ::looksLikeApiHealth,
|
||||
)
|
||||
}
|
||||
if (!dashboardReachable && !apiReachable) return null
|
||||
return HermesLanDiscoveryResult(
|
||||
host = host,
|
||||
@@ -115,6 +129,7 @@ object HermesLanDiscovery {
|
||||
client: OkHttpClient,
|
||||
url: String,
|
||||
expectedBody: (String, String) -> Boolean,
|
||||
attempts: Int = 1,
|
||||
): Boolean {
|
||||
val httpUrl = url.toHttpUrlOrNull() ?: return false
|
||||
val request = Request.Builder()
|
||||
@@ -123,21 +138,25 @@ object HermesLanDiscovery {
|
||||
.header("Accept", "application/json, text/plain, */*")
|
||||
.build()
|
||||
|
||||
return try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (response.code == 401 || response.code == 403) {
|
||||
return true
|
||||
repeat(attempts.coerceAtLeast(1)) { attempt ->
|
||||
try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (response.code == 401 || response.code == 403) {
|
||||
return true
|
||||
}
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code >= 500 && attempt + 1 < attempts) return@use
|
||||
return false
|
||||
}
|
||||
val contentType = response.header("Content-Type").orEmpty()
|
||||
val body = response.body.string().take(2_048)
|
||||
if (expectedBody(body, contentType)) return true
|
||||
}
|
||||
if (!response.isSuccessful) {
|
||||
return false
|
||||
}
|
||||
val contentType = response.header("Content-Type").orEmpty()
|
||||
val body = response.body.string().take(2_048)
|
||||
expectedBody(body, contentType)
|
||||
} catch (_: Exception) {
|
||||
if (attempt + 1 >= attempts) return false
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private suspend fun resolveHostname(address: String): String? =
|
||||
@@ -158,6 +177,23 @@ object HermesLanDiscovery {
|
||||
return normalized
|
||||
}
|
||||
|
||||
/** Interleave low/high host suffixes so `.1` and `.250` are both early. */
|
||||
internal fun prioritizeHostSweep(hosts: List<String>): List<String> {
|
||||
val sorted = hosts.distinct().sortedBy { address ->
|
||||
address.split('.').fold(0L) { acc, part ->
|
||||
(acc shl 8) + (part.toLongOrNull() ?: 0L)
|
||||
}
|
||||
}
|
||||
val prioritized = ArrayList<String>(sorted.size)
|
||||
var low = 0
|
||||
var high = sorted.lastIndex
|
||||
while (low <= high) {
|
||||
prioritized += sorted[low++]
|
||||
if (low <= high) prioritized += sorted[high--]
|
||||
}
|
||||
return prioritized
|
||||
}
|
||||
|
||||
private fun looksLikeDashboardStatus(body: String, contentType: String): Boolean {
|
||||
val lower = body.lowercase()
|
||||
return contentType.contains("json", ignoreCase = true) && (
|
||||
|
||||
@@ -1006,6 +1006,56 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bound the ephemeral, read-only child-watch projection. This is stricter
|
||||
* than the main transcript: system rows and tool results are not part of
|
||||
* the preview contract, and one live child must not retain unbounded text.
|
||||
*/
|
||||
internal fun boundReadOnlyPreview(
|
||||
maxMessages: Int = 100,
|
||||
maxTotalChars: Int = 32_000,
|
||||
maxFieldChars: Int = 8_000,
|
||||
maxToolChars: Int = 1_000,
|
||||
): Boolean {
|
||||
var truncated = false
|
||||
_messages.update { current ->
|
||||
val visible = current.filterNot { it.role == MessageRole.SYSTEM }
|
||||
if (visible.size != current.size || visible.size > maxMessages) truncated = true
|
||||
var remaining = maxTotalChars
|
||||
val kept = mutableListOf<ChatMessage>()
|
||||
visible.takeLast(maxMessages).asReversed().forEach { message ->
|
||||
if (remaining <= 0) {
|
||||
truncated = true
|
||||
return@forEach
|
||||
}
|
||||
fun bounded(value: String, limit: Int): String {
|
||||
val allowed = minOf(limit, remaining)
|
||||
val next = value.takeLast(allowed)
|
||||
if (next.length != value.length) truncated = true
|
||||
remaining -= next.length
|
||||
return next
|
||||
}
|
||||
val content = bounded(message.content, maxFieldChars)
|
||||
val thinking = bounded(message.thinkingContent, maxFieldChars)
|
||||
val tools = message.toolCalls.takeLast(50).map { tool ->
|
||||
if (message.toolCalls.size > 50) truncated = true
|
||||
tool.copy(
|
||||
args = tool.args?.let { bounded(it, maxToolChars) },
|
||||
result = null,
|
||||
error = tool.error?.let { bounded(it, maxToolChars) },
|
||||
)
|
||||
}
|
||||
kept += message.copy(
|
||||
content = content,
|
||||
thinkingContent = thinking,
|
||||
toolCalls = tools,
|
||||
)
|
||||
}
|
||||
kept.asReversed()
|
||||
}
|
||||
return truncated
|
||||
}
|
||||
|
||||
/**
|
||||
* Rehydrate the last client-owned state of an unfinished turn.
|
||||
*
|
||||
@@ -2036,7 +2086,7 @@ class ChatHandler {
|
||||
/**
|
||||
* Update sessions list from API response.
|
||||
*/
|
||||
fun updateSessions(items: List<SessionItem>) {
|
||||
fun updateSessions(items: List<SessionItem>, append: Boolean = false) {
|
||||
// Index the current rows so a server row that arrives without a title
|
||||
// can inherit a title we already know locally. Auto-titling is a
|
||||
// fire-and-forget background job on the server (upstream
|
||||
@@ -2109,9 +2159,22 @@ class ChatHandler {
|
||||
} else {
|
||||
null
|
||||
}
|
||||
_sessions.value = if (pending != null) listOf(pending) + mapped else mapped
|
||||
val resolved = if (append) {
|
||||
(_sessions.value + mapped)
|
||||
.distinctBy { it.sessionId }
|
||||
.sortedByDescending { it.activityTimestamp }
|
||||
} else {
|
||||
mapped
|
||||
}
|
||||
_sessions.value = if (pending != null && resolved.none { it.sessionId == pending.sessionId }) {
|
||||
listOf(pending) + resolved
|
||||
} else {
|
||||
resolved
|
||||
}
|
||||
}
|
||||
|
||||
fun appendSessions(items: List<SessionItem>) = updateSessions(items, append = true)
|
||||
|
||||
fun clearSessions() {
|
||||
_sessions.value = emptyList()
|
||||
}
|
||||
@@ -3030,7 +3093,9 @@ class ChatHandler {
|
||||
fun onSubagentEvent(messageId: String, event: GatewaySubagentEvent) {
|
||||
val label = event.goal.trim().take(60).ifBlank { null }
|
||||
when (event.phase) {
|
||||
GatewaySubagentEvent.Phase.START -> {
|
||||
GatewaySubagentEvent.Phase.SPAWN_REQUESTED,
|
||||
GatewaySubagentEvent.Phase.START,
|
||||
-> {
|
||||
if (label != null) subagentLabels[event.taskIndex] = label
|
||||
event.subagentId?.takeIf(String::isNotBlank)?.let {
|
||||
subagentIds[event.taskIndex] = it
|
||||
|
||||
+256
-95
@@ -18,6 +18,8 @@ import com.hermesandroid.relay.auth.SecureStoreCache
|
||||
import com.hermesandroid.relay.auth.SessionTokenStore
|
||||
import com.hermesandroid.relay.auth.buildRawTokenStore
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.SerialName
|
||||
@@ -34,6 +36,8 @@ import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.Cookie
|
||||
import okhttp3.CookieJar
|
||||
import okhttp3.HttpUrl
|
||||
@@ -50,6 +54,7 @@ import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resume
|
||||
import okio.BufferedSink
|
||||
|
||||
// Status/session/provider snapshots are @Serializable so the Manage tab's
|
||||
@@ -316,12 +321,16 @@ data class ElevenLabsVoices(
|
||||
class DashboardApiClient(
|
||||
baseUrl: String,
|
||||
private val okHttpClient: OkHttpClient = defaultClient(),
|
||||
private val ownsHttpClient: Boolean = true,
|
||||
private val json: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
coerceInputValues = true
|
||||
},
|
||||
private val nowMillis: () -> Long = System::currentTimeMillis,
|
||||
private val sessionReadTimeoutMillis: Long = SESSION_READ_TIMEOUT_MILLIS,
|
||||
private val controlReadTimeoutMillis: Long = CONTROL_READ_TIMEOUT_MILLIS,
|
||||
private val sessionEnrichmentBudgetMillis: Long = SESSION_ENRICHMENT_BUDGET_MILLIS,
|
||||
) {
|
||||
private val baseUrl: String = baseUrl.trim().trimEnd('/')
|
||||
private val sessionPrScanLock = Any()
|
||||
@@ -1027,16 +1036,20 @@ class DashboardApiClient(
|
||||
suspend fun listSessions(
|
||||
profile: String? = null,
|
||||
limit: Int = SESSION_LIST_WINDOW_LIMIT,
|
||||
offset: Int = 0,
|
||||
archived: String? = null,
|
||||
excludeSources: Collection<String> = emptyList(),
|
||||
): Result<List<SessionItem>> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val readDeadlineNanos = System.nanoTime() +
|
||||
TimeUnit.MILLISECONDS.toNanos(sessionReadTimeoutMillis.coerceAtLeast(1L))
|
||||
val sessions = linkedMapOf<String, SessionItem>()
|
||||
for (page in sessionListPages(limit)) {
|
||||
val query = buildList {
|
||||
// Upstream dashboard GET /api/sessions rejects pages over 100.
|
||||
// Keep Android's 200-row drawer window via two bounded pages.
|
||||
add("limit=${page.limit}")
|
||||
add("offset=${page.offset}")
|
||||
add("offset=${offset.coerceAtLeast(0) + page.offset}")
|
||||
add("order=recent")
|
||||
add("min_messages=1")
|
||||
val name = profile?.trim().orEmpty()
|
||||
@@ -1045,8 +1058,33 @@ class DashboardApiClient(
|
||||
// Omitted unless requested so older hosts see an unchanged request.
|
||||
val archivedMode = archived?.trim().orEmpty()
|
||||
if (archivedMode.isNotBlank()) add("archived=${pathSegment(archivedMode)}")
|
||||
val excluded = excludeSources
|
||||
.asSequence()
|
||||
.map(String::trim)
|
||||
.filter(String::isNotBlank)
|
||||
.map(String::lowercase)
|
||||
.distinct()
|
||||
.sorted()
|
||||
.toList()
|
||||
if (excluded.isNotEmpty()) {
|
||||
add("exclude_sources=${queryValue(excluded.joinToString(","))}")
|
||||
}
|
||||
}.joinToString(prefix = "?", separator = "&")
|
||||
val pageResult = getJson("/api/sessions$query").mapCatching { root ->
|
||||
val remainingReadMillis = TimeUnit.NANOSECONDS.toMillis(
|
||||
readDeadlineNanos - System.nanoTime(),
|
||||
)
|
||||
if (remainingReadMillis <= 0L) {
|
||||
return@withContext Result.failure(
|
||||
IOException("Dashboard session list exceeded its bounded read window"),
|
||||
)
|
||||
}
|
||||
val pageResult = getJson(
|
||||
"/api/sessions$query",
|
||||
// One budget covers the complete 200-row operation. A slow
|
||||
// first page cannot silently turn the nominal 8s bound into
|
||||
// 16s when the second page is needed.
|
||||
callTimeoutMillis = remainingReadMillis,
|
||||
).mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(SessionListResponse.serializer(), root)
|
||||
parsed.sessions ?: parsed.items ?: parsed.data ?: emptyList()
|
||||
}
|
||||
@@ -1055,13 +1093,20 @@ class DashboardApiClient(
|
||||
pageSessions.forEach { sessions.putIfAbsent(it.id, it) }
|
||||
if (pageSessions.size < page.limit) break
|
||||
}
|
||||
Result.success(
|
||||
val listed = sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT))
|
||||
// Repository/PR decoration is useful drawer metadata, but it is not
|
||||
// authoritative session data. Keep it off the critical path when an
|
||||
// older host or an unavailable GitHub helper stalls: return the exact
|
||||
// profile-scoped rows within a small budget and retry decoration on a
|
||||
// later refresh. Cancellation also cancels the active OkHttp call.
|
||||
val enriched = withTimeoutOrNull(sessionEnrichmentBudgetMillis) {
|
||||
enrichSessionWorkState(
|
||||
sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)),
|
||||
listed,
|
||||
fixedProfile = profile?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: DEFAULT_SESSION_PROFILE_SCOPE,
|
||||
),
|
||||
)
|
||||
)
|
||||
} ?: listed
|
||||
Result.success(enriched)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1227,7 +1272,10 @@ class DashboardApiClient(
|
||||
add("order=${page.order}")
|
||||
if (name.isNotBlank()) add("profile=${pathSegment(name)}")
|
||||
}.joinToString(prefix = "?", separator = "&")
|
||||
getJson("/api/sessions/${pathSegment(sessionId)}/messages$query").mapCatching { root ->
|
||||
getJson(
|
||||
"/api/sessions/${pathSegment(sessionId)}/messages$query",
|
||||
callTimeoutMillis = sessionReadTimeoutMillis,
|
||||
).mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(MessageListResponse.serializer(), root)
|
||||
SessionMessagePage(
|
||||
messages = parsed.messages ?: parsed.data ?: parsed.items ?: emptyList(),
|
||||
@@ -1471,10 +1519,14 @@ class DashboardApiClient(
|
||||
.post(ByteArray(0).toRequestBody(null))
|
||||
.build()
|
||||
|
||||
executeJson(request, "Dashboard websocket ticket").mapCatching { root ->
|
||||
executeJson(
|
||||
request,
|
||||
"Dashboard websocket ticket",
|
||||
callTimeoutMillis = controlReadTimeoutMillis,
|
||||
).mapCatching { root ->
|
||||
val ticket = root.stringField("ticket")
|
||||
?: root.stringField("ws_ticket")
|
||||
?: throw IOException("Dashboard websocket ticket response missing ticket")
|
||||
?: throw IllegalStateException("Dashboard websocket ticket response missing ticket")
|
||||
DashboardWsTicket(
|
||||
ticket = ticket,
|
||||
ttlSeconds = root.intField("ttl_seconds") ?: root.intField("ttl"),
|
||||
@@ -1496,44 +1548,77 @@ class DashboardApiClient(
|
||||
profile = profile,
|
||||
)
|
||||
|
||||
fun shutdown() = shutdownOffMainThread("DashboardApiClient-shutdown") {
|
||||
okHttpClient.dispatcher.executorService.shutdown()
|
||||
okHttpClient.connectionPool.evictAll()
|
||||
fun shutdown() {
|
||||
if (!ownsHttpClient) return
|
||||
shutdownOffMainThread("DashboardApiClient-shutdown") {
|
||||
okHttpClient.dispatcher.executorService.shutdown()
|
||||
okHttpClient.connectionPool.evictAll()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getJson(path: String): Result<JsonObject> = withContext(Dispatchers.IO) {
|
||||
private suspend fun getJson(
|
||||
path: String,
|
||||
callTimeoutMillis: Long? = null,
|
||||
): Result<JsonObject> = withContext(Dispatchers.IO) {
|
||||
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder()
|
||||
.url(httpUrl)
|
||||
.get()
|
||||
.build()
|
||||
executeJson(request, path)
|
||||
executeJson(request, path, callTimeoutMillis)
|
||||
}
|
||||
|
||||
private fun executeJson(request: Request, operation: String): Result<JsonObject> {
|
||||
return try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
return Result.failure(apiFailure(response, operation))
|
||||
}
|
||||
Result.success(response.readJsonObject(json))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
private suspend fun executeJson(
|
||||
request: Request,
|
||||
operation: String,
|
||||
callTimeoutMillis: Long? = null,
|
||||
): Result<JsonObject> = executeCancellable(request, operation, callTimeoutMillis) { response ->
|
||||
response.readJsonObject(json)
|
||||
}
|
||||
|
||||
private fun executeJsonElement(request: Request, operation: String): Result<JsonElement> {
|
||||
return try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
return Result.failure(apiFailure(response, operation))
|
||||
}
|
||||
Result.success(response.readJsonElement(json))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
private suspend fun executeJsonElement(
|
||||
request: Request,
|
||||
operation: String,
|
||||
): Result<JsonElement> = executeCancellable(request, operation) { response ->
|
||||
response.readJsonElement(json)
|
||||
}
|
||||
|
||||
/** Bridge OkHttp cancellation to the owning coroutine so superseded profile reads do not linger. */
|
||||
private suspend fun <T> executeCancellable(
|
||||
request: Request,
|
||||
operation: String,
|
||||
callTimeoutMillis: Long? = null,
|
||||
decode: (Response) -> T,
|
||||
): Result<T> = suspendCancellableCoroutine { continuation ->
|
||||
val call = okHttpClient.newCall(request)
|
||||
callTimeoutMillis?.takeIf { it > 0L }?.let {
|
||||
call.timeout().timeout(it, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
continuation.invokeOnCancellation { call.cancel() }
|
||||
call.enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
runCatching {
|
||||
if (continuation.isActive) continuation.resume(Result.failure(e))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
val result = response.use {
|
||||
try {
|
||||
if (!it.isSuccessful) {
|
||||
Result.failure(apiFailure(it, operation))
|
||||
} else {
|
||||
Result.success(decode(it))
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
runCatching {
|
||||
if (continuation.isActive) continuation.resume(result)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private suspend fun download(
|
||||
@@ -1570,6 +1655,13 @@ class DashboardApiClient(
|
||||
companion object {
|
||||
private val JSON_MEDIA = "application/json; charset=utf-8".toMediaType()
|
||||
private const val DEFAULT_SESSION_PROFILE_SCOPE = "__dashboard_default__"
|
||||
// Desktop allows 60s for its 40-row recents request. Android uses a
|
||||
// similarly small initial window and a bounded 20s mobile budget;
|
||||
// the old 8s deadline repeatedly cancelled valid first-load reads on
|
||||
// large profile databases before any row could be shown.
|
||||
private const val SESSION_READ_TIMEOUT_MILLIS = 20_000L
|
||||
private const val CONTROL_READ_TIMEOUT_MILLIS = 8_000L
|
||||
private const val SESSION_ENRICHMENT_BUDGET_MILLIS = 1_500L
|
||||
internal const val ACTIVE_SESSION_PR_MISS_TTL_MILLIS = 60_000L
|
||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||
// client-side avoids uploading a body the Dashboard will reject.
|
||||
@@ -1712,8 +1804,9 @@ class DashboardApiClient(
|
||||
cookieStore: DashboardCookieStore = InMemoryDashboardCookieStore(),
|
||||
bearerAuth: DashboardBearerAuth? = null,
|
||||
): OkHttpClient {
|
||||
val cookieJar = DashboardCookieJar(cookieStore)
|
||||
val builder = OkHttpClient.Builder()
|
||||
.cookieJar(DashboardCookieJar(cookieStore))
|
||||
.cookieJar(cookieJar)
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
// Skills-hub search fans out server-side with a 30s overall
|
||||
// timeout; keep the read window above it so a slow-but-successful
|
||||
@@ -1721,6 +1814,7 @@ class DashboardApiClient(
|
||||
.readTimeout(45, TimeUnit.SECONDS)
|
||||
.writeTimeout(30, TimeUnit.SECONDS)
|
||||
bearerAuth?.let {
|
||||
it.preferCookiesWhen(cookieJar::hasCookiesFor)
|
||||
builder.addInterceptor(it)
|
||||
builder.authenticator(it)
|
||||
}
|
||||
@@ -2080,14 +2174,20 @@ class DashboardCookieJar(
|
||||
private val store: DashboardCookieStore,
|
||||
private val clockMillis: () -> Long = { System.currentTimeMillis() },
|
||||
) : CookieJar {
|
||||
fun hasCookiesFor(url: HttpUrl): Boolean = loadForRequest(url).isNotEmpty()
|
||||
|
||||
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
|
||||
val now = clockMillis()
|
||||
val incoming = cookies.map { StoredDashboardCookie.fromCookie(it) }
|
||||
.filterNot { it.isExpired(now) }
|
||||
val incomingSessionFamilies = incoming.mapNotNullTo(mutableSetOf()) {
|
||||
it.sessionFamilyKey()
|
||||
}
|
||||
val retained = store.load()
|
||||
.filterNot { it.isExpired(now) }
|
||||
.filterNot { old -> incoming.any { it.key == old.key } }
|
||||
store.save(retained + incoming)
|
||||
.filterNot { old -> old.sessionFamilyKey() in incomingSessionFamilies }
|
||||
store.save(collapseDashboardSessionCookieVariants(retained + incoming))
|
||||
}
|
||||
|
||||
override fun loadForRequest(url: HttpUrl): List<Cookie> {
|
||||
@@ -2095,7 +2195,9 @@ class DashboardCookieJar(
|
||||
// Load once (each load() is a decrypt + JSON decode); prune expired
|
||||
// entries back to disk only when something actually expired.
|
||||
val all = store.load()
|
||||
val stored = all.filterNot { it.isExpired(now) }
|
||||
val stored = collapseDashboardSessionCookieVariants(
|
||||
all.filterNot { it.isExpired(now) },
|
||||
)
|
||||
if (stored.size != all.size) {
|
||||
store.save(stored)
|
||||
}
|
||||
@@ -2104,61 +2206,6 @@ class DashboardCookieJar(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy only Hermes' authenticated dashboard session cookies to another host
|
||||
* that belongs to the same saved Connection. Dashboard cookies are host-only
|
||||
* by design, while a Connection may reach one server through LAN and
|
||||
* Tailscale hostnames/IPs. The encrypted store remains the source of truth and
|
||||
* explicit sign-out clears every mirrored host together.
|
||||
*
|
||||
* PKCE, SSO-attempt, and unrelated application cookies are intentionally not
|
||||
* copied. Secure cookies also remain Secure; this helper never downgrades them
|
||||
* for an HTTP route.
|
||||
*/
|
||||
fun mirrorDashboardSessionCookies(
|
||||
store: DashboardCookieStore,
|
||||
targetUrl: String,
|
||||
trustedHosts: Set<String>,
|
||||
clockMillis: () -> Long = { System.currentTimeMillis() },
|
||||
): Int {
|
||||
val targetHost = targetUrl.toHttpUrlOrNull()?.host?.lowercase() ?: return 0
|
||||
val allowedHosts = trustedHosts.mapTo(mutableSetOf()) { it.lowercase() }
|
||||
if (targetHost !in allowedHosts) return 0
|
||||
|
||||
val now = clockMillis()
|
||||
val all = store.load()
|
||||
val live = all.filterNot { it.isExpired(now) }
|
||||
val existingTargetKeys = live.asSequence()
|
||||
.filter { it.domain.equals(targetHost, ignoreCase = true) }
|
||||
.map { "${it.name.lowercase()}|$targetHost|${it.path}" }
|
||||
.toSet()
|
||||
val mirrored = live.asSequence()
|
||||
.filter { it.isDashboardSessionCookie() }
|
||||
.filter { it.domain.lowercase() in allowedHosts }
|
||||
.filterNot { it.domain.equals(targetHost, ignoreCase = true) }
|
||||
.groupBy { "${it.name.lowercase()}|${it.path}" }
|
||||
.values
|
||||
.mapNotNull { candidates -> candidates.maxByOrNull { it.expiresAt } }
|
||||
.map { it.copy(domain = targetHost, hostOnly = true) }
|
||||
.filterNot { it.key in existingTargetKeys }
|
||||
.toList()
|
||||
|
||||
if (mirrored.isNotEmpty() || live.size != all.size) {
|
||||
store.save(live + mirrored)
|
||||
}
|
||||
return mirrored.size
|
||||
}
|
||||
|
||||
private fun StoredDashboardCookie.isDashboardSessionCookie(): Boolean {
|
||||
val bareName = name
|
||||
.removePrefix("__Host-")
|
||||
.removePrefix("__Secure-")
|
||||
return bareName == "hermes_session" ||
|
||||
bareName == "hermes_session_at" ||
|
||||
bareName == "hermes_session_rt" ||
|
||||
bareName == "hermes_session_provider"
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookie jar that resolves the backing per-connection store at request time.
|
||||
*
|
||||
@@ -2220,13 +2267,78 @@ fun importDashboardCookieHeader(
|
||||
.filterNot { it.isExpired(now) }
|
||||
if (imported.isEmpty()) return 0
|
||||
|
||||
val importedSessionFamilies = imported.mapNotNullTo(mutableSetOf()) {
|
||||
it.sessionFamilyKey()
|
||||
}
|
||||
val retained = store.load()
|
||||
.filterNot { it.isExpired(now) }
|
||||
.filterNot { old -> imported.any { it.key == old.key } }
|
||||
store.save(retained + imported)
|
||||
.filterNot { old -> old.sessionFamilyKey() in importedSessionFamilies }
|
||||
store.save(collapseDashboardSessionCookieVariants(retained + imported))
|
||||
return imported.size
|
||||
}
|
||||
|
||||
private val DASHBOARD_SESSION_COOKIE_FAMILIES = setOf(
|
||||
"hermes_session",
|
||||
"hermes_session_at",
|
||||
"hermes_session_rt",
|
||||
"hermes_session_provider",
|
||||
)
|
||||
|
||||
internal val DASHBOARD_SESSION_COOKIE_VARIANT_NAMES: List<String> =
|
||||
DASHBOARD_SESSION_COOKIE_FAMILIES.flatMap { name ->
|
||||
listOf(name, "__Host-$name", "__Secure-$name")
|
||||
}
|
||||
|
||||
private fun isDashboardSessionCookieName(name: String): Boolean =
|
||||
name.lowercase()
|
||||
.removePrefix("__host-")
|
||||
.removePrefix("__secure-") in DASHBOARD_SESSION_COOKIE_FAMILIES
|
||||
|
||||
/**
|
||||
* Clear only Hermes session cookies that would be attached to [requestUrl].
|
||||
* Called solely after an explicit provider selection; background 503 probes
|
||||
* never mutate auth state.
|
||||
*/
|
||||
internal fun clearDashboardSessionCookiesForRequest(
|
||||
store: DashboardCookieStore,
|
||||
requestUrl: String,
|
||||
): Int {
|
||||
val url = requestUrl.toHttpUrlOrNull() ?: return 0
|
||||
val current = store.load()
|
||||
val retained = current.filterNot { stored ->
|
||||
isDashboardSessionCookieName(stored.name) && stored.toCookie()?.matches(url) == true
|
||||
}
|
||||
if (retained.size != current.size) store.save(retained)
|
||||
return current.size - retained.size
|
||||
}
|
||||
|
||||
private fun StoredDashboardCookie.sessionFamilyKey(): String? {
|
||||
val normalized = name.lowercase()
|
||||
.removePrefix("__host-")
|
||||
.removePrefix("__secure-")
|
||||
if (normalized !in DASHBOARD_SESSION_COOKIE_FAMILIES) return null
|
||||
return "$normalized|${domain.lowercase()}|$path"
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTPS/proxy changes can leave bare, `__Host-`, and `__Secure-` variants in
|
||||
* Android's imported WebView store. Hermes treats those names as one logical
|
||||
* session family and prefers the strict prefix, so coexistence can revive an
|
||||
* older provider session. Preserve list order and keep only the newest variant.
|
||||
*/
|
||||
private fun collapseDashboardSessionCookieVariants(
|
||||
cookies: List<StoredDashboardCookie>,
|
||||
): List<StoredDashboardCookie> {
|
||||
val lastIndexByFamily = mutableMapOf<String, Int>()
|
||||
cookies.forEachIndexed { index, cookie ->
|
||||
cookie.sessionFamilyKey()?.let { lastIndexByFamily[it] = index }
|
||||
}
|
||||
return cookies.filterIndexed { index, cookie ->
|
||||
cookie.sessionFamilyKey()?.let { lastIndexByFamily[it] == index } ?: true
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class StoredDashboardCookie(
|
||||
val name: String,
|
||||
@@ -2293,10 +2405,59 @@ private fun Response.readJsonElement(json: Json): JsonElement {
|
||||
return json.parseToJsonElement(raw)
|
||||
}
|
||||
|
||||
internal class DashboardHttpException(
|
||||
val statusCode: Int,
|
||||
message: String,
|
||||
) : IOException(message)
|
||||
|
||||
internal fun Throwable.isDashboardAuthProviderUnavailable(): 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 &&
|
||||
current.statusCode == 503 &&
|
||||
current.message.orEmpty().contains("Auth provider", ignoreCase = true) &&
|
||||
current.message.orEmpty().contains("unreachable", ignoreCase = true)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
current = current.cause
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
if (isDashboardAuthProviderUnavailable()) return true
|
||||
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 &&
|
||||
current.statusCode == 401 &&
|
||||
(
|
||||
current.message.orEmpty().contains("no_cookie", ignoreCase = true) ||
|
||||
current.message.orEmpty().contains("unauthenticated", ignoreCase = true)
|
||||
)
|
||||
) {
|
||||
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 }
|
||||
return IOException("$operation failed - HTTP ${response.code}: $detail")
|
||||
return DashboardHttpException(
|
||||
statusCode = response.code,
|
||||
message = "$operation failed - HTTP ${response.code}: $detail",
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject?.stringField(name: String): String? =
|
||||
|
||||
+624
-49
@@ -104,6 +104,12 @@ class GatewayChatClient(
|
||||
private val callbackDispatcher: (block: () -> Unit) -> Unit = MainThreadDispatcher,
|
||||
/** Surface for "this server has no usable /api/ws" — flips availability to Unsupported. */
|
||||
private val onGatewayUnsupported: () -> Unit = {},
|
||||
/** Ticket/upgrade auth rejection is distinct from an unsupported Gateway. */
|
||||
private val onGatewaySignInRequired: () -> Unit = {},
|
||||
/** A bounded ticket/connect failure makes this route unreachable for now. */
|
||||
private val onGatewayUnreachable: () -> Unit = {},
|
||||
/** A completed gateway.ready handshake is authoritative live transport evidence. */
|
||||
private val onGatewayReady: () -> Unit = {},
|
||||
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
|
||||
/** Max wall-clock a single mid-turn reconnect keeps retrying before failing the turn. */
|
||||
private val midTurnRejoinWindowMs: Long = MAX_MIDTURN_REJOIN_MS,
|
||||
@@ -204,11 +210,16 @@ class GatewayChatClient(
|
||||
|
||||
/** Cooldown after a failed connect so rapid sends don't hammer a down server. */
|
||||
private const val CONNECT_FAILURE_COOLDOWN_MS = 5_000L
|
||||
private const val MAX_CONNECT_FAILURE_COOLDOWN_MS = 30_000L
|
||||
private const val COLD_START_FAILURE_EPISODE_LIMIT = 5
|
||||
private const val RATE_LIMIT_COOLDOWN_MS = 300_000L
|
||||
private const val CONNECT_ATTEMPTS = 2
|
||||
private const val INBOUND_BIND_TIMEOUT_MS = 2_000L
|
||||
private const val CANCELLED_TURN_SUBMIT_WAIT_MS = 2_000L
|
||||
private const val MAX_RECOVERY_BUFFERED_EVENTS = 256
|
||||
internal const val MAX_CHILD_WATCH_HISTORY_ITEMS = 200
|
||||
internal const val MAX_CHILD_WATCH_HISTORY_CHARS = 64_000
|
||||
private const val MAX_PENDING_CHILD_WATCH_EVENTS = 256
|
||||
|
||||
/** Distinct socket-loss (flap) events per turn we'll try to recover from. */
|
||||
private const val MAX_TURN_REJOINS = 4
|
||||
@@ -270,6 +281,13 @@ class GatewayChatClient(
|
||||
|
||||
private val _connectionState = MutableStateFlow(GatewayConnectionState.Idle)
|
||||
val connectionState: StateFlow<GatewayConnectionState> = _connectionState.asStateFlow()
|
||||
private val _reconnectDisposition = MutableStateFlow(GatewayReconnectDisposition.Retryable)
|
||||
val reconnectDisposition: StateFlow<GatewayReconnectDisposition> =
|
||||
_reconnectDisposition.asStateFlow()
|
||||
|
||||
/** Delay a foreground reconnect only while the bounded failure cooldown is active. */
|
||||
fun remainingConnectCooldownMillis(nowMillis: Long = System.currentTimeMillis()): Long =
|
||||
(connectCooldownUntil - nowMillis).coerceAtLeast(0L)
|
||||
|
||||
/**
|
||||
* Per-socket feature probe for upstream's session-scoped `process.*` RPCs.
|
||||
@@ -381,6 +399,15 @@ class GatewayChatClient(
|
||||
private val prewarmRequestGeneration = AtomicLong(0)
|
||||
private val pendingRpcs = ConcurrentHashMap<Long, CompletableDeferred<JsonObject>>()
|
||||
|
||||
/** Monotonic client-local fence for lazy child watch open/close races. */
|
||||
private val childWatchGeneration = AtomicLong(0)
|
||||
|
||||
/** Live child runtime id -> exact watcher that owns its callbacks. */
|
||||
private val childWatches = ConcurrentHashMap<String, ChildWatchRegistration>()
|
||||
|
||||
/** Events that race a lazy `session.resume` acknowledgement. */
|
||||
private val pendingChildWatchOpens = ConcurrentHashMap<Long, PendingChildWatchOpen>()
|
||||
|
||||
/** Live (per-connection) session id ←→ the stored DB id it was resumed/created from. */
|
||||
@Volatile
|
||||
private var liveSessionId: String? = null
|
||||
@@ -447,6 +474,62 @@ class GatewayChatClient(
|
||||
@Volatile var pendingAsk: GatewayAsk? = null,
|
||||
)
|
||||
|
||||
private class ChildWatchRegistration(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val profile: String?,
|
||||
val generation: Long,
|
||||
val callbacks: GatewayTurnCallbacks,
|
||||
) {
|
||||
lateinit var mapper: GatewayEventMapper
|
||||
}
|
||||
|
||||
private data class ChildWatchEvent(
|
||||
val sessionId: String,
|
||||
val type: String,
|
||||
val payload: JsonObject?,
|
||||
)
|
||||
|
||||
private data class PendingChildWatchReplay(
|
||||
val events: List<ChildWatchEvent>,
|
||||
val truncated: Boolean,
|
||||
)
|
||||
|
||||
private class PendingChildWatchOpen {
|
||||
private val lock = Any()
|
||||
private val events = mutableListOf<ChildWatchEvent>()
|
||||
private var closed = false
|
||||
private var truncated = false
|
||||
|
||||
fun capture(event: ChildWatchEvent): Boolean = synchronized(lock) {
|
||||
if (closed) return@synchronized false
|
||||
if (events.size >= MAX_PENDING_CHILD_WATCH_EVENTS) {
|
||||
events.removeAt(0)
|
||||
truncated = true
|
||||
}
|
||||
events += event
|
||||
true
|
||||
}
|
||||
|
||||
fun closeAndTake(sessionId: String): PendingChildWatchReplay = synchronized(lock) {
|
||||
closed = true
|
||||
PendingChildWatchReplay(
|
||||
events = events.filter { it.sessionId == sessionId },
|
||||
truncated = truncated,
|
||||
).also { events.clear() }
|
||||
}
|
||||
|
||||
fun close() = synchronized(lock) {
|
||||
closed = true
|
||||
events.clear()
|
||||
}
|
||||
}
|
||||
|
||||
private data class BoundedChildHistory(
|
||||
val messages: List<MessageItem>,
|
||||
val truncated: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Upstream may emit the interrupted turn's tail and terminal event after
|
||||
* `session.interrupt` returns. Keep a short exact-session tombstone so that
|
||||
@@ -495,6 +578,10 @@ class GatewayChatClient(
|
||||
@Volatile
|
||||
private var processEventListener: ((GatewayProcessEvent) -> Unit)? = null
|
||||
|
||||
/** Process-wide durable-session invalidation/liveness edge. */
|
||||
@Volatile
|
||||
private var sessionDirectoryInvalidationListener: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Which upload RPC name this socket understands — set after the first
|
||||
* successful upload so the legacy fallback is probed at most once per
|
||||
@@ -509,6 +596,8 @@ class GatewayChatClient(
|
||||
|
||||
@Volatile
|
||||
private var connectCooldownUntil: Long = 0L
|
||||
private var hasEverReachedReady = false
|
||||
private var coldStartFailureEpisodes = 0
|
||||
|
||||
/**
|
||||
* When true, the socket is never auto-closed on background — the opt-in
|
||||
@@ -890,6 +979,10 @@ class GatewayChatClient(
|
||||
processEventListener = listener
|
||||
}
|
||||
|
||||
fun setSessionDirectoryInvalidationListener(listener: (() -> Unit)?) {
|
||||
sessionDirectoryInvalidationListener = listener
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish the socket (and resume an existing session) ahead of the
|
||||
* user's first send, so a warm turn reaches first token in tens of ms
|
||||
@@ -906,6 +999,30 @@ class GatewayChatClient(
|
||||
scope.launch { prewarmAwait(storedSessionId) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish only the shared Gateway socket for read-only observation.
|
||||
*
|
||||
* `session.resume` and `session.activate` attach a live runtime to this
|
||||
* transport. Opening Chat, foreground restoration, and selecting a saved
|
||||
* transcript must not claim a turn that another Desktop/TUI client owns,
|
||||
* so those paths use this socket-only warmup and observe through REST
|
||||
* history plus `session.active_list` instead.
|
||||
*/
|
||||
fun observe(onReady: (() -> Unit)? = null) {
|
||||
scope.launch {
|
||||
if (observeAwait() && onReady != null) callbackDispatcher(onReady)
|
||||
}
|
||||
}
|
||||
|
||||
/** Suspending [observe]; returns true once the read-only socket is ready. */
|
||||
suspend fun observeAwait(): Boolean = try {
|
||||
connectMutex.withLock { ensureConnected() }
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Gateway observation warmup skipped: ${e.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* Suspending [prewarm]: establishes the socket and (when [storedSessionId]
|
||||
* is non-null) resumes the existing session, returning only once that work
|
||||
@@ -947,6 +1064,200 @@ class GatewayChatClient(
|
||||
return sessionReady
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the vanilla-upstream child-session watcher advertised by
|
||||
* `subagent.*.child_session_id`. This RPC deliberately does not mutate
|
||||
* [liveSessionId], [storedSessionId], or [liveSessionProfile]: the parent
|
||||
* conversation keeps owning the main mapper while the returned short live
|
||||
* id routes a second, read-only event stream on the same socket.
|
||||
*
|
||||
* Returned history is bounded locally even when an upstream gateway sends
|
||||
* the child's entire transcript in the resume acknowledgement. The server
|
||||
* may still enforce its own larger resume safety limit before replying.
|
||||
*/
|
||||
suspend fun openChildWatch(
|
||||
childSessionId: String,
|
||||
profile: String? = currentSessionProfile(),
|
||||
callbacks: GatewayTurnCallbacks,
|
||||
historyLimit: Int = MAX_CHILD_WATCH_HISTORY_ITEMS,
|
||||
): Result<GatewayChildWatch> = runCatching {
|
||||
val storedChildId = childSessionId.trim()
|
||||
require(storedChildId.isNotEmpty()) { "child session id is required" }
|
||||
val requestedProfile = profile?.trim()?.takeIf(String::isNotEmpty)
|
||||
connectMutex.withLock {
|
||||
// Allocate and register under the same mutex as the resume RPC so
|
||||
// concurrent opens complete in generation order; an older caller
|
||||
// can never `put` after a newer one for the same live child id.
|
||||
val generation = childWatchGeneration.incrementAndGet()
|
||||
val pending = PendingChildWatchOpen()
|
||||
pendingChildWatchOpens[generation] = pending
|
||||
try {
|
||||
ensureConnected()
|
||||
val result = rpc(
|
||||
"session.resume",
|
||||
buildJsonObject {
|
||||
put("session_id", storedChildId)
|
||||
put("cols", DEFAULT_COLS)
|
||||
put("source", sessionSource)
|
||||
put("lazy", true)
|
||||
put("close_on_disconnect", true)
|
||||
requestedProfile?.let { put("profile", it) }
|
||||
},
|
||||
).getOrElse { error ->
|
||||
throw GatewayPreflightException(
|
||||
"child session resume failed: ${error.message}",
|
||||
)
|
||||
}
|
||||
val liveChildId = result.stringField("session_id")?.takeIf(String::isNotBlank)
|
||||
?: throw GatewayPreflightException(
|
||||
"child session resume returned no live session id",
|
||||
)
|
||||
try {
|
||||
requireConfirmedSessionProfile(result, requestedProfile)
|
||||
} catch (error: GatewayPreflightException) {
|
||||
// The wrong profile must not leave an unowned lazy watcher behind.
|
||||
rpc(
|
||||
"session.close",
|
||||
buildJsonObject { put("session_id", liveChildId) },
|
||||
)
|
||||
throw error
|
||||
}
|
||||
|
||||
val registration = ChildWatchRegistration(
|
||||
storedSessionId = storedChildId,
|
||||
liveSessionId = liveChildId,
|
||||
profile = requestedProfile,
|
||||
generation = generation,
|
||||
callbacks = callbacks,
|
||||
)
|
||||
val dispatchedCallbacks = dispatchOn(callbacks) {
|
||||
childWatches[liveChildId] === registration
|
||||
}
|
||||
registration.mapper = GatewayEventMapper(
|
||||
dispatchedCallbacks,
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
)
|
||||
childWatches.put(liveChildId, registration)?.let { prior ->
|
||||
if (prior.generation != generation) {
|
||||
notifyChildWatchFailure(
|
||||
prior,
|
||||
"Child watch was replaced by a newer view",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Replay only frames tagged with the exact live id returned by
|
||||
// this resume. Unknown gateway sessions captured during the
|
||||
// narrow ack race remain foreign and are discarded.
|
||||
val replay = pending.closeAndTake(liveChildId)
|
||||
if (replay.truncated) dispatchedCallbacks.onReconcileRequired()
|
||||
replay.events.forEach { event ->
|
||||
if (childWatches[liveChildId] === registration) {
|
||||
registration.mapper.onEvent(event.type, event.payload)
|
||||
}
|
||||
}
|
||||
val replayedTerminal = replay.events.any {
|
||||
it.type == "message.complete" || it.type == "error"
|
||||
}
|
||||
|
||||
val history = parseChildWatchMessages(result, historyLimit)
|
||||
GatewayChildWatch(
|
||||
storedSessionId = storedChildId,
|
||||
liveSessionId = liveChildId,
|
||||
profile = requestedProfile,
|
||||
generation = generation,
|
||||
messages = history.messages,
|
||||
historyTruncated = history.truncated,
|
||||
running = !replayedTerminal && result.booleanField("running") == true,
|
||||
status = if (replayedTerminal) "idle" else result.stringField("status"),
|
||||
)
|
||||
} finally {
|
||||
pendingChildWatchOpens.remove(generation, pending)
|
||||
pending.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close only the exact lazy watcher represented by [watch]. A stale handle
|
||||
* is a no-op so it can never close a newer watcher whose live id was reused.
|
||||
* The parent session and delegated child continue running server-side.
|
||||
*/
|
||||
suspend fun closeChildWatch(watch: GatewayChildWatch): Result<Unit> =
|
||||
connectMutex.withLock {
|
||||
val registration = childWatches[watch.liveSessionId]
|
||||
?: return@withLock Result.success(Unit)
|
||||
if (
|
||||
registration.generation != watch.generation ||
|
||||
registration.storedSessionId != watch.storedSessionId ||
|
||||
registration.profile != watch.profile ||
|
||||
!childWatches.remove(watch.liveSessionId, registration)
|
||||
) {
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
if (webSocket == null || readySignal?.isCompleted != true) {
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
val result = rpc(
|
||||
"session.close",
|
||||
buildJsonObject { put("session_id", watch.liveSessionId) },
|
||||
)
|
||||
result.fold(
|
||||
onSuccess = { Result.success(Unit) },
|
||||
onFailure = { error ->
|
||||
// Permit an exact-handle retry. Opens share connectMutex,
|
||||
// so no newer registration can race this restoration.
|
||||
childWatches.putIfAbsent(watch.liveSessionId, registration)
|
||||
Result.failure(error)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseChildWatchMessages(
|
||||
result: JsonObject,
|
||||
requestedLimit: Int,
|
||||
): BoundedChildHistory {
|
||||
val limit = requestedLimit.coerceIn(1, MAX_CHILD_WATCH_HISTORY_ITEMS)
|
||||
val all = (result["messages"] as? JsonArray).orEmpty()
|
||||
val raw = all.takeLast(limit)
|
||||
var retainedChars = 0
|
||||
var truncated = all.size > raw.size
|
||||
val newestFirst = raw.asReversed().mapNotNull { element ->
|
||||
val message = element as? JsonObject ?: run {
|
||||
truncated = true
|
||||
return@mapNotNull null
|
||||
}
|
||||
// Gateway display history uses `text`; the shared session DTO uses
|
||||
// `content`. Normalize only that projection boundary.
|
||||
val normalized = JsonObject(message.toMutableMap().apply {
|
||||
if (!containsKey("content")) {
|
||||
put("content", message["text"] ?: message["context"] ?: JsonNull)
|
||||
}
|
||||
if (!containsKey("tool_name") && message.containsKey("name")) {
|
||||
put("tool_name", message["name"] ?: JsonNull)
|
||||
}
|
||||
})
|
||||
val serializedChars = normalized.toString().length
|
||||
if (serializedChars > MAX_CHILD_WATCH_HISTORY_CHARS - retainedChars) {
|
||||
truncated = true
|
||||
return@mapNotNull null
|
||||
}
|
||||
val decoded = runCatching {
|
||||
json.decodeFromJsonElement(MessageItem.serializer(), normalized)
|
||||
}.onFailure {
|
||||
Log.w(TAG, "child watch returned an unreadable history row", it)
|
||||
}.getOrNull()
|
||||
if (decoded == null) {
|
||||
truncated = true
|
||||
null
|
||||
} else {
|
||||
retainedChars += serializedChars
|
||||
decoded
|
||||
}
|
||||
}
|
||||
return BoundedChildHistory(newestFirst.asReversed(), truncated)
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain a session-scoped target before a model-selection `config.set`.
|
||||
*
|
||||
@@ -2525,6 +2836,7 @@ class GatewayChatClient(
|
||||
unmatchedTurnCompleteListener = null
|
||||
backgroundInteractionListener = null
|
||||
processEventListener = null
|
||||
sessionDirectoryInvalidationListener = null
|
||||
closeSocket("client shutdown")
|
||||
backgroundCloseJob?.cancel()
|
||||
// Stop the foreground collector — a replaced client must not keep
|
||||
@@ -2544,21 +2856,73 @@ class GatewayChatClient(
|
||||
throw GatewayPreflightException("gateway connect cooling down")
|
||||
}
|
||||
|
||||
// Two attempts: a just-died socket (network switch, server restart)
|
||||
// can poison the first try via a stale pooled connection. Each
|
||||
// attempt mints a FRESH single-use ticket — never reuse one.
|
||||
// A just-died pooled socket can poison the first WebSocket upgrade, so
|
||||
// that narrow transport failure gets one fresh-ticket retry. A ticket
|
||||
// 5xx and transport failures are transient (notably while the
|
||||
// Dashboard or Android's active network settles). Auth rejection and
|
||||
// rate limiting stay single-attempt; a bounded ticket timeout gets one
|
||||
// fresh attempt instead of leaving cold start permanently disconnected.
|
||||
var lastFailure = "gateway connect failed"
|
||||
repeat(CONNECT_ATTEMPTS) { attempt ->
|
||||
var terminalStage: GatewayConnectFailureStage? = null
|
||||
var terminalRetryAfterCooldown = false
|
||||
for (attempt in 0 until CONNECT_ATTEMPTS) {
|
||||
try {
|
||||
connectOnce()
|
||||
connectCooldownUntil = 0L
|
||||
return
|
||||
} catch (e: GatewayConnectAttemptException) {
|
||||
lastFailure = e.message ?: lastFailure
|
||||
Log.w(TAG, "Gateway connect attempt ${attempt + 1}/$CONNECT_ATTEMPTS failed: $lastFailure")
|
||||
terminalStage = e.stage
|
||||
terminalRetryAfterCooldown = e.retryAfterCooldown
|
||||
Log.w(
|
||||
TAG,
|
||||
"Gateway connect attempt ${attempt + 1}/$CONNECT_ATTEMPTS failed " +
|
||||
"(stage=${e.stage.logName}, retryable=${e.retryable}): $lastFailure",
|
||||
)
|
||||
if (!e.retryable) break
|
||||
}
|
||||
}
|
||||
connectCooldownUntil = System.currentTimeMillis() + CONNECT_FAILURE_COOLDOWN_MS
|
||||
when (terminalStage) {
|
||||
GatewayConnectFailureStage.TicketAuth,
|
||||
GatewayConnectFailureStage.UpgradeAuth -> onGatewaySignInRequired()
|
||||
GatewayConnectFailureStage.Ticket,
|
||||
GatewayConnectFailureStage.Upgrade -> {
|
||||
// A timeout is not a definitive availability verdict. Keep
|
||||
// the Gateway unresolved so the visible-chat owner remains
|
||||
// on this transport and can retry after the cooldown.
|
||||
if (!terminalRetryAfterCooldown) onGatewayUnreachable()
|
||||
}
|
||||
GatewayConnectFailureStage.Unsupported -> onGatewayUnsupported()
|
||||
null -> Unit
|
||||
}
|
||||
if (terminalRetryAfterCooldown && !hasEverReachedReady) {
|
||||
coldStartFailureEpisodes += 1
|
||||
}
|
||||
val coldStartBudgetExhausted = terminalRetryAfterCooldown &&
|
||||
!hasEverReachedReady &&
|
||||
coldStartFailureEpisodes >= COLD_START_FAILURE_EPISODE_LIMIT
|
||||
if (coldStartBudgetExhausted) onGatewayUnreachable()
|
||||
_reconnectDisposition.value = if (
|
||||
terminalRetryAfterCooldown && !coldStartBudgetExhausted
|
||||
) {
|
||||
GatewayReconnectDisposition.Retryable
|
||||
} else {
|
||||
GatewayReconnectDisposition.Terminal
|
||||
}
|
||||
val backoffCeiling = if (hasEverReachedReady) {
|
||||
CONNECT_FAILURE_COOLDOWN_MS
|
||||
} else {
|
||||
(CONNECT_FAILURE_COOLDOWN_MS shl
|
||||
(coldStartFailureEpisodes - 1).coerceIn(0, 3))
|
||||
.coerceAtMost(MAX_CONNECT_FAILURE_COOLDOWN_MS)
|
||||
}
|
||||
connectCooldownUntil = maxOf(
|
||||
connectCooldownUntil,
|
||||
System.currentTimeMillis() + fullJitterDelayMs(
|
||||
backoffCeiling,
|
||||
reconnectJitterUnit(),
|
||||
),
|
||||
)
|
||||
_connectionState.value = GatewayConnectionState.Idle
|
||||
throw GatewayPreflightException(lastFailure)
|
||||
}
|
||||
@@ -2570,14 +2934,37 @@ class GatewayChatClient(
|
||||
_approvalModeCapability.value = GatewayApprovalModeCapability.Unknown
|
||||
_connectionState.value = GatewayConnectionState.MintingTicket
|
||||
val ticket = dashboardClient.requestWsTicket().getOrElse { e ->
|
||||
throw GatewayConnectAttemptException("ws-ticket mint failed: ${e.message}")
|
||||
val statusCode = (e as? DashboardHttpException)?.statusCode
|
||||
val authFailure = statusCode in setOf(401, 403)
|
||||
val rateLimited = statusCode == 429
|
||||
if (rateLimited) {
|
||||
connectCooldownUntil = System.currentTimeMillis() + RATE_LIMIT_COOLDOWN_MS
|
||||
}
|
||||
val transportFailure = e is java.io.IOException && e !is javax.net.ssl.SSLException
|
||||
throw GatewayConnectAttemptException(
|
||||
message = "ws-ticket mint failed: ${e.message}",
|
||||
stage = if (authFailure) {
|
||||
GatewayConnectFailureStage.TicketAuth
|
||||
} else {
|
||||
GatewayConnectFailureStage.Ticket
|
||||
},
|
||||
retryable = !authFailure && !rateLimited &&
|
||||
(statusCode in 500..599 || (statusCode == null && transportFailure)),
|
||||
retryAfterCooldown = rateLimited ||
|
||||
(!authFailure && (statusCode in 500..599 ||
|
||||
(statusCode == null && transportFailure))),
|
||||
)
|
||||
}
|
||||
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
||||
val url = dashboardClient.gatewayWebSocketUrl(
|
||||
ticket = ticket.ticket,
|
||||
profile = currentSessionProfile(),
|
||||
)
|
||||
?: throw GatewayConnectAttemptException("could not build /api/ws URL")
|
||||
?: throw GatewayConnectAttemptException(
|
||||
"could not build /api/ws URL",
|
||||
GatewayConnectFailureStage.Unsupported,
|
||||
retryable = false,
|
||||
)
|
||||
|
||||
_connectionState.value = GatewayConnectionState.Connecting
|
||||
val ready = CompletableDeferred<Unit>()
|
||||
@@ -2589,19 +2976,38 @@ class GatewayChatClient(
|
||||
webSocket = socket
|
||||
|
||||
_connectionState.value = GatewayConnectionState.AwaitingReady
|
||||
val readyOk = withTimeoutOrNull(CONNECT_TIMEOUT_MS) {
|
||||
runCatching { ready.await() }.isSuccess
|
||||
} ?: false
|
||||
if (!readyOk) {
|
||||
val readyResult: Result<Unit>? = withTimeoutOrNull(CONNECT_TIMEOUT_MS) {
|
||||
runCatching { ready.await() }
|
||||
}
|
||||
val readyFailure = readyResult?.exceptionOrNull()
|
||||
?: if (readyResult == null) {
|
||||
GatewayConnectAttemptException(
|
||||
"gateway.ready never arrived",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = true,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (readyFailure != null) {
|
||||
socket.cancel()
|
||||
webSocket = null
|
||||
throw GatewayConnectAttemptException("gateway.ready never arrived")
|
||||
throw (readyFailure as? GatewayConnectAttemptException
|
||||
?: GatewayConnectAttemptException(
|
||||
"gateway connection failed: ${readyFailure.message}",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = true,
|
||||
))
|
||||
}
|
||||
// Split the cold-connect cost so a slow ticket mint (HTTP) is told
|
||||
// apart from a slow WS upgrade + gateway.ready (socket/TLS) on device.
|
||||
val wsMs = (System.nanoTime() - connectStart) / 1_000_000 - ticketMs
|
||||
Log.i(TAG, "Gateway connected (/api/ws ready) — ticket=${ticketMs}ms ws=${wsMs}ms")
|
||||
hasEverReachedReady = true
|
||||
coldStartFailureEpisodes = 0
|
||||
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
||||
_connectionState.value = GatewayConnectionState.Ready
|
||||
onGatewayReady()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2629,6 +3035,14 @@ class GatewayChatClient(
|
||||
put("session_id", storedId)
|
||||
put("cols", DEFAULT_COLS)
|
||||
put("source", sessionSource)
|
||||
// Android already hydrates the visible transcript through the
|
||||
// profile-scoped Dashboard REST owner. Match official Desktop's
|
||||
// bounded resume contract: register the live runtime now and let
|
||||
// Gateway hydrate model history off the RPC response path instead
|
||||
// of synchronously reading and returning the same transcript.
|
||||
// Older Gateways ignore these additive parameters.
|
||||
put("defer_history", true)
|
||||
put("omit_messages", true)
|
||||
requestedProfile?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
@@ -2941,29 +3355,112 @@ class GatewayChatClient(
|
||||
// the connection as gone immediately: the server is going away.
|
||||
webSocket.close(code, null)
|
||||
if (this@GatewayChatClient.webSocket === webSocket) {
|
||||
onSocketDown("closing: $code $reason")
|
||||
val wasReady = _connectionState.value == GatewayConnectionState.Ready
|
||||
val closeFailure = if (!wasReady) preReadyCloseFailure(code, reason) else null
|
||||
if (!ready.isCompleted) {
|
||||
ready.completeExceptionally(closeFailure!!)
|
||||
}
|
||||
if (wasReady && code == 4401) onGatewaySignInRequired()
|
||||
if (wasReady && code == 4403) onGatewayUnreachable()
|
||||
onSocketDown(
|
||||
"closing: $code $reason",
|
||||
disposition = when {
|
||||
wasReady && code !in setOf(4401, 4403) ->
|
||||
GatewayReconnectDisposition.Retryable
|
||||
closeFailure?.retryAfterCooldown == true ->
|
||||
GatewayReconnectDisposition.Retryable
|
||||
else -> GatewayReconnectDisposition.Terminal
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
if (this@GatewayChatClient.webSocket === webSocket) {
|
||||
onSocketDown("closed: $code $reason")
|
||||
val wasReady = _connectionState.value == GatewayConnectionState.Ready
|
||||
val closeFailure = if (!wasReady) preReadyCloseFailure(code, reason) else null
|
||||
if (!ready.isCompleted) {
|
||||
ready.completeExceptionally(closeFailure!!)
|
||||
}
|
||||
if (wasReady && code == 4401) onGatewaySignInRequired()
|
||||
if (wasReady && code == 4403) onGatewayUnreachable()
|
||||
onSocketDown(
|
||||
"closed: $code $reason",
|
||||
disposition = when {
|
||||
wasReady && code !in setOf(4401, 4403) ->
|
||||
GatewayReconnectDisposition.Retryable
|
||||
closeFailure?.retryAfterCooldown == true ->
|
||||
GatewayReconnectDisposition.Retryable
|
||||
else -> GatewayReconnectDisposition.Terminal
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
if (this@GatewayChatClient.webSocket !== webSocket) return
|
||||
when (response?.code) {
|
||||
404, 403 -> {
|
||||
val connectFailure = when (response?.code) {
|
||||
404 -> {
|
||||
// No /api/ws on this build (or embedded chat disabled) —
|
||||
// sticky downgrade so auto-resolution stops picking gateway.
|
||||
Log.w(TAG, "Gateway WS upgrade rejected (${response.code}) — marking unsupported")
|
||||
onGatewayUnsupported()
|
||||
GatewayConnectAttemptException(
|
||||
"gateway websocket is unsupported",
|
||||
GatewayConnectFailureStage.Unsupported,
|
||||
retryable = false,
|
||||
)
|
||||
}
|
||||
429 -> connectCooldownUntil = System.currentTimeMillis() + RATE_LIMIT_COOLDOWN_MS
|
||||
401, 403 -> GatewayConnectAttemptException(
|
||||
"gateway websocket authentication was rejected",
|
||||
GatewayConnectFailureStage.UpgradeAuth,
|
||||
retryable = false,
|
||||
)
|
||||
429 -> {
|
||||
connectCooldownUntil = System.currentTimeMillis() + RATE_LIMIT_COOLDOWN_MS
|
||||
GatewayConnectAttemptException(
|
||||
"gateway websocket rate limited",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = false,
|
||||
retryAfterCooldown = true,
|
||||
)
|
||||
}
|
||||
else -> GatewayConnectAttemptException(
|
||||
"gateway websocket upgrade failed: ${t.message}",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = true,
|
||||
)
|
||||
}
|
||||
if (!ready.isCompleted) ready.completeExceptionally(t)
|
||||
onSocketDown("failure: ${t.message}")
|
||||
if (!ready.isCompleted) ready.completeExceptionally(connectFailure)
|
||||
onSocketDown(
|
||||
"failure: ${t.message}",
|
||||
disposition = if (connectFailure.retryAfterCooldown) {
|
||||
GatewayReconnectDisposition.Retryable
|
||||
} else {
|
||||
GatewayReconnectDisposition.Terminal
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun preReadyCloseFailure(code: Int, reason: String): GatewayConnectAttemptException {
|
||||
val safeReason = reason.take(160).ifBlank { "closed before gateway.ready" }
|
||||
return when (code) {
|
||||
4401 -> GatewayConnectAttemptException(
|
||||
"gateway authentication was rejected ($safeReason)",
|
||||
GatewayConnectFailureStage.UpgradeAuth,
|
||||
retryable = false,
|
||||
)
|
||||
4403 -> GatewayConnectAttemptException(
|
||||
"gateway origin or access guard rejected the connection ($safeReason)",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = false,
|
||||
)
|
||||
else -> GatewayConnectAttemptException(
|
||||
"gateway closed before ready (code=$code, $safeReason)",
|
||||
GatewayConnectFailureStage.Upgrade,
|
||||
retryable = code in setOf(1001, 1011, 1012, 1013),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3013,6 +3510,11 @@ class GatewayChatClient(
|
||||
return
|
||||
}
|
||||
|
||||
if (type == "sessions.changed") {
|
||||
callbackDispatcher { sessionDirectoryInvalidationListener?.invoke() }
|
||||
return
|
||||
}
|
||||
|
||||
// Upstream emits session.reclaimed process-wide, so it is identified
|
||||
// by payload rather than params.session_id. Retire only an exact live
|
||||
// runtime we own; preserve the durable id so the next send resumes it.
|
||||
@@ -3022,6 +3524,9 @@ class GatewayChatClient(
|
||||
val reason = payload?.stringField("reason")
|
||||
val supportedReason = reason in setOf("idle_timeout", "lru_evict", "ws_orphan_reap")
|
||||
if (!reclaimedLiveId.isNullOrBlank() && supportedReason) {
|
||||
childWatches.remove(reclaimedLiveId)?.let { registration ->
|
||||
notifyChildWatchFailure(registration, "Gateway reclaimed the child watch")
|
||||
}
|
||||
val background = backgroundTurns.remove(reclaimedLiveId)
|
||||
if (background != null) {
|
||||
callbackDispatcher {
|
||||
@@ -3073,6 +3578,23 @@ class GatewayChatClient(
|
||||
return
|
||||
}
|
||||
|
||||
// A lazy child watcher is a second session on this shared socket. Route
|
||||
// it before the main-session recovery/foreign-session gates and require
|
||||
// the exact live id returned by its own session.resume acknowledgement.
|
||||
val childWatch = eventSessionId?.let(childWatches::get)
|
||||
if (childWatch != null) {
|
||||
if (childWatches[eventSessionId] === childWatch) {
|
||||
childWatch.mapper.onEvent(type, payload)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val capturedForPendingChildWatch = !eventSessionId.isNullOrBlank() &&
|
||||
eventSessionId != liveSessionId &&
|
||||
!backgroundTurns.containsKey(eventSessionId) &&
|
||||
capturePendingChildWatchEvent(ChildWatchEvent(eventSessionId, type, payload))
|
||||
if (capturedForPendingChildWatch) return
|
||||
|
||||
// A cold session.resume may schedule auto-continue before its RPC
|
||||
// response reaches Android. The recovery buffer is an ownership gate,
|
||||
// not an observational copy: an event is either claimed here for
|
||||
@@ -3296,7 +3818,10 @@ class GatewayChatClient(
|
||||
callbackDispatcher { processEventListener?.invoke(event) }
|
||||
}
|
||||
|
||||
private fun onSocketDown(reason: String) {
|
||||
private fun onSocketDown(
|
||||
reason: String,
|
||||
disposition: GatewayReconnectDisposition = GatewayReconnectDisposition.Retryable,
|
||||
) {
|
||||
Log.i(TAG, "Gateway socket down ($reason)")
|
||||
// Capture the in-flight session id BEFORE clearing it — the mid-turn
|
||||
// rejoin restores it so the running turn's tail (still tagged with this
|
||||
@@ -3310,11 +3835,13 @@ class GatewayChatClient(
|
||||
_processCapability.value = GatewayProcessCapability.Unknown
|
||||
_activeSessionCapability.value = GatewayActiveSessionCapability.Unknown
|
||||
_approvalModeCapability.value = GatewayApprovalModeCapability.Unknown
|
||||
_reconnectDisposition.value = disposition
|
||||
_connectionState.value = GatewayConnectionState.Idle
|
||||
pendingRpcs.values.forEach {
|
||||
it.completeExceptionally(GatewayRpcException("gateway connection lost"))
|
||||
}
|
||||
pendingRpcs.clear()
|
||||
failChildWatches("Child watch disconnected from the gateway")
|
||||
val turn = activeTurn
|
||||
if (turn == null) {
|
||||
if (backgroundTurns.isNotEmpty() && !backgroundRejoinInProgress) {
|
||||
@@ -3496,7 +4023,9 @@ class GatewayChatClient(
|
||||
_processCapability.value = GatewayProcessCapability.Unknown
|
||||
_activeSessionCapability.value = GatewayActiveSessionCapability.Unknown
|
||||
_approvalModeCapability.value = GatewayApprovalModeCapability.Unknown
|
||||
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
||||
_connectionState.value = GatewayConnectionState.Idle
|
||||
failChildWatches("Child watch closed with the gateway socket")
|
||||
}
|
||||
|
||||
private fun scheduleBackgroundClose() {
|
||||
@@ -3506,7 +4035,7 @@ class GatewayChatClient(
|
||||
backgroundCloseJob?.cancel()
|
||||
backgroundCloseJob = scope.launch {
|
||||
delay(BACKGROUND_CLOSE_GRACE_MS)
|
||||
if (activeTurn == null && backgroundTurns.isEmpty() &&
|
||||
if (activeTurn == null && backgroundTurns.isEmpty() && childWatches.isEmpty() &&
|
||||
!AppForegroundTracker.isForeground.value
|
||||
) {
|
||||
closeSocket("app backgrounded")
|
||||
@@ -3514,6 +4043,28 @@ class GatewayChatClient(
|
||||
}
|
||||
}
|
||||
|
||||
private fun failChildWatches(message: String) {
|
||||
if (childWatches.isEmpty()) return
|
||||
val registrations = childWatches.values.toSet()
|
||||
childWatches.clear()
|
||||
registrations.forEach { notifyChildWatchFailure(it, message) }
|
||||
}
|
||||
|
||||
private fun notifyChildWatchFailure(
|
||||
registration: ChildWatchRegistration,
|
||||
message: String,
|
||||
) {
|
||||
callbackDispatcher { registration.callbacks.onResumeFailure(message) }
|
||||
}
|
||||
|
||||
private fun capturePendingChildWatchEvent(event: ChildWatchEvent): Boolean {
|
||||
var captured = false
|
||||
pendingChildWatchOpens.values.forEach { pending ->
|
||||
if (pending.capture(event)) captured = true
|
||||
}
|
||||
return captured
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// JSON-RPC
|
||||
// ------------------------------------------------------------------
|
||||
@@ -4062,44 +4613,55 @@ class GatewayChatClient(
|
||||
}
|
||||
|
||||
/** Wrap callbacks so every invocation lands on the callback dispatcher (main thread). */
|
||||
private fun dispatchOn(callbacks: GatewayTurnCallbacks) = GatewayTurnCallbacks(
|
||||
onSessionId = { v -> callbackDispatcher { callbacks.onSessionId(v) } },
|
||||
onStart = { callbackDispatcher { callbacks.onStart() } },
|
||||
onTextDelta = { v -> callbackDispatcher { callbacks.onTextDelta(v) } },
|
||||
private fun dispatchOn(
|
||||
callbacks: GatewayTurnCallbacks,
|
||||
stillCurrent: () -> Boolean = { true },
|
||||
) = GatewayTurnCallbacks(
|
||||
onSessionId = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onSessionId(v) } },
|
||||
onStart = { dispatchIfCurrent(stillCurrent) { callbacks.onStart() } },
|
||||
onTextDelta = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onTextDelta(v) } },
|
||||
onInterimMessage = { text, alreadyStreamed ->
|
||||
callbackDispatcher { callbacks.onInterimMessage(text, alreadyStreamed) }
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onInterimMessage(text, alreadyStreamed) }
|
||||
},
|
||||
onInterimReconciled = { text ->
|
||||
callbackDispatcher { callbacks.onInterimReconciled(text) }
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onInterimReconciled(text) }
|
||||
},
|
||||
onThinkingDelta = { v -> callbackDispatcher { callbacks.onThinkingDelta(v) } },
|
||||
onThinkingDelta = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onThinkingDelta(v) } },
|
||||
onToolCallStart = { id, name, args ->
|
||||
callbackDispatcher { callbacks.onToolCallStart(id, name, args) }
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onToolCallStart(id, name, args) }
|
||||
},
|
||||
onToolCallDone = { a, b -> callbackDispatcher { callbacks.onToolCallDone(a, b) } },
|
||||
onToolCallFailed = { a, b -> callbackDispatcher { callbacks.onToolCallFailed(a, b) } },
|
||||
onToolOutputRisk = { v -> callbackDispatcher { callbacks.onToolOutputRisk(v) } },
|
||||
onTurnComplete = { callbackDispatcher { callbacks.onTurnComplete() } },
|
||||
onReconcileRequired = { callbackDispatcher { callbacks.onReconcileRequired() } },
|
||||
onComplete = { callbackDispatcher { callbacks.onComplete() } },
|
||||
onUsage = { v -> callbackDispatcher { callbacks.onUsage(v) } },
|
||||
onError = { v -> callbackDispatcher { callbacks.onError(v) } },
|
||||
onToolGenerating = { v -> callbackDispatcher { callbacks.onToolGenerating(v) } },
|
||||
onSubagentEvent = { v -> callbackDispatcher { callbacks.onSubagentEvent(v) } },
|
||||
onMoaReference = { v -> callbackDispatcher { callbacks.onMoaReference(v) } },
|
||||
onInteractionRequest = { v -> callbackDispatcher { callbacks.onInteractionRequest(v) } },
|
||||
onInteractionExpired = { v -> callbackDispatcher { callbacks.onInteractionExpired(v) } },
|
||||
onResumeFailure = { v -> callbackDispatcher { callbacks.onResumeFailure(v) } },
|
||||
onFailure = { v -> callbackDispatcher { callbacks.onFailure(v) } },
|
||||
onToolCallDone = { a, b -> dispatchIfCurrent(stillCurrent) { callbacks.onToolCallDone(a, b) } },
|
||||
onToolCallFailed = { a, b -> dispatchIfCurrent(stillCurrent) { callbacks.onToolCallFailed(a, b) } },
|
||||
onToolOutputRisk = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onToolOutputRisk(v) } },
|
||||
onTurnComplete = { dispatchIfCurrent(stillCurrent) { callbacks.onTurnComplete() } },
|
||||
onReconcileRequired = { dispatchIfCurrent(stillCurrent) { callbacks.onReconcileRequired() } },
|
||||
onComplete = { dispatchIfCurrent(stillCurrent) { callbacks.onComplete() } },
|
||||
onUsage = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onUsage(v) } },
|
||||
onError = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onError(v) } },
|
||||
onToolGenerating = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onToolGenerating(v) } },
|
||||
onSubagentEvent = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onSubagentEvent(v) } },
|
||||
onMoaReference = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onMoaReference(v) } },
|
||||
onInteractionRequest = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onInteractionRequest(v) } },
|
||||
onInteractionExpired = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onInteractionExpired(v) } },
|
||||
onResumeFailure = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onResumeFailure(v) } },
|
||||
onFailure = { v -> dispatchIfCurrent(stillCurrent) { callbacks.onFailure(v) } },
|
||||
// MUST be wrapped like every other member: GatewayTurnCallbacks gives
|
||||
// onStatusUpdate a default no-op, so omitting it here silently swallows
|
||||
// EVERY gateway status line — the ❌ terminal-error lifecycle update
|
||||
// included. Without it markError never fires, the turn isn't badged
|
||||
// "Error", and onComplete's history reload wipes the error bubble (the
|
||||
// "reply appears then vanishes" bug).
|
||||
onStatusUpdate = { kind, text -> callbackDispatcher { callbacks.onStatusUpdate(kind, text) } },
|
||||
onStatusClear = { kind -> callbackDispatcher { callbacks.onStatusClear(kind) } },
|
||||
onStatusUpdate = { kind, text ->
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
||||
},
|
||||
onStatusClear = { kind -> dispatchIfCurrent(stillCurrent) { callbacks.onStatusClear(kind) } },
|
||||
)
|
||||
|
||||
private fun dispatchIfCurrent(stillCurrent: () -> Boolean, callback: () -> Unit) {
|
||||
callbackDispatcher {
|
||||
if (stillCurrent()) callback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseGatewayPersonalityOptions(result: JsonObject): List<String> =
|
||||
@@ -4151,8 +4713,21 @@ internal class GatewayPreflightException(message: String) : Exception(message)
|
||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||
internal class GatewayAttachmentPreflightException(message: String) : Exception(message)
|
||||
|
||||
/** One connect attempt failed; [GatewayChatClient] may retry with a fresh ticket. */
|
||||
internal class GatewayConnectAttemptException(message: String) : Exception(message)
|
||||
/** One connect attempt failed; only a transient WebSocket upgrade may retry immediately. */
|
||||
internal class GatewayConnectAttemptException(
|
||||
message: String,
|
||||
val stage: GatewayConnectFailureStage,
|
||||
val retryable: Boolean,
|
||||
val retryAfterCooldown: Boolean = retryable,
|
||||
) : Exception(message)
|
||||
|
||||
internal enum class GatewayConnectFailureStage(val logName: String) {
|
||||
TicketAuth("ticket_auth"),
|
||||
Ticket("ticket"),
|
||||
UpgradeAuth("upgrade_auth"),
|
||||
Upgrade("upgrade"),
|
||||
Unsupported("unsupported"),
|
||||
}
|
||||
|
||||
/** Server intentionally refused a durable resume; never create/fallback into a context-free turn. */
|
||||
internal class GatewayAuthoritativeResumeException(message: String) : Exception(message)
|
||||
|
||||
@@ -281,11 +281,12 @@ class GatewayEventMapper(
|
||||
callbacks.onError(payload.string("message") ?: "Gateway error")
|
||||
}
|
||||
|
||||
"subagent.start", "subagent.thinking", "subagent.tool",
|
||||
"subagent.spawn_requested", "subagent.start", "subagent.thinking", "subagent.tool",
|
||||
"subagent.progress", "subagent.complete",
|
||||
-> {
|
||||
clearActivityStatuses()
|
||||
val phase = when (type) {
|
||||
"subagent.spawn_requested" -> GatewaySubagentEvent.Phase.SPAWN_REQUESTED
|
||||
"subagent.start" -> GatewaySubagentEvent.Phase.START
|
||||
"subagent.thinking" -> GatewaySubagentEvent.Phase.THINKING
|
||||
"subagent.tool" -> GatewaySubagentEvent.Phase.TOOL
|
||||
@@ -306,6 +307,10 @@ class GatewayEventMapper(
|
||||
preview = payload.string("tool_preview") ?: payload.string("text"),
|
||||
durationSeconds = payload.double("duration_seconds"),
|
||||
subagentId = payload.string("subagent_id"),
|
||||
childSessionId = payload.string("child_session_id"),
|
||||
parentId = payload.string("parent_id"),
|
||||
depth = payload.int("depth"),
|
||||
model = payload.string("model"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
@@ -28,7 +29,7 @@ enum class GatewayAvailability {
|
||||
/** No probe has completed yet (startup, connection switch). */
|
||||
Unknown,
|
||||
|
||||
/** Dashboard reachable and authenticated (or auth not required). */
|
||||
/** The `/api/ws` socket completed `gateway.ready` for the active route. */
|
||||
Ready,
|
||||
|
||||
/** Dashboard reachable and gated, but no signed-in session — Manage sign-in unlocks it. */
|
||||
@@ -55,6 +56,13 @@ enum class GatewayConnectionState {
|
||||
Ready,
|
||||
}
|
||||
|
||||
/** Whether an idle Gateway may be retried automatically by a visible Chat surface. */
|
||||
enum class GatewayReconnectDisposition {
|
||||
None,
|
||||
Retryable,
|
||||
Terminal,
|
||||
}
|
||||
|
||||
/** Profile-persisted approval policy introduced by upstream gateway contract v3. */
|
||||
enum class GatewayApprovalMode(val wireValue: String) {
|
||||
Manual("manual"),
|
||||
@@ -257,7 +265,8 @@ data class GatewayToolOutputRisk(
|
||||
|
||||
/**
|
||||
* One `subagent.*` lifecycle event, emitted on the PARENT session. Lifecycle
|
||||
* per task: START → (THINKING | TOOL | PROGRESS)* → COMPLETE. Field
|
||||
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
||||
* COMPLETE. Field
|
||||
* availability varies by phase — [toolName]/[preview] ride TOOL,
|
||||
* [status]/[summary]/[durationSeconds] ride COMPLETE — and older emitters
|
||||
* omit everything beyond the three defaults-bearing fields.
|
||||
@@ -273,10 +282,36 @@ data class GatewaySubagentEvent(
|
||||
val preview: String? = null,
|
||||
val durationSeconds: Double? = null,
|
||||
val subagentId: String? = null,
|
||||
/** Durable child session id accepted by `session.resume {lazy:true}`. */
|
||||
val childSessionId: String? = null,
|
||||
/** Owning subagent id for nested delegation; null for first-level children. */
|
||||
val parentId: String? = null,
|
||||
/** Zero-based depth used by the upstream spawn-tree renderer. */
|
||||
val depth: Int? = null,
|
||||
/** Effective child model, when the emitter exposes it. */
|
||||
val model: String? = null,
|
||||
) {
|
||||
enum class Phase { START, THINKING, TOOL, PROGRESS, COMPLETE }
|
||||
enum class Phase { SPAWN_REQUESTED, START, THINKING, TOOL, PROGRESS, COMPLETE }
|
||||
}
|
||||
|
||||
/**
|
||||
* One profile-pinned, read-only child-session watch opened through the vanilla
|
||||
* upstream Gateway. [storedSessionId] is the durable child id from
|
||||
* `subagent.*`; [liveSessionId] is the short runtime id that tags subsequent
|
||||
* mirror events on this socket. The bounded [messages] snapshot is child-only.
|
||||
*/
|
||||
data class GatewayChildWatch(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val profile: String?,
|
||||
val generation: Long,
|
||||
val messages: List<MessageItem>,
|
||||
/** True when Android retained only a bounded recent tail of the response. */
|
||||
val historyTruncated: Boolean,
|
||||
val running: Boolean,
|
||||
val status: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* One session-owned background process returned by the upstream gateway's
|
||||
* `process.list` RPC. The registry calls its process id `session_id`; Android
|
||||
|
||||
+215
-45
@@ -1,5 +1,7 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.data.normalizeCredentialFreeAuthenticatedDashboardOrigin
|
||||
|
||||
import android.content.Context
|
||||
import com.hermesandroid.relay.auth.SessionTokenStore
|
||||
import com.hermesandroid.relay.auth.SecureStoreCache
|
||||
@@ -101,6 +103,7 @@ class NativeDashboardAuthorization internal constructor(
|
||||
internal val verifier: String,
|
||||
internal val state: String,
|
||||
internal val generation: Long,
|
||||
internal val usesAlternateOrigin: Boolean,
|
||||
)
|
||||
|
||||
class NativeDashboardAuthClient(
|
||||
@@ -144,14 +147,9 @@ class NativeDashboardAuthClient(
|
||||
.addQueryParameter("code_challenge_method", "S256")
|
||||
.addQueryParameter("redirect_uri", redirectUri)
|
||||
.addQueryParameter("state", state)
|
||||
// Match the official Desktop client for Nous-hosted gateways: the
|
||||
// gateway selects its single native-eligible provider. The provider
|
||||
// name advertised to UI clients is presentation/configuration data,
|
||||
// not a stable native-broker identifier. Other providers retain the
|
||||
// explicit selector for direct client use and tests.
|
||||
.apply {
|
||||
provider
|
||||
?.takeIf { it.isNotBlank() && !it.equals("nous", ignoreCase = true) }
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { addQueryParameter("provider", it) }
|
||||
}
|
||||
.build()
|
||||
@@ -159,29 +157,29 @@ class NativeDashboardAuthClient(
|
||||
val generation = NativeTokenRefreshCoordinator.beginAuthorization(
|
||||
tokenStore.coordinationKey,
|
||||
)
|
||||
return NativeDashboardAuthorization(url, verifier, state, generation)
|
||||
return NativeDashboardAuthorization(
|
||||
authorizationUrl = url,
|
||||
verifier = verifier,
|
||||
state = state,
|
||||
generation = generation,
|
||||
usesAlternateOrigin = !sameDashboardBase(authorizationBaseUrl, baseUrl),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A private-route dashboard may be configured with a canonical HTTPS
|
||||
* callback origin for its provider. Starting the browser on the private
|
||||
* origin would scope Hermes' temporary PKCE cookie to the wrong host, so
|
||||
* discover the provider's declared callback and start native auth there.
|
||||
* Token exchange still uses [baseUrl], keeping the resulting bearer bound
|
||||
* to the active connection route.
|
||||
* Discover the callback-owning Dashboard origin for every interactive
|
||||
* redirect provider. Provider names do not imply topology; upstream may
|
||||
* advertise a canonical origin that differs from a LAN/Tailscale entry.
|
||||
* Token exchange still uses [baseUrl], keeping the bearer scoped to this
|
||||
* connection while the shared gateway process consumes its one-time code.
|
||||
*/
|
||||
private fun resolveAuthorizationBaseUrl(provider: String?): String {
|
||||
val configured = baseUrl.toHttpUrlOrNull() ?: return baseUrl
|
||||
if (
|
||||
!provider.equals("nous", ignoreCase = true) ||
|
||||
configured.scheme != "http" ||
|
||||
!isPrivateNetworkLiteral(configured.host)
|
||||
) {
|
||||
return baseUrl
|
||||
}
|
||||
val selectedProvider = provider?.takeIf { it.isNotBlank() } ?: return baseUrl
|
||||
if (isLoopbackDashboardHost(configured.host)) return baseUrl
|
||||
val loginUrl = configured.newBuilder()
|
||||
.addPathSegments("auth/login")
|
||||
.addQueryParameter("provider", provider)
|
||||
.addQueryParameter("provider", selectedProvider)
|
||||
.addQueryParameter("next", "/")
|
||||
.build()
|
||||
val discoveryClient = client.newBuilder()
|
||||
@@ -193,14 +191,14 @@ class NativeDashboardAuthClient(
|
||||
).execute().use { response ->
|
||||
if (response.code !in 300..399) null else response.header("Location")
|
||||
}
|
||||
return canonicalDashboardBaseFromNousRedirect(location)
|
||||
?: throw IOException("Dashboard did not advertise a secure Nous callback origin")
|
||||
return canonicalDashboardBaseFromProviderRedirect(baseUrl, location)
|
||||
}
|
||||
|
||||
fun exchangeCallback(
|
||||
authorization: NativeDashboardAuthorization,
|
||||
callbackTarget: String,
|
||||
commitAllowed: () -> Boolean = { true },
|
||||
onValidated: () -> Unit = {},
|
||||
): NativeDashboardTokens {
|
||||
val callback = callbackTarget.toHttpUrlOrNull()
|
||||
?: "http://127.0.0.1$callbackTarget".toHttpUrlOrNull()
|
||||
@@ -224,6 +222,7 @@ class NativeDashboardAuthClient(
|
||||
?: throw NativeDashboardCallbackException(
|
||||
"Native sign-in callback did not include an authorization code",
|
||||
)
|
||||
runCatching(onValidated)
|
||||
val payload = NativeTokenExchange(code = code, codeVerifier = authorization.verifier)
|
||||
return postTokens(
|
||||
path = "/auth/native/token",
|
||||
@@ -322,6 +321,10 @@ class NativeDashboardAuthClient(
|
||||
throw NativeDashboardInactiveAuthorizationException()
|
||||
}
|
||||
tokenStore.save(tokens)
|
||||
NativeTokenRefreshCoordinator.markBootstrapApproved(
|
||||
tokenStore.coordinationKey,
|
||||
tokens.accessToken,
|
||||
)
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
@@ -412,6 +415,63 @@ private fun isPrivateNetworkLiteral(host: String): Boolean {
|
||||
(first == 100 && second in 64..127)
|
||||
}
|
||||
|
||||
private fun isLoopbackDashboardHost(host: String): Boolean =
|
||||
host.equals("localhost", ignoreCase = true) ||
|
||||
host == "127.0.0.1" ||
|
||||
host == "::1"
|
||||
|
||||
/**
|
||||
* Extract a callback-owning Dashboard base from an auth-provider redirect.
|
||||
* Different HTTPS origins are accepted after an HTTPS provider hop. HTTP is
|
||||
* retained for upstream-supported local/overlay callbacks only when both the
|
||||
* selected and callback hosts are private literals/loopback and no HTTPS-to-
|
||||
* HTTP downgrade occurs. Arbitrary public cleartext origins are rejected.
|
||||
*/
|
||||
internal fun canonicalDashboardBaseFromProviderRedirect(
|
||||
configuredBase: String,
|
||||
location: String?,
|
||||
): String {
|
||||
val configured = configuredBase.trim().trimEnd('/').toHttpUrlOrNull()
|
||||
?: return configuredBase
|
||||
val fallback = configured.toString().trimEnd('/')
|
||||
val providerUrl = location?.toHttpUrlOrNull() ?: return fallback
|
||||
val callback = providerUrl.queryParameter("redirect_uri")
|
||||
?.toHttpUrlOrNull()
|
||||
?: return fallback
|
||||
if (
|
||||
providerUrl.username.isNotEmpty() || providerUrl.password.isNotEmpty() ||
|
||||
callback.username.isNotEmpty() || callback.password.isNotEmpty() ||
|
||||
callback.query != null || callback.fragment != null
|
||||
) {
|
||||
return fallback
|
||||
}
|
||||
val callbackSuffix = "/auth/callback"
|
||||
if (!callback.encodedPath.endsWith(callbackSuffix)) return fallback
|
||||
val callbackBase = callback.newBuilder()
|
||||
.encodedPath(callback.encodedPath.removeSuffix(callbackSuffix).ifBlank { "/" })
|
||||
.query(null)
|
||||
.fragment(null)
|
||||
.build()
|
||||
if (
|
||||
configured.scheme == callbackBase.scheme &&
|
||||
configured.host.equals(callbackBase.host, ignoreCase = true) &&
|
||||
configured.port == callbackBase.port &&
|
||||
configured.encodedPath.trimEnd('/') == callbackBase.encodedPath.trimEnd('/')
|
||||
) {
|
||||
return fallback
|
||||
}
|
||||
if (providerUrl.scheme != "https") return fallback
|
||||
val trustedDifferentOrigin = callbackBase.scheme == "https" || (
|
||||
configured.scheme == "http" &&
|
||||
callbackBase.scheme == "http" &&
|
||||
normalizeCredentialFreeAuthenticatedDashboardOrigin(fallback) != null &&
|
||||
normalizeCredentialFreeAuthenticatedDashboardOrigin(
|
||||
callbackBase.toString().trimEnd('/'),
|
||||
) != null
|
||||
)
|
||||
return if (trustedDifferentOrigin) callbackBase.toString().trimEnd('/') else fallback
|
||||
}
|
||||
|
||||
internal fun canonicalDashboardBaseFromNousRedirect(location: String?): String? {
|
||||
val providerUrl = location?.toHttpUrlOrNull() ?: return null
|
||||
if (
|
||||
@@ -420,28 +480,20 @@ internal fun canonicalDashboardBaseFromNousRedirect(location: String?): String?
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val callback = providerUrl.queryParameter("redirect_uri")
|
||||
?.toHttpUrlOrNull()
|
||||
?: return null
|
||||
if (callback.scheme != "https") return null
|
||||
val callbackSuffix = "/auth/callback"
|
||||
if (!callback.encodedPath.endsWith(callbackSuffix)) return null
|
||||
val basePath = callback.encodedPath
|
||||
.removeSuffix(callbackSuffix)
|
||||
.ifBlank { "/" }
|
||||
return callback.newBuilder()
|
||||
.encodedPath(basePath)
|
||||
.query(null)
|
||||
.fragment(null)
|
||||
.build()
|
||||
.toString()
|
||||
.trimEnd('/')
|
||||
val resolved = canonicalDashboardBaseFromProviderRedirect(
|
||||
configuredBase = "http://192.168.0.1:9119",
|
||||
location = location,
|
||||
)
|
||||
return resolved.takeUnless { it == "http://192.168.0.1:9119" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the native bearer to dashboard REST calls and rotates it before expiry
|
||||
* or after one 401. Refresh requests use a separate bare client, so neither a
|
||||
* stale bearer nor the authenticator can recurse into token rotation.
|
||||
* or after one 401. Ticket mint also gets one bounded refresh on 503 because a
|
||||
* multi-provider Dashboard can report an expired token as provider-unreachable
|
||||
* before the owning provider gets to reject it. Refresh requests use a separate
|
||||
* bare client, so neither a stale bearer nor the authenticator can recurse into
|
||||
* token rotation.
|
||||
*/
|
||||
class DashboardBearerAuth(
|
||||
baseUrl: String,
|
||||
@@ -449,20 +501,90 @@ class DashboardBearerAuth(
|
||||
private val clockSeconds: () -> Long = { System.currentTimeMillis() / 1000L },
|
||||
) : Interceptor, Authenticator {
|
||||
private val authClient = NativeDashboardAuthClient(baseUrl, tokenStore)
|
||||
@Volatile
|
||||
private var cookieAuthAvailable: ((okhttp3.HttpUrl) -> Boolean)? = null
|
||||
@Volatile
|
||||
private var preferNativeBearerAfterCookieProviderFailure = false
|
||||
|
||||
internal fun preferCookiesWhen(predicate: (okhttp3.HttpUrl) -> Boolean) {
|
||||
cookieAuthAvailable = predicate
|
||||
}
|
||||
|
||||
private fun shouldPreferCookie(url: okhttp3.HttpUrl): Boolean =
|
||||
!preferNativeBearerAfterCookieProviderFailure &&
|
||||
runCatching { cookieAuthAvailable?.invoke(url) == true }.getOrDefault(false)
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
if (shouldPreferCookie(chain.request().url)) {
|
||||
val cookieResponse = chain.proceed(chain.request())
|
||||
if (!cookieResponse.isAuthProviderUnavailable()) return cookieResponse
|
||||
val tokens = usableTokens(forceRefresh = false, failedAccessToken = null)
|
||||
?: return cookieResponse
|
||||
val accessToken = normalizeCredentialForHeader(
|
||||
tokens.accessToken,
|
||||
"Dashboard credential",
|
||||
)
|
||||
cookieResponse.close()
|
||||
val bearerResponse = chain.proceed(
|
||||
chain.request().newBuilder()
|
||||
.bearerAuthorization(accessToken, "Dashboard credential")
|
||||
.build(),
|
||||
)
|
||||
if (bearerResponse.isSuccessful) {
|
||||
// Preserve the cookie on disk: upstream's 503 intentionally
|
||||
// avoids logging browsers out during an IdP outage. This exact
|
||||
// Dashboard client merely stops presenting the stranded cookie
|
||||
// first after its connection-scoped bearer proves valid.
|
||||
preferNativeBearerAfterCookieProviderFailure = true
|
||||
}
|
||||
return bearerResponse
|
||||
}
|
||||
val tokens = usableTokens(forceRefresh = false, failedAccessToken = null)
|
||||
val request = tokens?.let {
|
||||
chain.request().newBuilder()
|
||||
.bearerAuthorization(it.accessToken, "Dashboard credential")
|
||||
.build()
|
||||
} ?: chain.request()
|
||||
return chain.proceed(request)
|
||||
val response = chain.proceed(request)
|
||||
if (
|
||||
response.code != 503 ||
|
||||
!request.url.encodedPath.endsWith("/api/auth/ws-ticket")
|
||||
) {
|
||||
return response
|
||||
}
|
||||
val previous = request.header("Authorization") ?: return response
|
||||
val failedAccessToken = previous.removePrefix("Bearer ").takeIf { it != previous }
|
||||
?: return response
|
||||
val refreshed = usableTokens(
|
||||
forceRefresh = true,
|
||||
failedAccessToken = failedAccessToken,
|
||||
) ?: return response
|
||||
val accessToken = normalizeCredentialForHeader(
|
||||
refreshed.accessToken,
|
||||
"Dashboard credential",
|
||||
)
|
||||
if (accessToken == failedAccessToken) return response
|
||||
response.close()
|
||||
return chain.proceed(
|
||||
request.newBuilder()
|
||||
.bearerAuthorization(accessToken, "Dashboard credential")
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun authenticate(route: Route?, response: Response): Request? {
|
||||
if (responseCount(response) >= 2) return null
|
||||
val previous = response.request.header("Authorization") ?: return null
|
||||
val previous = response.request.header("Authorization")
|
||||
if (previous == null) {
|
||||
if (!shouldPreferCookie(response.request.url)) return null
|
||||
val tokens = usableTokens(
|
||||
forceRefresh = false,
|
||||
failedAccessToken = null,
|
||||
) ?: return null
|
||||
return response.request.newBuilder()
|
||||
.bearerAuthorization(tokens.accessToken, "Dashboard credential")
|
||||
.build()
|
||||
}
|
||||
val failedAccessToken = previous.removePrefix("Bearer ").takeIf { it != previous }
|
||||
val tokens = usableTokens(
|
||||
forceRefresh = true,
|
||||
@@ -487,11 +609,39 @@ class DashboardBearerAuth(
|
||||
if (failedAccessToken != null && current.accessToken != failedAccessToken) {
|
||||
return@synchronized current
|
||||
}
|
||||
val needsNousBootstrap = current.provider.equals("nous", ignoreCase = true) &&
|
||||
current.refreshToken.isNotBlank() &&
|
||||
!NativeTokenRefreshCoordinator.isBootstrapApproved(
|
||||
tokenStore.coordinationKey,
|
||||
current.accessToken,
|
||||
)
|
||||
if (needsNousBootstrap &&
|
||||
NativeTokenRefreshCoordinator.isBootstrapRejected(
|
||||
tokenStore.coordinationKey,
|
||||
current.accessToken,
|
||||
)
|
||||
) {
|
||||
return@synchronized null
|
||||
}
|
||||
val nearExpiry = current.expiresAt <= 0L || clockSeconds() >= current.expiresAt - 60L
|
||||
if (!forceRefresh && !nearExpiry) return@synchronized current
|
||||
runCatching { authClient.refresh(current) }.getOrNull()
|
||||
if (!forceRefresh && !nearExpiry && !needsNousBootstrap) return@synchronized current
|
||||
val refreshed = runCatching { authClient.refresh(current) }.getOrNull()
|
||||
if (refreshed == null && needsNousBootstrap) {
|
||||
NativeTokenRefreshCoordinator.markBootstrapRejected(
|
||||
tokenStore.coordinationKey,
|
||||
current.accessToken,
|
||||
)
|
||||
}
|
||||
refreshed
|
||||
}
|
||||
|
||||
private fun Response.isAuthProviderUnavailable(): Boolean {
|
||||
if (code != 503) return false
|
||||
val detail = runCatching { peekBody(1_024L).string() }.getOrDefault("")
|
||||
return detail.contains("Auth provider", ignoreCase = true) &&
|
||||
detail.contains("unreachable", ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun responseCount(response: Response): Int {
|
||||
var count = 1
|
||||
var prior = response.priorResponse
|
||||
@@ -564,6 +714,8 @@ private inline fun <reified T : Throwable> Throwable.firstCauseOfType(): T? {
|
||||
private object NativeTokenRefreshCoordinator {
|
||||
private val locks = ConcurrentHashMap<String, Any>()
|
||||
private val generations = ConcurrentHashMap<String, Long>()
|
||||
private val bootstrapApproved = ConcurrentHashMap<String, String>()
|
||||
private val bootstrapRejected = ConcurrentHashMap<String, String>()
|
||||
|
||||
fun lockFor(key: String): Any = locks.computeIfAbsent(key) { Any() }
|
||||
|
||||
@@ -583,10 +735,28 @@ private object NativeTokenRefreshCoordinator {
|
||||
}
|
||||
}
|
||||
|
||||
fun isBootstrapApproved(key: String, accessToken: String): Boolean =
|
||||
bootstrapApproved[key] == accessToken
|
||||
|
||||
fun isBootstrapRejected(key: String, accessToken: String): Boolean =
|
||||
bootstrapRejected[key] == accessToken
|
||||
|
||||
fun markBootstrapApproved(key: String, accessToken: String) {
|
||||
bootstrapApproved[key] = accessToken
|
||||
bootstrapRejected.remove(key)
|
||||
}
|
||||
|
||||
fun markBootstrapRejected(key: String, accessToken: String) {
|
||||
bootstrapRejected[key] = accessToken
|
||||
bootstrapApproved.remove(key)
|
||||
}
|
||||
|
||||
fun clear(store: NativeDashboardTokenStore) {
|
||||
synchronized(lockFor(store.coordinationKey)) {
|
||||
generations[store.coordinationKey] =
|
||||
(generations[store.coordinationKey] ?: 0L) + 1L
|
||||
bootstrapApproved.remove(store.coordinationKey)
|
||||
bootstrapRejected.remove(store.coordinationKey)
|
||||
store.clear()
|
||||
}
|
||||
}
|
||||
|
||||
+29
-16
@@ -3,6 +3,7 @@ package com.hermesandroid.relay.network.upstream
|
||||
import com.hermesandroid.relay.BuildConfig
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.InterruptedIOException
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
@@ -25,6 +26,9 @@ private const val ACCEPT_POLL_MILLIS = 500
|
||||
internal const val DEFAULT_NATIVE_SIGN_IN_TIMEOUT_MILLIS = 5 * 60 * 1000L
|
||||
internal val NATIVE_SIGN_IN_RETURN_URI = "${BuildConfig.APPLICATION_ID}://return"
|
||||
|
||||
internal class NativeDashboardSignInTimeoutException :
|
||||
InterruptedIOException("Dashboard sign-in timed out")
|
||||
|
||||
private enum class CallbackPage(
|
||||
val modifier: String,
|
||||
val eyebrow: String,
|
||||
@@ -109,23 +113,24 @@ internal fun dashboardRedirectAuthMode(authFlows: List<String>): DashboardRedire
|
||||
DashboardRedirectAuthMode.WebView
|
||||
}
|
||||
|
||||
/**
|
||||
* Nous Portal uses Cloudflare Turnstile and does not support embedded Android
|
||||
* WebViews. Keep self-hosted OIDC on the dashboard cookie flow, but use the
|
||||
* gateway's brokered system-browser flow for Nous when it is advertised.
|
||||
*/
|
||||
/** Match upstream Desktop's capability-driven redirect policy. */
|
||||
internal fun androidDashboardRedirectAuthMode(
|
||||
providerName: String,
|
||||
@Suppress("UNUSED_PARAMETER") providerName: String,
|
||||
authFlows: List<String>,
|
||||
): DashboardRedirectAuthMode =
|
||||
if (
|
||||
providerName.equals("nous", ignoreCase = true) &&
|
||||
dashboardRedirectAuthMode(authFlows) == DashboardRedirectAuthMode.NativePkce
|
||||
) {
|
||||
DashboardRedirectAuthMode.NativePkce
|
||||
} else {
|
||||
DashboardRedirectAuthMode.WebView
|
||||
}
|
||||
@Suppress("UNUSED_PARAMETER") competingRedirectProviders: Int = 1,
|
||||
): DashboardRedirectAuthMode = dashboardRedirectAuthMode(authFlows)
|
||||
|
||||
/**
|
||||
* Hosted gateways commonly expose Nous as their single native provider and
|
||||
* require the selector to be omitted. Multi-provider self-hosted gateways need
|
||||
* the explicit selector so upstream can disambiguate the requested provider.
|
||||
*/
|
||||
internal fun nativeDashboardAuthorizationProvider(
|
||||
providerName: String,
|
||||
competingRedirectProviders: Int,
|
||||
): String? = providerName.takeUnless {
|
||||
it.equals("nous", ignoreCase = true) && competingRedirectProviders <= 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one native dashboard sign-in attempt.
|
||||
@@ -141,6 +146,8 @@ class NativeDashboardSignInCoordinator(
|
||||
) {
|
||||
suspend fun signIn(
|
||||
provider: String?,
|
||||
onAuthorizationPrepared: (usesAlternateOrigin: Boolean) -> Unit = {},
|
||||
onCallbackValidated: () -> Unit = {},
|
||||
launchAuthorization: suspend (String) -> Unit,
|
||||
): NativeDashboardTokens =
|
||||
try {
|
||||
@@ -165,11 +172,15 @@ class NativeDashboardSignInCoordinator(
|
||||
val attemptContext = currentCoroutineContext()
|
||||
var completed = false
|
||||
try {
|
||||
runCatching {
|
||||
onAuthorizationPrepared(authorization.usesAlternateOrigin)
|
||||
}
|
||||
launchAuthorization(authorization.authorizationUrl)
|
||||
awaitValidCallback(
|
||||
server = server,
|
||||
authorization = authorization,
|
||||
commitAllowed = { attemptContext.isActive },
|
||||
onCallbackValidated = onCallbackValidated,
|
||||
).also { completed = true }
|
||||
} finally {
|
||||
if (!completed) {
|
||||
@@ -180,13 +191,14 @@ class NativeDashboardSignInCoordinator(
|
||||
}
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
throw IOException("Dashboard sign-in timed out")
|
||||
throw NativeDashboardSignInTimeoutException()
|
||||
}
|
||||
|
||||
private suspend fun awaitValidCallback(
|
||||
server: ServerSocket,
|
||||
authorization: NativeDashboardAuthorization,
|
||||
commitAllowed: () -> Boolean,
|
||||
onCallbackValidated: () -> Unit,
|
||||
): NativeDashboardTokens {
|
||||
while (true) {
|
||||
val callback = acceptCallback(server)
|
||||
@@ -217,6 +229,7 @@ class NativeDashboardSignInCoordinator(
|
||||
authorization,
|
||||
target,
|
||||
commitAllowed = commitAllowed,
|
||||
onValidated = onCallbackValidated,
|
||||
).also {
|
||||
writeResponse(
|
||||
socket,
|
||||
|
||||
+18
-8
@@ -74,13 +74,13 @@ object ProactiveMessageNotifier {
|
||||
text: String,
|
||||
messageId: String?,
|
||||
chatId: String?,
|
||||
) {
|
||||
): Int? {
|
||||
ensureChannel(context)
|
||||
if (!hasPostNotificationsPermission(context)) {
|
||||
Log.i(TAG, "POST_NOTIFICATIONS not granted — skipping proactive notification")
|
||||
return
|
||||
return null
|
||||
}
|
||||
if (text.isBlank()) return
|
||||
if (text.isBlank()) return null
|
||||
|
||||
val tapIntent = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
@@ -89,7 +89,7 @@ object ProactiveMessageNotifier {
|
||||
val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
// Distinct requestCode per slot so each notification gets its own
|
||||
// PendingIntent rather than all sharing slot 0's intent.
|
||||
val notificationId = slotFor(messageId)
|
||||
val notificationId = slotFor(messageId, chatId)
|
||||
val tapPending =
|
||||
PendingIntent.getActivity(context, notificationId, tapIntent, pendingFlags)
|
||||
|
||||
@@ -108,9 +108,15 @@ object ProactiveMessageNotifier {
|
||||
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
|
||||
runCatching {
|
||||
return runCatching {
|
||||
NotificationManagerCompat.from(context).notify(notificationId, builder.build())
|
||||
}.onFailure { Log.w(TAG, "notify failed", it) }
|
||||
notificationId
|
||||
}.onFailure { Log.w(TAG, "notify failed", it) }.getOrNull()
|
||||
}
|
||||
|
||||
/** Cancel one exact slot previously returned by [notificationIdFor]. */
|
||||
fun cancel(context: Context, notificationId: Int) {
|
||||
NotificationManagerCompat.from(context).cancel(notificationId)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,8 +212,12 @@ object ProactiveMessageNotifier {
|
||||
}
|
||||
|
||||
/** Derive a stable notification slot from the message id. */
|
||||
private fun slotFor(messageId: String?): Int {
|
||||
val key = messageId?.takeIf { it.isNotBlank() } ?: return ID_BASE
|
||||
internal fun notificationIdFor(messageId: String?, chatId: String?): Int =
|
||||
slotFor(messageId, chatId)
|
||||
|
||||
private fun slotFor(messageId: String?, chatId: String?): Int {
|
||||
val key = messageId?.takeIf { it.isNotBlank() }
|
||||
?: "chat:${chatId?.takeIf { it.isNotBlank() } ?: "phone"}"
|
||||
// Keep within a small positive window above the base so re-delivery of
|
||||
// the same id collapses to one slot and distinct ids spread out.
|
||||
return ID_BASE + (key.hashCode() and 0xFFFF)
|
||||
|
||||
@@ -240,6 +240,25 @@ class HermesProcessRuntime internal constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun republishAssistantSnapshot(activationId: String) {
|
||||
val snapshot = synchronized(activationLock) {
|
||||
if (currentActivationId != activationId ||
|
||||
_initializationState.value != HermesRuntimeInitializationState.Ready
|
||||
) {
|
||||
null
|
||||
} else {
|
||||
binder.assistantSnapshot.value
|
||||
}
|
||||
} ?: return
|
||||
if (snapshot.phase != com.hermesandroid.relay.assistant.AssistantSessionPhase.Closed) {
|
||||
com.hermesandroid.relay.assistant.AssistantSessionProtocol.publish(
|
||||
application,
|
||||
activationId,
|
||||
snapshot,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun recordAssistantHeartbeat(
|
||||
activationId: String,
|
||||
nowElapsedMs: Long = SystemClock.elapsedRealtime(),
|
||||
|
||||
@@ -25,7 +25,9 @@ import com.hermesandroid.relay.data.VoiceSettings
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||
import com.hermesandroid.relay.network.shared.AutoVoiceAudioClient
|
||||
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
|
||||
import com.hermesandroid.relay.network.upstream.StandardHermesVoiceClient
|
||||
import com.hermesandroid.relay.viewmodel.SESSION_DIRECTORY_PAGE_SIZE
|
||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||
import com.hermesandroid.relay.viewmodel.VoiceState
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -89,7 +91,10 @@ internal class HermesRuntimeBinder(
|
||||
.build(),
|
||||
relayUrlProvider = { connection.effectiveRelayUrl.value },
|
||||
relayRouteChangesProvider = {
|
||||
connection.activeEndpoint.mapNotNull { it?.relay?.url }
|
||||
connection.activeRelayEndpoint.mapNotNull { endpoint ->
|
||||
endpoint?.pluginProxyRoutesOrNull()?.relayWebSocketUrl
|
||||
?: endpoint?.relay?.url
|
||||
}
|
||||
},
|
||||
routeProbeRequester = connection::probeNow,
|
||||
profileNameProvider = {
|
||||
@@ -99,6 +104,8 @@ internal class HermesRuntimeBinder(
|
||||
(connection.authState.value as? AuthState.Paired)?.token
|
||||
},
|
||||
apiBearerTokenProvider = connection::getApiKey,
|
||||
dashboardHttpClientProvider = connection::dashboardHttpClientForRelayIngress,
|
||||
dashboardIngressWebSocketRequestProvider = connection::dashboardRelayRequestForIngress,
|
||||
)
|
||||
val standardVoiceClient = StandardHermesVoiceClient(
|
||||
context = application,
|
||||
@@ -185,7 +192,19 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
}
|
||||
chat.setProfileSessionLister { profileName ->
|
||||
connection.listProfileScopedSessions(profileName)
|
||||
connection.listProfileScopedSessions(
|
||||
profileName = profileName,
|
||||
limit = SESSION_DIRECTORY_PAGE_SIZE,
|
||||
excludeSources = connection.hiddenSources.value,
|
||||
)
|
||||
}
|
||||
chat.setProfileSessionPageLister { profileName, offset, limit ->
|
||||
connection.listProfileScopedSessions(
|
||||
profileName = profileName,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
excludeSources = connection.hiddenSources.value,
|
||||
)
|
||||
}
|
||||
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
|
||||
connection.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
@@ -196,6 +215,7 @@ internal class HermesRuntimeBinder(
|
||||
chat.profileSessionPinner = connection::setSessionPinned
|
||||
chat.profileSessionArchiver = connection::setSessionArchived
|
||||
chat.onSessionChanged = connection::saveLastSessionId
|
||||
chat.onFreshDraftSelected = connection::saveFreshDraft
|
||||
chat.setDemoModeWiring(
|
||||
isDemo = { connection.isDemoMode.value },
|
||||
handler = { connection.chatHandler },
|
||||
@@ -291,23 +311,41 @@ internal class HermesRuntimeBinder(
|
||||
connection.activeConnectionId,
|
||||
connection.effectiveSessionProfileName,
|
||||
connection.lastSessionId,
|
||||
) { ready, connectionId, profileName, sessionId ->
|
||||
ProfileContextInputs(ready, connectionId, profileName, sessionId)
|
||||
connection.activeEndpoint,
|
||||
) { ready, connectionId, profileName, sessionId, activeEndpoint ->
|
||||
ProfileContextInputs(
|
||||
ready,
|
||||
connectionId,
|
||||
profileName,
|
||||
sessionId,
|
||||
dashboardRouteResolved = activeEndpoint != null,
|
||||
)
|
||||
}
|
||||
combine(
|
||||
contextInputs,
|
||||
connection.profileSelectionSettled,
|
||||
connection.lockedProfileName,
|
||||
) { inputs, settled, lockedProfileName ->
|
||||
connection.hiddenSources,
|
||||
) { inputs, settled, lockedProfileName, hiddenSources ->
|
||||
inputs.copy(
|
||||
profileSelectionSettled = settled,
|
||||
profileLocked = lockedProfileName != null,
|
||||
hiddenSources = hiddenSources,
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
profileContextReady.value = false
|
||||
if (!inputs.chatReady) return@collectLatest
|
||||
if (!inputs.profileSelectionSettled) delay(PROFILE_SETTLE_BACKSTOP_MS)
|
||||
else delay(PROFILE_CONTEXT_COALESCE_MS)
|
||||
if (!shouldRefreshSessionDirectory(inputs.chatReady, inputs.dashboardRouteResolved)) {
|
||||
return@collectLatest
|
||||
}
|
||||
if (!inputs.profileSelectionSettled) {
|
||||
delay(PROFILE_SETTLE_BACKSTOP_MS)
|
||||
// The backstop is diagnostic patience, not permission to
|
||||
// issue an unscoped read. Server-default ownership remains
|
||||
// unknown until the lightweight active-profile scope lands.
|
||||
if (!connection.profileSelectionSettled.value) return@collectLatest
|
||||
} else {
|
||||
delay(PROFILE_CONTEXT_COALESCE_MS)
|
||||
}
|
||||
val contextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = inputs.connectionId,
|
||||
profileName = inputs.profileName,
|
||||
@@ -321,6 +359,28 @@ internal class HermesRuntimeBinder(
|
||||
profileContextReady.value = true
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
var metadataHydratedRoute: Pair<String, String>? = null
|
||||
chat.sessionDirectoryReadyEvents.collect { event ->
|
||||
if (!chat.ownsSessionDirectoryReadyEvent(event)) return@collect
|
||||
val connectionId = connection.activeConnectionId.value ?: return@collect
|
||||
val expectedContextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = connectionId,
|
||||
profileName = connection.effectiveSessionProfileName.value,
|
||||
)
|
||||
if (event.contextKey != expectedContextKey) return@collect
|
||||
val dashboardUrl = connection.effectiveDashboardUrl.value
|
||||
.takeIf(String::isNotBlank)
|
||||
?: return@collect
|
||||
val routeKey = connectionId to dashboardUrl.trim().trimEnd('/').lowercase()
|
||||
if (metadataHydratedRoute == routeKey) return@collect
|
||||
metadataHydratedRoute = routeKey
|
||||
// `/api/profiles`, Gateway avatars, pets, skills, and model
|
||||
// metadata are not session-directory prerequisites. Hydrate
|
||||
// them only after exact-owner rows have already published.
|
||||
connection.refreshDeferredProfileMetadata()
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
connection.parseToolAnnotations.collect { enabled ->
|
||||
connection.chatHandler.parseToolAnnotations = enabled
|
||||
@@ -376,7 +436,9 @@ internal class HermesRuntimeBinder(
|
||||
if (!AssistantAppSessionState.active.value) return@collect
|
||||
if (state.voiceMode) AssistantAppSessionState.markVoiceStarted()
|
||||
if (state.voiceMode || AssistantAppSessionState.hasVoiceStarted()) {
|
||||
AssistantSessionProtocol.publish(application, snapshot)
|
||||
state.assistantActivationId?.let { activationId ->
|
||||
AssistantSessionProtocol.publish(application, activationId, snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -489,8 +551,10 @@ internal class HermesRuntimeBinder(
|
||||
val connectionId: String?,
|
||||
val profileName: String?,
|
||||
val sessionId: String?,
|
||||
val dashboardRouteResolved: Boolean,
|
||||
val profileSelectionSettled: Boolean = false,
|
||||
val profileLocked: Boolean = false,
|
||||
val hiddenSources: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
private companion object {
|
||||
@@ -500,6 +564,16 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session browsing is Dashboard HTTP state, not Gateway-socket state. API-only
|
||||
* connections still use chat readiness; Dashboard connections can refresh once
|
||||
* the resolver has selected a live route, after the profile-settle fence.
|
||||
*/
|
||||
internal fun shouldRefreshSessionDirectory(
|
||||
chatReady: Boolean,
|
||||
dashboardRouteResolved: Boolean,
|
||||
): Boolean = chatReady || dashboardRouteResolved
|
||||
|
||||
internal fun assistantCanTransmitScreenContext(engineMode: VoiceEngineMode): Boolean =
|
||||
engineMode == VoiceEngineMode.HermesVoiceOutput
|
||||
|
||||
|
||||
@@ -249,14 +249,27 @@ internal fun resolvePairSetupReady(
|
||||
authorizedHandoffId: String?,
|
||||
activeConnectionId: String?,
|
||||
connectionIds: Set<String>,
|
||||
): Boolean = connectionId == null || storeHydrated && activeConnectionId != null &&
|
||||
activeConnectionId in connectionIds &&
|
||||
(activeConnectionId == connectionId || activeConnectionId == authorizedHandoffId)
|
||||
draftConnectionId: String? = null,
|
||||
): Boolean = connectionId == null || connectionId == draftConnectionId ||
|
||||
storeHydrated && activeConnectionId != null && (
|
||||
activeConnectionId == connectionId ||
|
||||
activeConnectionId == authorizedHandoffId && activeConnectionId in connectionIds
|
||||
)
|
||||
|
||||
/** A user retry replaces even a still-active preparation attempt. */
|
||||
internal fun shouldStartPairPreparation(hasActiveJob: Boolean, retryRequested: Boolean): Boolean =
|
||||
retryRequested || !hasActiveJob
|
||||
|
||||
internal fun shouldCommitPairDraftBeforeDashboardSignIn(
|
||||
connectionId: String?,
|
||||
draftConnectionId: String?,
|
||||
): Boolean = connectionId != null && connectionId == draftConnectionId
|
||||
|
||||
/** Pair-origin sign-in must finish the staged Dashboard-ingress Relay handshake. */
|
||||
internal fun shouldResumePairingAfterDashboardAuthentication(source: String): Boolean =
|
||||
source == Screen.DashboardSignIn.SOURCE_PAIR ||
|
||||
source == Screen.DashboardSignIn.SOURCE_ONBOARDING
|
||||
|
||||
/** A replaced/canceled attempt must not evict the newer job from the route map. */
|
||||
internal fun isCurrentPairPreparation(mappedJob: Any?, completingJob: Any): Boolean =
|
||||
mappedJob === completingJob
|
||||
@@ -287,6 +300,28 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
|
||||
}
|
||||
|
||||
internal fun shouldSettleStartupUnreachable(
|
||||
hasConfiguredChat: Boolean,
|
||||
runtimeStatus: ChatRuntimeStatus,
|
||||
): Boolean =
|
||||
hasConfiguredChat &&
|
||||
runtimeStatus is ChatRuntimeStatus.Unavailable
|
||||
|
||||
internal fun startupShellCanRender(
|
||||
appReady: Boolean,
|
||||
hasStartupConnection: Boolean,
|
||||
endpointSelected: Boolean,
|
||||
chatUp: Boolean,
|
||||
narrationStage: Int,
|
||||
unreachableConfirmed: Boolean,
|
||||
timedOut: Boolean,
|
||||
): Boolean = appReady && (
|
||||
!hasStartupConnection ||
|
||||
((endpointSelected || chatUp) && narrationStage >= 2) ||
|
||||
unreachableConfirmed ||
|
||||
timedOut
|
||||
)
|
||||
|
||||
/** Route represented by the app footer's currently usable chat transport. */
|
||||
internal fun resolveFooterRouteCandidate(
|
||||
runtimeStatus: ChatRuntimeStatus,
|
||||
@@ -319,6 +354,40 @@ internal fun resolveFooterRouteCandidate(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact, surface-aware label for the persistent chat footer.
|
||||
*
|
||||
* 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
|
||||
* the route's ordinary transport label.
|
||||
*/
|
||||
internal fun resolveFooterRouteLabel(
|
||||
runtimeStatus: ChatRuntimeStatus,
|
||||
route: EndpointCandidate?,
|
||||
fallbackLabel: String,
|
||||
): String {
|
||||
val connected = runtimeStatus as? ChatRuntimeStatus.Connected ?: return ""
|
||||
if (route == null) return fallbackLabel
|
||||
if (connected.transport == ChatTransportPath.ApiSse) return route.displayLabel()
|
||||
|
||||
return when (route.role.trim().lowercase()) {
|
||||
"lan" -> "LAN"
|
||||
"tailscale" -> "Tailscale"
|
||||
else -> if (
|
||||
route.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
|
||||
) {
|
||||
"HTTP"
|
||||
} else {
|
||||
route.displayLabel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep the footer's model identity compact; context-window suffixes belong in model details. */
|
||||
internal fun compactFooterModelLabel(model: String): String =
|
||||
model.substringAfterLast('/').replace(Regex("-\\d+[kKmM]$"), "")
|
||||
|
||||
/**
|
||||
* Conversation voice remains part of chat, so its persistent connection
|
||||
* footer stays visible. Focus voice is the only presentation that suppresses
|
||||
@@ -484,10 +553,8 @@ sealed class Screen(
|
||||
//
|
||||
// Multi-connection: accepts an optional `connectionId` query arg —
|
||||
// the ConnectionsSettings "Re-pair" button targets a specific
|
||||
// connection. The "Add connection" path pre-creates a placeholder
|
||||
// via `ConnectionViewModel.beginAddConnection()` and routes here
|
||||
// with that id, so the wizard's standard connect / applyPairingPayload lands in the
|
||||
// new connection's auth store instead of the outgoing one's.
|
||||
// connection. The "Add connection" path creates a transient id-scoped
|
||||
// auth draft; it is persisted and activated only after setup succeeds.
|
||||
data object Pair : Screen(
|
||||
"pair?connectionId={connectionId}&autoStart={autoStart}",
|
||||
"Connect",
|
||||
@@ -511,7 +578,7 @@ sealed class Screen(
|
||||
return if (params.isEmpty()) "pair" else "pair?${params.joinToString("&")}"
|
||||
}
|
||||
}
|
||||
data object ConnectionsSettings : Screen("settings/connections", "Connections", Icons.Filled.Settings)
|
||||
data object ConnectionsSettings : Screen("settings/connections", "Gateways", Icons.Filled.Settings)
|
||||
// Level-2 detail for a single connection (tabbed: Overview / Routes /
|
||||
// Advanced / Security). Drilled into from the Connections list. The
|
||||
// `connectionId` path segment survives process death via SavedStateHandle;
|
||||
@@ -750,6 +817,7 @@ fun RelayApp() {
|
||||
val profileSelectionSettled by connectionViewModel.profileSelectionSettled.collectAsState()
|
||||
val agentProfiles by connectionViewModel.agentProfiles.collectAsState()
|
||||
val activeConnectionId by connectionViewModel.activeConnectionId.collectAsState()
|
||||
val activeConnection by connectionViewModel.activeConnection.collectAsState()
|
||||
val connectionStoreHydrated by
|
||||
connectionViewModel.connectionStore.isHydrated.collectAsState()
|
||||
val supervisedModeStore = remember(applicationContext) {
|
||||
@@ -771,18 +839,14 @@ fun RelayApp() {
|
||||
}
|
||||
val ownedSupervisedPolicyState = supervisedPolicyState.value
|
||||
?.takeIf { (ownerConnectionId, _) -> ownerConnectionId == activeConnectionId }
|
||||
// Fail closed across process restoration. activeConnectionId starts as
|
||||
// null while ConnectionStore reads DataStore, so null alone cannot prove
|
||||
// this is a fresh install with no supervised policy to restore.
|
||||
if (!isRelayNavigationHydrated(
|
||||
connectionStoreHydrated = connectionStoreHydrated,
|
||||
activeConnectionId = activeConnectionId,
|
||||
supervisedPolicyHydrated = ownedSupervisedPolicyState != null,
|
||||
)
|
||||
) {
|
||||
SupervisedStartupLoadingScreen()
|
||||
return
|
||||
}
|
||||
// Keep navigation mounted while the new connection owner's supervised
|
||||
// policy loads. Protected destinations are covered later in the NavHost
|
||||
// box; returning here would dispose the controller and replay cold start.
|
||||
val relayNavigationHydrated = isRelayNavigationHydrated(
|
||||
connectionStoreHydrated = connectionStoreHydrated,
|
||||
activeConnectionId = activeConnectionId,
|
||||
supervisedPolicyHydrated = ownedSupervisedPolicyState != null,
|
||||
)
|
||||
val supervisedPolicy = ownedSupervisedPolicyState?.second ?: SupervisedModePolicy()
|
||||
val supervisedPinnedProfile = supervisedPolicy.pinnedProfileName?.let { name ->
|
||||
agentProfiles.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
@@ -798,12 +862,14 @@ fun RelayApp() {
|
||||
var parentAccessUnlocked by remember(activeConnectionId) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(
|
||||
relayNavigationHydrated,
|
||||
activeConnectionId,
|
||||
supervisedPolicy,
|
||||
agentProfiles,
|
||||
selectedProfile,
|
||||
profileSelectionSettled,
|
||||
) {
|
||||
if (!relayNavigationHydrated) return@LaunchedEffect
|
||||
chatViewModel.updateSupervisedModePolicy(chatSupervisedPolicy)
|
||||
connectionViewModel.authManager.updateSupervisedMode(chatSupervisedPolicy)
|
||||
if (!supervisedPolicy.enabled) {
|
||||
@@ -862,6 +928,7 @@ fun RelayApp() {
|
||||
val serverCapabilities by connectionViewModel.serverCapabilities.collectAsState()
|
||||
val gatewayAvailability by connectionViewModel.gatewayAvailability.collectAsState()
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val gitRepoScanningEnabled = activeConnection?.gitRepoScanningEnabled == true
|
||||
val gitOwnerKey = activeConnectionId?.takeIf { it.isNotBlank() }?.let { connectionId ->
|
||||
effectiveDashboardUrl.takeIf { it.isNotBlank() }?.let { dashboardUrl ->
|
||||
"$connectionId\u0000${effectiveSessionProfileName.orEmpty()}\u0000$dashboardUrl"
|
||||
@@ -881,11 +948,15 @@ fun RelayApp() {
|
||||
sessionId = currentChatSessionId,
|
||||
)
|
||||
}
|
||||
LaunchedEffect(gitOwnerKey) {
|
||||
LaunchedEffect(gitOwnerKey, gitRepoScanningEnabled) {
|
||||
val dashboard = effectiveDashboardUrl
|
||||
.takeIf { it.isNotBlank() }
|
||||
?.let { connectionViewModel.dashboardClientForActive(it) }
|
||||
gitStateViewModel.configure(dashboard, gitOwnerKey)
|
||||
gitStateViewModel.configure(
|
||||
dashboard = dashboard,
|
||||
ownerKey = gitOwnerKey,
|
||||
scanningEnabled = gitRepoScanningEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
// Mirror the plugin.api.write grant into the Git view model so write
|
||||
@@ -928,7 +999,8 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
|
||||
val gitWorkspaceAvailable = gitReposState is GitStateUiState.Ready
|
||||
val gitWorkspaceAvailable = gitRepoScanningEnabled &&
|
||||
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
||||
val gitWorkspaceSummary = remember(
|
||||
gitReposState,
|
||||
gitDetailState,
|
||||
@@ -1251,10 +1323,12 @@ fun RelayApp() {
|
||||
// ineffective even before the state-clearing effect runs.
|
||||
LaunchedEffect(
|
||||
navController,
|
||||
relayNavigationHydrated,
|
||||
supervisedPolicy.enabled,
|
||||
parentAccessForCurrentRoute,
|
||||
) {
|
||||
com.hermesandroid.relay.util.NavRouteRequest.requests.collect { route ->
|
||||
if (!relayNavigationHydrated) return@collect
|
||||
if (
|
||||
supervisedPolicy.enabled &&
|
||||
!isSupervisedRouteAllowed(route, parentAccessForCurrentRoute)
|
||||
@@ -1265,10 +1339,12 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
LaunchedEffect(
|
||||
relayNavigationHydrated,
|
||||
supervisedPolicy.enabled,
|
||||
parentAccessForCurrentRoute,
|
||||
currentRoute,
|
||||
) {
|
||||
if (!relayNavigationHydrated) return@LaunchedEffect
|
||||
val redirect = shouldRedirectSupervisedRoute(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
@@ -1312,11 +1388,12 @@ fun RelayApp() {
|
||||
lifecycleOwner.lifecycle.addObserver(relockObserver)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(relockObserver) }
|
||||
}
|
||||
val suppressGlobalChrome = shouldSuppressGlobalChrome(
|
||||
onboardingCompleted = onboardingCompleted,
|
||||
isDemoMode = isDemoMode,
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
val suppressGlobalChrome = !relayNavigationHydrated ||
|
||||
shouldSuppressGlobalChrome(
|
||||
onboardingCompleted = onboardingCompleted,
|
||||
isDemoMode = isDemoMode,
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
|
||||
// Safety net: landing on a real connect surface (onboarding or the
|
||||
// Connect/Pair wizard) while demo is still active — via the banner's
|
||||
@@ -1435,13 +1512,13 @@ fun RelayApp() {
|
||||
}
|
||||
val postResumeQuiet by connectionViewModel.postResumeQuiet.collectAsState()
|
||||
val apiHealth by connectionViewModel.apiServerHealth.collectAsState()
|
||||
val activeConnection by connectionViewModel.activeConnection.collectAsState()
|
||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||
val connectionSecurity by connectionViewModel.connectionSecurity.collectAsState()
|
||||
val serverModelName by chatViewModel.serverModelName.collectAsState()
|
||||
val gatewayCurrentModel by chatViewModel.gatewayCurrentModel.collectAsState()
|
||||
val appReady by connectionViewModel.isReady.collectAsState()
|
||||
val initialChatSettled by chatViewModel.initialChatSettled.collectAsState()
|
||||
val startupSessionsLoading by chatViewModel.isLoadingSessions.collectAsState()
|
||||
val shareConnectionId by rememberUpdatedState(
|
||||
activeConnection?.id?.takeIf(String::isNotBlank) ?: "offline"
|
||||
)
|
||||
@@ -1528,15 +1605,24 @@ fun RelayApp() {
|
||||
// first verdict was what flashed the disconnected chat UI at users
|
||||
// who were connected-just-waiting. The keyed effect restarts on
|
||||
// every health flip, cancelling a pending settle.
|
||||
LaunchedEffect(appChatRuntimeStatus, startupGateReleased) {
|
||||
LaunchedEffect(appChatRuntimeStatus, activeEndpoint, startupGateReleased) {
|
||||
if (startupGateReleased) return@LaunchedEffect
|
||||
if (hasStartupConnection && appChatRuntimeStatus is ChatRuntimeStatus.Unavailable) {
|
||||
if (shouldSettleStartupUnreachable(
|
||||
hasConfiguredChat = hasStartupConnection,
|
||||
runtimeStatus = appChatRuntimeStatus,
|
||||
)
|
||||
) {
|
||||
delay(3_000L)
|
||||
startupUnreachableSettled = true
|
||||
} else {
|
||||
startupUnreachableSettled = false
|
||||
}
|
||||
}
|
||||
val startupUnreachableConfirmed = startupUnreachableSettled &&
|
||||
shouldSettleStartupUnreachable(
|
||||
hasConfiguredChat = hasStartupConnection,
|
||||
runtimeStatus = appChatRuntimeStatus,
|
||||
)
|
||||
|
||||
// ---- Startup narration: real states the checklist verifies ----
|
||||
val startupEndpoint = activeEndpoint
|
||||
@@ -1563,8 +1649,14 @@ fun RelayApp() {
|
||||
when {
|
||||
startupChatUp ->
|
||||
StartupCheck(StartupCheckState.Done, "hermes online")
|
||||
appChatRuntimeStatus is ChatRuntimeStatus.Unavailable ->
|
||||
startupUnreachableConfirmed ->
|
||||
StartupCheck(StartupCheckState.Failed, "hermes unreachable")
|
||||
appChatRuntimeStatus is ChatRuntimeStatus.Unavailable && startupEndpoint != null ->
|
||||
StartupCheck(StartupCheckState.Active, "gateway retrying")
|
||||
startupEndpoint != null -> StartupCheck(
|
||||
StartupCheckState.Active,
|
||||
"waking ${effectiveDisplayProfile?.name?.replaceFirstChar { it.uppercase() } ?: "Hermes"}",
|
||||
)
|
||||
appReady ->
|
||||
StartupCheck(StartupCheckState.Active, "contacting hermes")
|
||||
else -> StartupCheck(StartupCheckState.Pending, "hermes")
|
||||
@@ -1573,10 +1665,12 @@ fun RelayApp() {
|
||||
// renders from — so this row can never tick while the chat
|
||||
// surface would still show its connect CTA.
|
||||
when {
|
||||
chatReady && initialChatSettled ->
|
||||
StartupCheck(StartupCheckState.Done, "conversation ready")
|
||||
initialChatSettled && !startupSessionsLoading ->
|
||||
StartupCheck(StartupCheckState.Done, "sessions ready")
|
||||
startupSessionsLoading ->
|
||||
StartupCheck(StartupCheckState.Active, "loading sessions")
|
||||
startupChatUp ->
|
||||
StartupCheck(StartupCheckState.Active, "loading conversation")
|
||||
StartupCheck(StartupCheckState.Active, "restoring conversation")
|
||||
else -> StartupCheck(StartupCheckState.Pending, "conversation")
|
||||
},
|
||||
)
|
||||
@@ -1600,25 +1694,22 @@ fun RelayApp() {
|
||||
startupNarrationStage += 1
|
||||
}
|
||||
}
|
||||
// Full-screen startup owns only process state + route selection. The
|
||||
// mounted Chat surface owns Gateway wake and session hydration so the
|
||||
// user can see cached rows and accurate inline progress instead of a
|
||||
// global sphere that appears hung for the server's entire wake budget.
|
||||
val startupNarrationComplete =
|
||||
startupNarrationStage >= startupCheckTargets.size
|
||||
startupNarrationStage >= minOf(2, startupCheckTargets.size)
|
||||
|
||||
val startupConnectionResolved = appReady && (
|
||||
!hasStartupConnection ||
|
||||
// Happy path: the chat surface's OWN readiness signal is
|
||||
// true (client built + reachable verdict — what its connect
|
||||
// CTA renders from), the last conversation has been restored
|
||||
// (or there was none), and the checklist has visibly
|
||||
// finished ticking. Anything weaker (e.g. the resolver's
|
||||
// earlier health evidence) reveals a chat screen that still
|
||||
// shows "Connect Vanilla Hermes" for the few hundred ms
|
||||
// until the client-based verdict catches up.
|
||||
(chatReady && initialChatSettled && startupNarrationComplete) ||
|
||||
// Error path: a settled unreachable reveals the normal UI,
|
||||
// which owns offline presentation (status pill, retry).
|
||||
startupUnreachableSettled ||
|
||||
startupGateTimedOut
|
||||
)
|
||||
val startupConnectionResolved = startupShellCanRender(
|
||||
appReady = appReady,
|
||||
hasStartupConnection = hasStartupConnection,
|
||||
endpointSelected = startupEndpoint != null,
|
||||
chatUp = startupChatUp,
|
||||
narrationStage = startupNarrationStage,
|
||||
unreachableConfirmed = startupUnreachableConfirmed,
|
||||
timedOut = startupGateTimedOut,
|
||||
)
|
||||
LaunchedEffect(
|
||||
onboardingCompleted,
|
||||
startupGateMinElapsed,
|
||||
@@ -1640,7 +1731,7 @@ fun RelayApp() {
|
||||
if (
|
||||
hasStartupConnection &&
|
||||
!happyPathReady &&
|
||||
!startupUnreachableSettled &&
|
||||
!startupUnreachableConfirmed &&
|
||||
startupGateTimedOut
|
||||
) {
|
||||
DiagnosticsLog.record(
|
||||
@@ -2000,19 +2091,20 @@ fun RelayApp() {
|
||||
connection = activeConnection,
|
||||
effectiveDashboardUrl = effectiveDashboardUrl,
|
||||
)
|
||||
val routeLabel = footerRoute?.displayLabel()
|
||||
?: activeConnection?.label
|
||||
?: stringResource(R.string.status_no_route)
|
||||
val routeLabel = resolveFooterRouteLabel(
|
||||
runtimeStatus = appChatRuntimeStatus,
|
||||
route = footerRoute,
|
||||
fallbackLabel = activeConnection?.label
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
val transportRouteLabel = if (transportStatus.tier == ChatTransportTier.Offline) {
|
||||
""
|
||||
} else {
|
||||
routeLabel
|
||||
}
|
||||
val transportRouteLabel = if (
|
||||
transportStatus.tier == ChatTransportTier.Offline
|
||||
) "" else routeLabel
|
||||
val profileLabel = AgentDisplay.profileDisplayName(effectiveDisplayProfile)
|
||||
?: stringResource(R.string.status_profile_default)
|
||||
val displayProfile = effectiveDisplayProfile
|
||||
@@ -2020,12 +2112,7 @@ fun RelayApp() {
|
||||
?: AgentDisplay.displayModelName(displayProfile?.model)
|
||||
?: AgentDisplay.displayModelName(serverModelName)
|
||||
?: stringResource(R.string.status_model_pending)
|
||||
val safetyLabel = if (BuildFlavor.isSideload && masterEnabled) {
|
||||
if (unattendedEnabled && timedScreenControlActive) stringResource(R.string.status_safety_unattended)
|
||||
else stringResource(R.string.status_safety_on)
|
||||
} else {
|
||||
stringResource(R.string.status_profile_format, profileLabel)
|
||||
}
|
||||
val footerModelLabel = compactFooterModelLabel(modelLabel)
|
||||
val openConnections = {
|
||||
navController.navigate(Screen.ConnectionsSettings.route) {
|
||||
launchSingleTop = true
|
||||
@@ -2039,7 +2126,7 @@ fun RelayApp() {
|
||||
)
|
||||
},
|
||||
routeLabel = transportRouteLabel,
|
||||
trailing = "$modelLabel / $safetyLabel",
|
||||
trailing = "$footerModelLabel / $profileLabel",
|
||||
// Tap the persistent status/route readout to open
|
||||
// Connections — preserves the affordance the dropped
|
||||
// header endpoint chip used to provide.
|
||||
@@ -2078,6 +2165,7 @@ fun RelayApp() {
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
composable(Screen.Onboarding.route) {
|
||||
val onboardingDraftId by connectionViewModel.connectionDraftId.collectAsState()
|
||||
// The wizard inside OnboardingScreen now owns credential
|
||||
// application via ConnectionViewModel.applyPairingPayload,
|
||||
// so the callback collapses to "mark complete + navigate
|
||||
@@ -2096,19 +2184,69 @@ fun RelayApp() {
|
||||
OnboardingScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onComplete = {
|
||||
connectionViewModel.completeOnboarding()
|
||||
// Concrete bare-"chat" URI — the Screen.Chat.route
|
||||
// field is the route TEMPLATE (contains
|
||||
// `{openAgentSheet}`) and must not be navigated
|
||||
// to directly; build the URI via Screen.Chat.route(...).
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(Screen.Onboarding.route) { inclusive = true }
|
||||
val draftId = onboardingDraftId
|
||||
connectionSwitchScope.launch {
|
||||
val prepared = runCatching {
|
||||
if (draftId != null) {
|
||||
connectionViewModel.commitConnectionDraft(draftId)
|
||||
}
|
||||
}
|
||||
if (prepared.isFailure) {
|
||||
val error = prepared.exceptionOrNull()
|
||||
android.util.Log.e(
|
||||
"GatewayPairFlow",
|
||||
"Could not commit onboarding gateway",
|
||||
error,
|
||||
)
|
||||
snackbarHostState.showSnackbar(
|
||||
error?.message ?: "Could not finish gateway setup",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
connectionViewModel.completeOnboarding()
|
||||
// Concrete bare-"chat" URI — the Screen.Chat.route
|
||||
// field is the route TEMPLATE (contains
|
||||
// `{openAgentSheet}`) and must not be navigated
|
||||
// to directly; build the URI via Screen.Chat.route(...).
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(Screen.Onboarding.route) { inclusive = true }
|
||||
}
|
||||
}
|
||||
},
|
||||
onManageSignIn = {
|
||||
navController.navigate(
|
||||
Screen.DashboardSignIn.route(Screen.DashboardSignIn.SOURCE_ONBOARDING),
|
||||
)
|
||||
val draftId = onboardingDraftId
|
||||
connectionSwitchScope.launch {
|
||||
android.util.Log.i(
|
||||
"GatewayPairFlow",
|
||||
"Preparing onboarding gateway for Dashboard sign-in",
|
||||
)
|
||||
val prepared = runCatching {
|
||||
if (draftId != null) {
|
||||
connectionViewModel.commitConnectionDraft(draftId)
|
||||
}
|
||||
}
|
||||
if (prepared.isFailure) {
|
||||
val error = prepared.exceptionOrNull()
|
||||
android.util.Log.e(
|
||||
"GatewayPairFlow",
|
||||
"Could not prepare onboarding Dashboard sign-in",
|
||||
error,
|
||||
)
|
||||
snackbarHostState.showSnackbar(
|
||||
error?.message ?: "Could not prepare Dashboard sign-in",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
android.util.Log.i(
|
||||
"GatewayPairFlow",
|
||||
"Opening Dashboard sign-in from onboarding",
|
||||
)
|
||||
navController.navigate(
|
||||
Screen.DashboardSignIn.route(Screen.DashboardSignIn.SOURCE_ONBOARDING),
|
||||
) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
},
|
||||
onOpenPermissions = {
|
||||
navController.navigate(Screen.PermissionsSettings.route)
|
||||
@@ -2217,9 +2355,12 @@ fun RelayApp() {
|
||||
(it.connectionId == null || it.connectionId == activeConnectionId) &&
|
||||
(it.chatId ?: "phone") == chatId
|
||||
}
|
||||
if (entries.isEmpty()) return@LaunchedEffect
|
||||
chatViewModel.openProactiveThread(chatId, entries)
|
||||
if (entries.isNotEmpty()) {
|
||||
chatViewModel.openProactiveThread(chatId, entries)
|
||||
}
|
||||
}
|
||||
// Consume the request even when deletion removed its
|
||||
// local row before a stale notification tap arrived.
|
||||
backStackEntry.arguments?.putString(
|
||||
Screen.Chat.ARG_PROACTIVE_CHAT_ID,
|
||||
null,
|
||||
@@ -2290,7 +2431,7 @@ fun RelayApp() {
|
||||
},
|
||||
// AgentInfoSheet footer jumps straight into the full
|
||||
// Connections CRUD screen — saves a detour through
|
||||
// Settings → Connections.
|
||||
// Settings → Gateways.
|
||||
onNavigateToConnections = {
|
||||
navController.navigate(Screen.ConnectionsSettings.route)
|
||||
},
|
||||
@@ -2314,13 +2455,9 @@ fun RelayApp() {
|
||||
// without leaving Chat. Safe here — this state only shows when
|
||||
// nothing is configured, so there's no placeholder in flight.
|
||||
onTryDemo = enterDemo,
|
||||
onNavigateToManage = {
|
||||
navController.navigate(Screen.Manage.route) {
|
||||
popUpTo(navController.graph.findStartDestination().id) {
|
||||
saveState = true
|
||||
}
|
||||
onNavigateToDashboardSignIn = {
|
||||
navController.navigate(Screen.DashboardSignIn.route()) {
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
},
|
||||
onNavigateToBridge = {
|
||||
@@ -2538,6 +2675,13 @@ fun RelayApp() {
|
||||
DashboardSignInScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
onAuthenticationReady = if (
|
||||
shouldResumePairingAfterDashboardAuthentication(source)
|
||||
) {
|
||||
{ connectionViewModel.resumeDeferredDashboardRelayPairing() }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onAuthenticated = {
|
||||
when (source) {
|
||||
Screen.DashboardSignIn.SOURCE_ONBOARDING -> {
|
||||
@@ -2687,6 +2831,7 @@ fun RelayApp() {
|
||||
SettingsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
chatViewModel = chatViewModel,
|
||||
gitRepoScanningEnabled = gitRepoScanningEnabled,
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
onRequestParentAccess = { parentAccessUnlocked = true },
|
||||
@@ -2862,6 +3007,7 @@ fun RelayApp() {
|
||||
composable(Screen.GitState.route) {
|
||||
GitStateScreen(
|
||||
viewModel = gitStateViewModel,
|
||||
onScanningEnabledChange = connectionViewModel::setGitRepoScanningEnabled,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
@@ -3054,14 +3200,20 @@ fun RelayApp() {
|
||||
onOpenConnection = { id ->
|
||||
navController.navigate(Screen.ConnectionDetail.route(id))
|
||||
},
|
||||
addConnectionEnabled = mayStartAddConnection(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
),
|
||||
onAddConnection = {
|
||||
val id = java.util.UUID.randomUUID().toString()
|
||||
// Draw step 1 immediately. Placeholder persistence
|
||||
// and the heavy connection-context switch continue
|
||||
// underneath the discovery UI instead of blocking
|
||||
// navigation on encrypted-store/client setup.
|
||||
navController.navigate(Screen.Pair.route(connectionId = id))
|
||||
prepareAddConnection(id, false)
|
||||
runAddConnectionAction(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
navigateToPair = {
|
||||
navController.navigate(Screen.Pair.route(connectionId = id))
|
||||
},
|
||||
prepareConnection = { prepareAddConnection(id, false) },
|
||||
)
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
// Pass the VM so the list cards can read live status
|
||||
@@ -3155,6 +3307,7 @@ fun RelayApp() {
|
||||
?.getString(Screen.Pair.ARG_AUTO_START)
|
||||
val pairConnections by connectionViewModel.connections.collectAsState()
|
||||
val pairActiveId by connectionViewModel.activeConnectionId.collectAsState()
|
||||
val pairDraftId by connectionViewModel.connectionDraftId.collectAsState()
|
||||
val pairStoreHydrated by connectionViewModel.connectionStore.isHydrated.collectAsState()
|
||||
// Duplicate Renew authorizes one explicit route handoff
|
||||
// before switching away from the placeholder. Persist the
|
||||
@@ -3170,6 +3323,7 @@ fun RelayApp() {
|
||||
authorizedHandoffId = authorizedPairHandoffId,
|
||||
activeConnectionId = pairActiveId,
|
||||
connectionIds = pairConnections.mapTo(mutableSetOf()) { it.id },
|
||||
draftConnectionId = pairDraftId,
|
||||
)
|
||||
com.hermesandroid.relay.ui.screens.PairScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
@@ -3199,22 +3353,57 @@ fun RelayApp() {
|
||||
// flight that enterDemo would leave un-discarded.
|
||||
onTryDemo = if (connectionIdArg == null) enterDemo else null,
|
||||
onComplete = {
|
||||
// Both "add new" and "re-pair in place" now
|
||||
// route to this screen with connectionIdArg
|
||||
// set — add-new goes through
|
||||
// ConnectionViewModel.beginAddConnection()
|
||||
// which pre-creates the placeholder + switches
|
||||
// to it before navigating here, so
|
||||
// applyPairingPayload lands on the correct
|
||||
// auth store. Nothing extra to do on success
|
||||
// beyond popping the backstack.
|
||||
navController.popBackStack()
|
||||
if (connectionIdArg != null && pairDraftId == connectionIdArg) {
|
||||
connectionSwitchScope.launch {
|
||||
connectionViewModel.commitConnectionDraft(connectionIdArg)
|
||||
navController.popBackStack()
|
||||
}
|
||||
} else {
|
||||
navController.popBackStack()
|
||||
}
|
||||
},
|
||||
onManageSignIn = {
|
||||
navController.navigate(
|
||||
Screen.DashboardSignIn.route(Screen.DashboardSignIn.SOURCE_PAIR),
|
||||
val targetId = connectionIdArg
|
||||
if (
|
||||
shouldCommitPairDraftBeforeDashboardSignIn(
|
||||
connectionId = targetId,
|
||||
draftConnectionId = pairDraftId,
|
||||
) && targetId != null
|
||||
) {
|
||||
launchSingleTop = true
|
||||
connectionSwitchScope.launch {
|
||||
android.util.Log.i(
|
||||
"GatewayPairFlow",
|
||||
"Committing staged gateway before Dashboard sign-in",
|
||||
)
|
||||
runCatching {
|
||||
connectionViewModel.commitConnectionDraft(targetId)
|
||||
}.onSuccess {
|
||||
android.util.Log.i(
|
||||
"GatewayPairFlow",
|
||||
"Opening Dashboard sign-in for staged gateway",
|
||||
)
|
||||
navController.navigate(
|
||||
Screen.DashboardSignIn.route(Screen.DashboardSignIn.SOURCE_PAIR),
|
||||
) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}.onFailure { error ->
|
||||
android.util.Log.e(
|
||||
"GatewayPairFlow",
|
||||
"Could not commit staged gateway before sign-in",
|
||||
error,
|
||||
)
|
||||
snackbarHostState.showSnackbar(
|
||||
error.message ?: "Could not prepare Dashboard sign-in",
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
navController.navigate(
|
||||
Screen.DashboardSignIn.route(Screen.DashboardSignIn.SOURCE_PAIR),
|
||||
) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
},
|
||||
onCancel = {
|
||||
@@ -3402,6 +3591,8 @@ fun RelayApp() {
|
||||
okHttpClient = profileInspectorHttpClient,
|
||||
relayUrlProvider = { relayUrl },
|
||||
sessionTokenProvider = { relayToken },
|
||||
dashboardHttpClientProvider =
|
||||
connectionViewModel::dashboardHttpClientForRelayIngress,
|
||||
),
|
||||
gatewayClient = inspectorGatewayClient,
|
||||
savedStateHandle = ssh,
|
||||
@@ -3430,9 +3621,15 @@ fun RelayApp() {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!routeContentAllowed) {
|
||||
if (shouldCoverRelayNavigation(
|
||||
navigationHydrated = relayNavigationHydrated,
|
||||
routeContentAllowed = routeContentAllowed,
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
) {
|
||||
// Keep the graph mounted so the redirect can complete, but
|
||||
// cover restored parent-only content with an opaque fail-closed surface.
|
||||
// cover restored parent-only content and policy-owner
|
||||
// hydration with an opaque fail-closed surface.
|
||||
SupervisedStartupLoadingScreen()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,23 @@ internal fun isSupervisedRouteAllowed(route: String?, parentAccessUnlocked: Bool
|
||||
normalized == Screen.SupervisedAppearanceSettings.route
|
||||
}
|
||||
|
||||
internal fun mayStartAddConnection(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
): Boolean = !supervisedEnabled || parentAccessUnlocked
|
||||
|
||||
internal inline fun runAddConnectionAction(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
navigateToPair: () -> Unit,
|
||||
prepareConnection: () -> Unit,
|
||||
): Boolean {
|
||||
if (!mayStartAddConnection(supervisedEnabled, parentAccessUnlocked)) return false
|
||||
navigateToPair()
|
||||
prepareConnection()
|
||||
return true
|
||||
}
|
||||
|
||||
/** Do not inspect or mutate a NavController until its first destination exists. */
|
||||
internal fun shouldRedirectSupervisedRoute(
|
||||
supervisedEnabled: Boolean,
|
||||
@@ -45,6 +62,25 @@ internal fun isRelayNavigationHydrated(
|
||||
): Boolean = connectionStoreHydrated &&
|
||||
(activeConnectionId == null || supervisedPolicyHydrated)
|
||||
|
||||
/**
|
||||
* Keep the NavHost mounted while a new connection's supervised policy loads.
|
||||
* Setup and Dashboard sign-in expose no protected conversation/settings data,
|
||||
* so they may remain visible; every other route stays covered fail-closed.
|
||||
*/
|
||||
internal fun shouldCoverRelayNavigation(
|
||||
navigationHydrated: Boolean,
|
||||
routeContentAllowed: Boolean,
|
||||
currentRoute: String?,
|
||||
): Boolean {
|
||||
if (!routeContentAllowed) return true
|
||||
if (navigationHydrated) return false
|
||||
return currentRoute?.substringBefore('?') !in setOf(
|
||||
Screen.Onboarding.route,
|
||||
Screen.Pair.route.substringBefore('?'),
|
||||
Screen.DashboardSignIn.route.substringBefore('?'),
|
||||
)
|
||||
}
|
||||
|
||||
/** A parent unlock never follows the user back into the supervised chat root. */
|
||||
internal fun shouldRelockParentAccess(
|
||||
supervisedEnabled: Boolean,
|
||||
|
||||
+552
-616
File diff suppressed because it is too large
Load Diff
@@ -47,7 +47,7 @@ import com.hermesandroid.relay.viewmodel.BridgeStatus
|
||||
* Phase 3 Wave 1 — bridge-ui (`bridge-screen-ui`). Visual style mirrors the status
|
||||
* cards in `PairedDevicesScreen`: surfaceVariant background, 16dp padding,
|
||||
* 10dp row spacing. Uses [ConnectionStatusBadge] for the pulsing status dot
|
||||
* so the Bridge tab looks visually consistent with the Settings → Connections
|
||||
* so the Bridge tab looks visually consistent with the Settings → Gateways
|
||||
* section.
|
||||
*
|
||||
* The headline switch is `enabled = allowEnable` so users can't flip it on
|
||||
|
||||
@@ -30,7 +30,7 @@ import com.hermesandroid.relay.viewmodel.BridgeStatus
|
||||
* Phase 3 Wave 1 — bridge-ui (`bridge-screen-ui`). Kept distinct from
|
||||
* [BridgeMasterToggle] so that Agent safety-rails in Wave 2 can relocate the master
|
||||
* toggle without losing the status surface (and so we can reuse this card
|
||||
* in the Settings → Connections section later if desired).
|
||||
* in Settings → Gateways later if desired).
|
||||
*/
|
||||
@Composable
|
||||
fun BridgeStatusCard(
|
||||
|
||||
+32
-2
@@ -14,6 +14,9 @@ import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.LinkOff
|
||||
import androidx.compose.material.icons.filled.Shield
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -30,6 +33,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.data.ConnectionSecurity
|
||||
import com.hermesandroid.relay.data.ConnectionSecurityLevel
|
||||
import com.hermesandroid.relay.data.SurfaceSecurity
|
||||
import com.hermesandroid.relay.data.SurfaceUseState
|
||||
|
||||
private const val LEARN_MORE_URL =
|
||||
"https://hermes-relay.dev/docs/architecture/connection-security.html"
|
||||
@@ -128,7 +132,23 @@ private fun SurfaceSecurityRow(surface: SurfaceSecurity) {
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SurfaceSecurityGlyph(kind = surface.kind, modifier = Modifier.size(16.dp))
|
||||
if (surface.useState == SurfaceUseState.Unavailable) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.LinkOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
} else if (surface.useState == SurfaceUseState.Available) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Shield,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
} else {
|
||||
SurfaceSecurityGlyph(kind = surface.kind, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = surface.label,
|
||||
@@ -142,7 +162,17 @@ private fun SurfaceSecurityRow(surface: SurfaceSecurity) {
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = surface.mechanism,
|
||||
text = when (surface.useState) {
|
||||
SurfaceUseState.InUse -> surface.mechanism
|
||||
SurfaceUseState.Available -> stringResource(
|
||||
R.string.security_sheet_available_mechanism,
|
||||
surface.mechanism,
|
||||
)
|
||||
SurfaceUseState.Unavailable -> stringResource(
|
||||
R.string.security_sheet_unavailable_mechanism,
|
||||
surface.mechanism,
|
||||
)
|
||||
},
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ import com.hermesandroid.relay.data.Connection
|
||||
|
||||
/**
|
||||
* Bottom sheet chooser for switching between Hermes connections. Driven by
|
||||
* the top-bar [ConnectionChip] tap and the Settings → Connections row.
|
||||
* the top-bar [ConnectionChip] tap and the Settings → Gateways row.
|
||||
* Each row is a radio selection — tapping commits immediately and dismisses
|
||||
* the sheet so the swap kicks off before the user's finger is off the screen.
|
||||
*
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,8 @@ 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.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
@@ -56,15 +58,16 @@ import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.SurfaceSecurityKind
|
||||
import com.hermesandroid.relay.data.classifySurfaceSecurity
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.data.hasSecureProxy
|
||||
import com.hermesandroid.relay.data.secureLinkCoversAllServices
|
||||
import com.hermesandroid.relay.data.secureLinkServices
|
||||
import com.hermesandroid.relay.data.isEncryptedOverlayRoute
|
||||
import com.hermesandroid.relay.data.isKnownRole
|
||||
import com.hermesandroid.relay.data.isTlsUrl
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.network.shared.EndpointSurface
|
||||
import com.hermesandroid.relay.network.shared.RouteProbeOutcome
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -100,7 +103,7 @@ fun EndpointsCard(
|
||||
/**
|
||||
* Live transient override installed by "Use now" (or by preference
|
||||
* restoration — equal to [preferredRole] in that case). Drives the
|
||||
* automatic / preferred / manual annotation on the Current line.
|
||||
* automatic / preferred / manual annotation on the selected-candidate line.
|
||||
*/
|
||||
manualOverrideRole: String?,
|
||||
onUseNow: (EndpointCandidate) -> Unit,
|
||||
@@ -117,6 +120,7 @@ fun EndpointsCard(
|
||||
* resolver's cache-key scheme.
|
||||
*/
|
||||
outcomeFor: (EndpointCandidate) -> RouteProbeOutcome? = { null },
|
||||
surfaceOutcomeFor: (EndpointCandidate, EndpointSurface) -> RouteProbeOutcome? = { _, _ -> null },
|
||||
/** Auth state applies only to the currently active Dashboard route. */
|
||||
dashboardAuthenticated: Boolean? = null,
|
||||
dashboardSignInRequired: Boolean = false,
|
||||
@@ -133,11 +137,11 @@ fun EndpointsCard(
|
||||
// Pre-resolve strings
|
||||
val noRoutesStoredText = stringResource(R.string.endpoints_no_routes_stored)
|
||||
val addRouteText = stringResource(R.string.endpoints_add_route)
|
||||
val resolvingText = stringResource(R.string.endpoints_resolving)
|
||||
val manualUntilDisconnectText = stringResource(R.string.endpoints_manual_until_disconnect)
|
||||
val preferredText = stringResource(R.string.endpoints_preferred)
|
||||
val automaticText = stringResource(R.string.endpoints_automatic)
|
||||
val currentRouteText = stringResource(R.string.endpoints_current_route)
|
||||
val noActiveFallbackText = stringResource(R.string.endpoints_no_active_fallback)
|
||||
|
||||
if (endpoints.isEmpty()) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
@@ -166,18 +170,41 @@ fun EndpointsCard(
|
||||
val stopPreferringText = stringResource(R.string.endpoints_stop_preferring)
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = currentRouteText.format(
|
||||
activeEndpoint?.displayLabel() ?: resolvingText,
|
||||
when {
|
||||
manualSwitchActive -> manualUntilDisconnectText
|
||||
manualOverrideRole != null -> preferredText
|
||||
else -> automaticText
|
||||
}
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
val activeOutcome = activeEndpoint?.let(outcomeFor)
|
||||
if (activeEndpoint == null) {
|
||||
Text(
|
||||
text = noActiveFallbackText,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = currentRouteText.format(
|
||||
activeEndpoint.displayLabel(),
|
||||
when {
|
||||
manualSwitchActive -> manualUntilDisconnectText
|
||||
manualOverrideRole != null -> preferredText
|
||||
else -> automaticText
|
||||
}
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.endpoints_selection_reason,
|
||||
activeEndpoint.priority,
|
||||
when (routeReachabilityPresentation(isProbing, activeOutcome)) {
|
||||
RouteReachabilityPresentation.Checking -> stringResource(R.string.endpoints_checking)
|
||||
RouteReachabilityPresentation.Reachable -> stringResource(R.string.endpoints_reachable_now)
|
||||
RouteReachabilityPresentation.Unreachable -> stringResource(R.string.endpoints_last_check_failed)
|
||||
RouteReachabilityPresentation.NotChecked -> stringResource(R.string.endpoints_reachability_not_checked)
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
endpoints.forEachIndexed { index, candidate ->
|
||||
if (index > 0) HorizontalDivider()
|
||||
EndpointRow(
|
||||
@@ -188,6 +215,7 @@ fun EndpointsCard(
|
||||
isPreferred = preferredRole?.equals(candidate.role, ignoreCase = true) == true,
|
||||
isProbing = isProbing,
|
||||
outcome = outcomeFor(candidate),
|
||||
surfaceOutcomeFor = surfaceOutcomeFor,
|
||||
dashboardAuthenticated = dashboardAuthenticated.takeIf { activeEndpoint != null &&
|
||||
activeEndpoint.role.equals(candidate.role, ignoreCase = true) &&
|
||||
activeEndpoint.routeAuthority() == candidate.routeAuthority()
|
||||
@@ -232,6 +260,7 @@ fun EndpointsCard(
|
||||
/**
|
||||
* One row: role chip + host:port + transport hint + health chip + 3-dot menu.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun EndpointRow(
|
||||
candidate: EndpointCandidate,
|
||||
@@ -239,6 +268,7 @@ private fun EndpointRow(
|
||||
isPreferred: Boolean,
|
||||
isProbing: Boolean = false,
|
||||
outcome: RouteProbeOutcome? = null,
|
||||
surfaceOutcomeFor: (EndpointCandidate, EndpointSurface) -> RouteProbeOutcome? = { _, _ -> null },
|
||||
dashboardAuthenticated: Boolean? = null,
|
||||
dashboardSignInRequired: Boolean = false,
|
||||
onUseNow: () -> Unit,
|
||||
@@ -276,28 +306,38 @@ private fun EndpointRow(
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = candidate.displayLabel(),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
SurfaceSecurityGlyph(kind = candidate.routeSecurityKind())
|
||||
if (isActive) {
|
||||
ActiveChip(stringResource(R.string.endpoints_active))
|
||||
} else if (isPreferred) {
|
||||
PreferredChip(stringResource(R.string.endpoints_preferred_chip))
|
||||
} else {
|
||||
FallbackChip(stringResource(R.string.endpoints_fallback))
|
||||
Text(
|
||||
text = routeTransportLabel(candidate),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
FlowRow(
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
when {
|
||||
isActive -> ActiveChip(stringResource(R.string.endpoints_active))
|
||||
isPreferred -> PreferredChip(stringResource(R.string.endpoints_preferred_chip))
|
||||
else -> FallbackChip(stringResource(R.string.endpoints_fallback))
|
||||
}
|
||||
if (!candidate.isKnownRole()) {
|
||||
// Show the raw role for custom-VPN entries so users
|
||||
// can tell "netbird-eu" from "wireguard-home" at a
|
||||
// glance without poking into the menu.
|
||||
if (!candidate.isKnownRole() && candidate.displayName.isNullOrBlank()) {
|
||||
Text(
|
||||
text = "(${candidate.role})",
|
||||
text = candidate.role,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -307,7 +347,7 @@ private fun EndpointRow(
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
outcome == null -> Unit // never probed — say nothing
|
||||
outcome == null || outcome.isSupersededProbeFailure() -> Unit
|
||||
outcome.reachable -> Text(
|
||||
text = stringResource(R.string.endpoints_reachable),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -484,6 +524,7 @@ private fun EndpointRow(
|
||||
candidate = candidate,
|
||||
dashboardAuthenticated = dashboardAuthenticated,
|
||||
dashboardSignInRequired = dashboardSignInRequired,
|
||||
outcomeFor = { surface -> surfaceOutcomeFor(candidate, surface) },
|
||||
modifier = Modifier.padding(start = 26.dp, end = 4.dp, top = 8.dp),
|
||||
)
|
||||
}
|
||||
@@ -536,13 +577,16 @@ private fun RouteSurfaceMap(
|
||||
candidate: EndpointCandidate,
|
||||
dashboardAuthenticated: Boolean? = null,
|
||||
dashboardSignInRequired: Boolean = false,
|
||||
outcomeFor: (EndpointSurface) -> RouteProbeOutcome? = { null },
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val dashboardUrl = candidate.dashboard?.url
|
||||
?: candidate.api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
val apiUrl = candidate.api?.url
|
||||
val relayUrl = candidate.relay?.url
|
||||
|
||||
val dashboardOutcome = outcomeFor(EndpointSurface.Dashboard)
|
||||
val apiOutcome = outcomeFor(EndpointSurface.Api)
|
||||
val relayOutcome = outcomeFor(EndpointSurface.Relay)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f),
|
||||
shape = appearanceRoundedCornerShape(10.dp),
|
||||
@@ -558,26 +602,28 @@ private fun RouteSurfaceMap(
|
||||
status = when {
|
||||
dashboardSignInRequired -> stringResource(R.string.active_section_sign_in_required)
|
||||
dashboardAuthenticated == true -> stringResource(R.string.active_section_signed_in)
|
||||
dashboardUrl != null -> stringResource(R.string.active_section_configured)
|
||||
else -> stringResource(R.string.active_section_not_configured)
|
||||
else -> routeSurfaceRuntimeStatus(dashboardUrl, dashboardOutcome)
|
||||
},
|
||||
warning = dashboardSignInRequired,
|
||||
warning = dashboardSignInRequired || dashboardOutcome.isDefinitiveFailure(),
|
||||
security = routeSurfaceSecurityPresentation(
|
||||
candidate,
|
||||
EndpointSurface.Dashboard,
|
||||
dashboardUrl,
|
||||
),
|
||||
)
|
||||
RouteSurfaceRow(
|
||||
label = stringResource(R.string.active_section_api_server),
|
||||
url = apiUrl,
|
||||
status = stringResource(
|
||||
if (apiUrl != null) R.string.active_section_configured
|
||||
else R.string.active_section_not_configured,
|
||||
),
|
||||
status = routeSurfaceRuntimeStatus(apiUrl, apiOutcome),
|
||||
warning = apiOutcome.isDefinitiveFailure(),
|
||||
security = routeSurfaceSecurityPresentation(candidate, EndpointSurface.Api, apiUrl),
|
||||
)
|
||||
RouteSurfaceRow(
|
||||
label = stringResource(R.string.active_section_relay),
|
||||
url = relayUrl,
|
||||
status = stringResource(
|
||||
if (relayUrl != null) R.string.active_section_configured
|
||||
else R.string.active_section_not_configured,
|
||||
),
|
||||
status = routeSurfaceRuntimeStatus(relayUrl, relayOutcome),
|
||||
warning = relayOutcome.isDefinitiveFailure(),
|
||||
security = routeSurfaceSecurityPresentation(candidate, EndpointSurface.Relay, relayUrl),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -589,6 +635,7 @@ private fun RouteSurfaceRow(
|
||||
url: String?,
|
||||
status: String,
|
||||
warning: Boolean = false,
|
||||
security: RouteSurfaceSecurityPresentation = RouteSurfaceSecurityPresentation.NotConfigured,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -609,6 +656,31 @@ private fun RouteSurfaceRow(
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (security != RouteSurfaceSecurityPresentation.NotConfigured) {
|
||||
Text(
|
||||
text = when (security) {
|
||||
RouteSurfaceSecurityPresentation.ApplicationTls ->
|
||||
stringResource(R.string.endpoints_security_application_tls)
|
||||
RouteSurfaceSecurityPresentation.TailscaleOverlay ->
|
||||
stringResource(R.string.endpoints_security_tailscale_overlay)
|
||||
RouteSurfaceSecurityPresentation.WireGuardOverlay ->
|
||||
stringResource(R.string.endpoints_security_wireguard_overlay)
|
||||
RouteSurfaceSecurityPresentation.SecureLink ->
|
||||
stringResource(R.string.endpoints_security_secure_link)
|
||||
RouteSurfaceSecurityPresentation.PrivatePlain ->
|
||||
stringResource(R.string.endpoints_security_private_plain)
|
||||
RouteSurfaceSecurityPresentation.PublicPlain ->
|
||||
stringResource(R.string.endpoints_security_public_plain)
|
||||
RouteSurfaceSecurityPresentation.NotConfigured -> ""
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (security == RouteSurfaceSecurityPresentation.PublicPlain) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
text = status,
|
||||
@@ -700,26 +772,241 @@ private fun FallbackChip(label: String) {
|
||||
|
||||
/**
|
||||
* Role → Material icon. Known roles get their canonical glyph; anything
|
||||
* else falls through to [Icons.Filled.Shield] (generic "Custom VPN").
|
||||
* else falls through to [Icons.Filled.Shield] (generic custom route).
|
||||
*/
|
||||
private fun roleIcon(role: String): ImageVector = when (role.lowercase()) {
|
||||
"lan" -> Icons.Filled.Lan
|
||||
"tailscale" -> Icons.Filled.VpnKey
|
||||
"public" -> Icons.Filled.Public
|
||||
"dashboard", "authenticated_dashboard", "https" -> Icons.Filled.Public
|
||||
else -> Icons.Filled.Shield
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun routeSurfaceRuntimeStatus(
|
||||
url: String?,
|
||||
outcome: RouteProbeOutcome?,
|
||||
): String = when (routeSurfaceProbePresentation(url, outcome)) {
|
||||
RouteSurfaceProbePresentation.NotConfigured ->
|
||||
stringResource(R.string.active_section_not_configured)
|
||||
RouteSurfaceProbePresentation.NotChecked ->
|
||||
stringResource(R.string.active_section_not_checked_separately)
|
||||
RouteSurfaceProbePresentation.Reachable -> stringResource(R.string.endpoints_reachable)
|
||||
RouteSurfaceProbePresentation.Unreachable -> stringResource(
|
||||
R.string.endpoints_unreachable,
|
||||
outcome?.detail ?: stringResource(R.string.endpoints_unreachable_no_detail),
|
||||
)
|
||||
}
|
||||
|
||||
internal enum class RouteSurfaceProbePresentation {
|
||||
NotConfigured,
|
||||
NotChecked,
|
||||
Reachable,
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
internal enum class RouteReachabilityPresentation {
|
||||
Checking,
|
||||
Reachable,
|
||||
Unreachable,
|
||||
NotChecked,
|
||||
}
|
||||
|
||||
/** Honest selection context: a selected route is not proof of a fresh probe. */
|
||||
internal fun routeReachabilityPresentation(
|
||||
isProbing: Boolean,
|
||||
outcome: RouteProbeOutcome?,
|
||||
): RouteReachabilityPresentation = when {
|
||||
isProbing -> RouteReachabilityPresentation.Checking
|
||||
outcome == null || outcome.isSupersededProbeFailure() -> RouteReachabilityPresentation.NotChecked
|
||||
outcome.reachable -> RouteReachabilityPresentation.Reachable
|
||||
else -> RouteReachabilityPresentation.Unreachable
|
||||
}
|
||||
|
||||
internal enum class RouteSurfaceSecurityPresentation {
|
||||
ApplicationTls,
|
||||
TailscaleOverlay,
|
||||
WireGuardOverlay,
|
||||
SecureLink,
|
||||
PrivatePlain,
|
||||
PublicPlain,
|
||||
NotConfigured,
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-route security classification for the picker glyph. Keyed on the
|
||||
* candidate's own scheme + role (no device-level Tailscale detection needed —
|
||||
* a `tailscale`/`plugin_proxy` role is encrypted regardless), so each row can
|
||||
* be classified independently before it's the active route.
|
||||
* Separates application TLS from private overlay encryption. An HTTP/WS
|
||||
* Tailscale route is WireGuard-encrypted in transit, but it does not have
|
||||
* application-layer TLS; public plaintext remains an error.
|
||||
*/
|
||||
private fun EndpointCandidate.routeSecurityKind(): SurfaceSecurityKind = when {
|
||||
hasSecureProxy() -> SurfaceSecurityKind.Tls
|
||||
isTlsUrl(primaryRouteUrl().orEmpty()) -> SurfaceSecurityKind.Tls
|
||||
isEncryptedOverlayRoute(isTailscaleDetected = false) -> SurfaceSecurityKind.Overlay
|
||||
else -> SurfaceSecurityKind.Plain
|
||||
internal fun routeSurfaceSecurityPresentation(
|
||||
candidate: EndpointCandidate,
|
||||
surface: EndpointSurface,
|
||||
url: String?,
|
||||
): RouteSurfaceSecurityPresentation {
|
||||
if (url.isNullOrBlank()) return RouteSurfaceSecurityPresentation.NotConfigured
|
||||
val label = when (surface) {
|
||||
EndpointSurface.Standard,
|
||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||
EndpointSurface.Api -> "API fallback"
|
||||
EndpointSurface.Relay -> "Relay tools"
|
||||
}
|
||||
val securityVerdict = classifySurfaceSecurity(
|
||||
label = label,
|
||||
url = url,
|
||||
activeEndpoint = candidate,
|
||||
isTailscaleDetected = false,
|
||||
)
|
||||
val role = candidate.role.trim().lowercase()
|
||||
return when (securityVerdict.kind) {
|
||||
SurfaceSecurityKind.Tls -> when (securityVerdict.mechanism) {
|
||||
"Hermes Secure Link", "Hermes Reach" -> RouteSurfaceSecurityPresentation.SecureLink
|
||||
else -> RouteSurfaceSecurityPresentation.ApplicationTls
|
||||
}
|
||||
SurfaceSecurityKind.Overlay -> when (securityVerdict.mechanism) {
|
||||
"Tailscale" -> RouteSurfaceSecurityPresentation.TailscaleOverlay
|
||||
else -> RouteSurfaceSecurityPresentation.WireGuardOverlay
|
||||
}
|
||||
SurfaceSecurityKind.Plain -> if (role == "public" || role == "https") {
|
||||
RouteSurfaceSecurityPresentation.PublicPlain
|
||||
} else {
|
||||
RouteSurfaceSecurityPresentation.PrivatePlain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun routeSurfaceProbePresentation(
|
||||
url: String?,
|
||||
outcome: RouteProbeOutcome?,
|
||||
): RouteSurfaceProbePresentation = when {
|
||||
url == null -> RouteSurfaceProbePresentation.NotConfigured
|
||||
outcome == null || outcome.isSupersededProbeFailure() -> RouteSurfaceProbePresentation.NotChecked
|
||||
outcome.reachable -> RouteSurfaceProbePresentation.Reachable
|
||||
else -> RouteSurfaceProbePresentation.Unreachable
|
||||
}
|
||||
|
||||
private fun RouteProbeOutcome?.isDefinitiveFailure(): Boolean =
|
||||
this != null && !reachable && !isSupersededProbeFailure()
|
||||
|
||||
/** A cancelled shared probe is unknown/checking state, never proof of outage. */
|
||||
internal fun RouteProbeOutcome.isSupersededProbeFailure(): Boolean {
|
||||
if (reachable) return false
|
||||
val value = detail.orEmpty().lowercase()
|
||||
return value.contains("interruptedioexception") ||
|
||||
value.contains("canceled") ||
|
||||
value.contains("cancelled") ||
|
||||
value.contains("superseded")
|
||||
}
|
||||
|
||||
/** Explicit HTTP/HTTPS route identity; security warnings stay surface-scoped. */
|
||||
internal fun routeTransportLabel(candidate: EndpointCandidate): String {
|
||||
val routeUrl = candidate.dashboard?.url
|
||||
?: candidate.api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
?: candidate.primaryRouteUrl()
|
||||
return when (runCatching { URI(routeUrl.orEmpty()).scheme?.lowercase() }.getOrNull()) {
|
||||
"https" -> "HTTPS"
|
||||
"http" -> "HTTP"
|
||||
"wss" -> "WSS"
|
||||
"ws" -> "WS"
|
||||
else -> "—"
|
||||
}
|
||||
}
|
||||
|
||||
/** Plain transport warnings belong to Relay, not to an allowed HTTP Gateway. */
|
||||
internal fun EndpointCandidate.hasPlainRelayTransport(): Boolean {
|
||||
val relayScheme = runCatching { URI(relay?.url.orEmpty()).scheme?.lowercase() }.getOrNull()
|
||||
if (relayScheme !in setOf("ws", "http")) return false
|
||||
val routeHint = security.orEmpty().lowercase()
|
||||
return role.lowercase() != "tailscale" &&
|
||||
!routeHint.contains("tailscale") &&
|
||||
!routeHint.contains("wireguard")
|
||||
}
|
||||
|
||||
/** First-class editor for the Dashboard/Gateway origin used by Manage, chat, sessions, and OIDC. */
|
||||
@Composable
|
||||
fun DashboardAddressEditorDialog(
|
||||
initialUrl: String,
|
||||
onSave: (dashboardUrl: String, onResult: (String?) -> Unit) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var url by remember(initialUrl) { mutableStateOf(initialUrl) }
|
||||
var errorText by remember { mutableStateOf<String?>(null) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
val normalized = remember(url) {
|
||||
url.takeIf { it.isNotBlank() }?.let(Connection::normalizeDashboardUrlInput).orEmpty()
|
||||
}
|
||||
val valid = remember(normalized) { isValidDashboardEditorAddress(normalized) }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!saving) onDismiss() },
|
||||
title = { Text(stringResource(R.string.dashboard_address_editor_title)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_address_editor_body),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = url,
|
||||
onValueChange = {
|
||||
url = it
|
||||
errorText = null
|
||||
},
|
||||
label = { Text(stringResource(R.string.dashboard_address_label)) },
|
||||
placeholder = { Text(stringResource(R.string.dashboard_address_placeholder)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
isError = errorText != null,
|
||||
supportingText = {
|
||||
Text(
|
||||
text = errorText ?: if (url.isBlank()) {
|
||||
stringResource(R.string.dashboard_address_required)
|
||||
} else {
|
||||
stringResource(R.string.dashboard_address_preview, normalized)
|
||||
},
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_address_oidc_hint),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
enabled = valid && !saving && normalized != initialUrl.trim().trimEnd('/'),
|
||||
onClick = {
|
||||
saving = true
|
||||
onSave(normalized) { error ->
|
||||
saving = false
|
||||
if (error == null) onDismiss() else errorText = error
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
if (saving) stringResource(R.string.endpoints_saving)
|
||||
else stringResource(R.string.endpoints_save),
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss, enabled = !saving) {
|
||||
Text(stringResource(R.string.endpoints_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun isValidDashboardEditorAddress(address: String): Boolean {
|
||||
val parsed = runCatching { URI(address) }.getOrNull() ?: return false
|
||||
return parsed.scheme?.lowercase() in setOf("http", "https") &&
|
||||
!parsed.host.isNullOrBlank() &&
|
||||
parsed.userInfo == null &&
|
||||
parsed.query == null &&
|
||||
parsed.fragment == null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -737,6 +1024,7 @@ private fun EndpointCandidate.routeSecurityKind(): SurfaceSecurityKind = when {
|
||||
* receives a user-facing error string to render inline, or null on
|
||||
* success (the dialog then closes itself).
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun RouteEditorDialog(
|
||||
original: EndpointCandidate?,
|
||||
@@ -745,11 +1033,11 @@ fun RouteEditorDialog(
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val uriHandler = LocalUriHandler.current
|
||||
val knownRoles = listOf("tailscale", "public")
|
||||
val knownRoles = GATEWAY_ROUTE_EDITOR_ROLES
|
||||
var selectedRole by remember {
|
||||
mutableStateOf(
|
||||
when (original?.role?.lowercase()) {
|
||||
null -> "tailscale"
|
||||
null -> "lan"
|
||||
in knownRoles -> original.role.lowercase()
|
||||
else -> CUSTOM_ROLE
|
||||
},
|
||||
@@ -760,7 +1048,7 @@ fun RouteEditorDialog(
|
||||
original?.role?.takeIf { it.lowercase() !in knownRoles }.orEmpty(),
|
||||
)
|
||||
}
|
||||
var url by remember(original) { mutableStateOf(original?.primaryRouteUrl().orEmpty()) }
|
||||
var url by remember(original) { mutableStateOf(routeEditorInitialGatewayUrl(original)) }
|
||||
var errorText by remember { mutableStateOf<String?>(null) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
|
||||
@@ -784,7 +1072,12 @@ fun RouteEditorDialog(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(
|
||||
selected = selectedRole == "lan",
|
||||
onClick = { selectedRole = "lan" },
|
||||
label = { Text(stringResource(R.string.cw_role_lan)) },
|
||||
)
|
||||
FilterChip(
|
||||
selected = selectedRole == "tailscale",
|
||||
onClick = { selectedRole = "tailscale" },
|
||||
@@ -908,3 +1201,6 @@ private const val REMOTE_ACCESS_DOCS_URL =
|
||||
"https://hermes-relay.dev/docs/guide/remote-access"
|
||||
|
||||
private const val CUSTOM_ROLE = "__custom__"
|
||||
internal val GATEWAY_ROUTE_EDITOR_ROLES = listOf("lan", "tailscale", "public")
|
||||
internal fun routeEditorInitialGatewayUrl(original: EndpointCandidate?): String =
|
||||
original?.gatewayRouteUrl().orEmpty()
|
||||
|
||||
+138
-22
@@ -20,13 +20,17 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.PauseCircleOutline
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -39,9 +43,13 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -49,6 +57,7 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.heading
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
@@ -56,6 +65,10 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.network.upstream.GatewayProcess
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivity
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivityPhase
|
||||
import com.hermesandroid.relay.viewmodel.SubagentChildPreview
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Composer-adjacent summary of upstream Hermes processes for the active chat.
|
||||
@@ -63,8 +76,10 @@ import com.hermesandroid.relay.network.upstream.GatewayProcess
|
||||
* in the global session/navigation drawer.
|
||||
*/
|
||||
@Composable
|
||||
fun GatewayBackgroundProcessStrip(
|
||||
internal fun GatewayBackgroundProcessStrip(
|
||||
processes: List<GatewayProcess>,
|
||||
subagentActivities: List<SubagentActivity>,
|
||||
subagentPreviewVisibility: SubagentPreviewVisibility,
|
||||
loading: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -72,16 +87,26 @@ fun GatewayBackgroundProcessStrip(
|
||||
// Initial/switch refreshes are silent. The strip appears only after the
|
||||
// session actually owns a process, avoiding a transient "Checking" row on
|
||||
// every ordinary chat open.
|
||||
if (processes.isEmpty()) return
|
||||
val visibleActivities = subagentActivities.takeIf { subagentPreviewVisibility.showLifecycle }.orEmpty()
|
||||
if (processes.isEmpty() && visibleActivities.isEmpty()) return
|
||||
|
||||
val running = processes.count { it.isRunning }
|
||||
val runningAgents = visibleActivities.count { !it.isTerminal }
|
||||
val failed = processes.count { !it.isRunning && (it.exitCode ?: 0) != 0 }
|
||||
val displayedCount = if (running > 0) running else processes.size
|
||||
val failedAgents = visibleActivities.count { it.phase == SubagentActivityPhase.FAILED }
|
||||
val interruptedAgents = visibleActivities.count {
|
||||
it.phase == SubagentActivityPhase.INTERRUPTED ||
|
||||
it.phase == SubagentActivityPhase.ENDED_WITH_PARENT
|
||||
}
|
||||
val failureCount = failed + failedAgents
|
||||
val status = when {
|
||||
runningAgents > 0 -> stringResource(R.string.subagent_lane_running_count, runningAgents)
|
||||
running > 0 -> "$running ${stringResource(R.string.bg_processes_running)}"
|
||||
failed > 0 -> "$failed ${stringResource(R.string.task_status_failed)}"
|
||||
failureCount > 0 -> "$failureCount ${stringResource(R.string.task_status_failed)}"
|
||||
interruptedAgents > 0 -> stringResource(R.string.agent_activity_status_interrupted)
|
||||
else -> stringResource(R.string.task_status_complete)
|
||||
}
|
||||
val openDescription = stringResource(R.string.current_chat_activity_open)
|
||||
|
||||
Surface(
|
||||
modifier = modifier
|
||||
@@ -90,11 +115,11 @@ fun GatewayBackgroundProcessStrip(
|
||||
.heightIn(min = 48.dp)
|
||||
.semantics {
|
||||
contentDescription =
|
||||
"Background processes, $status. Open current chat activity."
|
||||
"$openDescription, $status"
|
||||
stateDescription = status
|
||||
}
|
||||
.clickable(
|
||||
onClickLabel = stringResource(R.string.bg_processes_open),
|
||||
onClickLabel = openDescription,
|
||||
onClick = onClick,
|
||||
),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
@@ -105,37 +130,41 @@ fun GatewayBackgroundProcessStrip(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (running > 0 || loading) {
|
||||
if (running > 0 || runningAgents > 0 || loading) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = if (failed > 0) Icons.Filled.ErrorOutline else Icons.Filled.CheckCircle,
|
||||
imageVector = when {
|
||||
failureCount > 0 -> Icons.Filled.ErrorOutline
|
||||
interruptedAgents > 0 -> Icons.Filled.PauseCircleOutline
|
||||
else -> Icons.Filled.CheckCircle
|
||||
},
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(17.dp),
|
||||
tint = if (failed > 0) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primary
|
||||
tint = when {
|
||||
failureCount > 0 -> MaterialTheme.colorScheme.error
|
||||
interruptedAgents > 0 -> MaterialTheme.colorScheme.tertiary
|
||||
else -> MaterialTheme.colorScheme.primary
|
||||
},
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(9.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.background_process_count, displayedCount),
|
||||
text = stringResource(R.string.current_chat_activity_title),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
text = status,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = if (failed > 0 && running == 0) {
|
||||
color = if (failureCount > 0 && running == 0) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ExpandLess,
|
||||
imageVector = Icons.Filled.Visibility,
|
||||
contentDescription = null,
|
||||
modifier = Modifier
|
||||
.padding(start = 6.dp)
|
||||
@@ -149,18 +178,56 @@ fun GatewayBackgroundProcessStrip(
|
||||
/** Mobile analogue of Hermes Desktop's composer process stack + terminal viewer. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GatewayBackgroundProcessSheet(
|
||||
internal fun GatewayBackgroundProcessSheet(
|
||||
processes: List<GatewayProcess>,
|
||||
subagentActivities: List<SubagentActivity>,
|
||||
subagentChildPreview: SubagentChildPreview?,
|
||||
subagentPreviewVisibility: SubagentPreviewVisibility,
|
||||
loading: Boolean,
|
||||
stoppingProcessIds: Set<String>,
|
||||
onRefresh: () -> Unit,
|
||||
onStop: (String) -> Unit,
|
||||
onDismissProcess: (String) -> Unit,
|
||||
onOpenSubagentChild: (String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
|
||||
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
|
||||
val scope = rememberCoroutineScope()
|
||||
var expandedAgentKeys by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
val running = processes.filter { it.isRunning }
|
||||
val recent = processes.filterNot { it.isRunning }
|
||||
val visibleActivities = subagentActivities.takeIf { subagentPreviewVisibility.showLifecycle }.orEmpty()
|
||||
val followTarget = subagentActivityFollowTarget(
|
||||
visibleActivities,
|
||||
expandedAgentKeys,
|
||||
subagentPreviewVisibility,
|
||||
subagentChildPreview,
|
||||
)
|
||||
val activityRevision = visibleActivities.sumOf { it.revision } +
|
||||
subagentChildPreview?.messages.orEmpty().sumOf { message ->
|
||||
message.content.length + message.thinkingContent.length +
|
||||
message.toolCalls.sumOf { (it.args?.length ?: 0) + it.name.length }
|
||||
}
|
||||
val nearActivityTail by remember(followTarget, listState) {
|
||||
derivedStateOf {
|
||||
val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
|
||||
followTarget >= 0 && last in maxOf(0, followTarget - 2)..followTarget
|
||||
}
|
||||
}
|
||||
var followAgentTail by remember { mutableStateOf(true) }
|
||||
|
||||
LaunchedEffect(listState, followTarget) {
|
||||
snapshotFlow { listState.isScrollInProgress to nearActivityTail }.collect { (scrolling, nearTail) ->
|
||||
if (scrolling) followAgentTail = nearTail
|
||||
else if (nearTail) followAgentTail = true
|
||||
}
|
||||
}
|
||||
LaunchedEffect(activityRevision, followTarget) {
|
||||
if (followAgentTail && followTarget >= 0) {
|
||||
listState.scrollToItem(followTarget)
|
||||
}
|
||||
}
|
||||
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -178,23 +245,48 @@ fun GatewayBackgroundProcessSheet(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.background_processes_title), style = MaterialTheme.typography.titleLarge)
|
||||
Text(
|
||||
stringResource(R.string.background_processes_subtitle),
|
||||
stringResource(R.string.current_chat_activity_title),
|
||||
modifier = Modifier.semantics { heading() },
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.current_chat_activity_subtitle),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onRefresh, enabled = !loading) {
|
||||
if (processes.isNotEmpty()) IconButton(onClick = onRefresh, enabled = !loading) {
|
||||
if (loading) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.background_processes_refresh_a11y))
|
||||
}
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.current_chat_activity_close),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!followAgentTail && followTarget >= 0) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(onClick = {
|
||||
followAgentTail = true
|
||||
scope.launch { listState.animateScrollToItem(followTarget) }
|
||||
}) {
|
||||
Text(stringResource(R.string.current_chat_activity_latest))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (processes.isEmpty() && !loading) {
|
||||
if (processes.isEmpty() && visibleActivities.isEmpty() && !loading) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -202,23 +294,47 @@ fun GatewayBackgroundProcessSheet(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Terminal,
|
||||
Icons.Filled.AccountTree,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(30.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.bg_processes_empty),
|
||||
stringResource(R.string.current_chat_activity_empty),
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp),
|
||||
) {
|
||||
subagentActivityItems(
|
||||
activities = visibleActivities,
|
||||
expandedKeys = expandedAgentKeys,
|
||||
visibility = subagentPreviewVisibility,
|
||||
childPreview = subagentChildPreview,
|
||||
onToggle = { key ->
|
||||
expandedAgentKeys = if (key in expandedAgentKeys) {
|
||||
expandedAgentKeys - key
|
||||
} else {
|
||||
expandedAgentKeys + key
|
||||
}
|
||||
},
|
||||
onOpenChild = onOpenSubagentChild,
|
||||
)
|
||||
if (visibleActivities.isNotEmpty() && processes.isNotEmpty()) {
|
||||
item { HorizontalDivider(modifier = Modifier.padding(vertical = 6.dp)) }
|
||||
item {
|
||||
ProcessSectionLabel(
|
||||
stringResource(R.string.background_processes_title),
|
||||
processes.size,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (running.isNotEmpty()) {
|
||||
item { ProcessSectionLabel(stringResource(R.string.bg_processes_running), running.size) }
|
||||
items(running, key = { it.id }) { process ->
|
||||
|
||||
@@ -14,7 +14,6 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
@@ -25,6 +24,7 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
@@ -71,6 +71,7 @@ import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
@@ -172,26 +173,26 @@ fun HermesCardBubble(
|
||||
),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(IntrinsicSize.Min),
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxWidth()) {
|
||||
// Accent stripe — runs full card height so tall cards keep the
|
||||
// color tie. Using the SAME tertiary accent strategy as the
|
||||
// voice/phone-action bubble marker in MessageBubble.kt so the
|
||||
// visual language stays consistent.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(3.dp)
|
||||
.fillMaxHeight()
|
||||
.background(accentColor),
|
||||
)
|
||||
modifier = Modifier.matchParentSize(),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(3.dp)
|
||||
.fillMaxHeight()
|
||||
.background(accentColor),
|
||||
)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
.padding(start = 15.dp, top = 12.dp, end = 12.dp, bottom = 12.dp),
|
||||
) {
|
||||
// Header
|
||||
Row(
|
||||
@@ -426,6 +427,19 @@ private fun CardInputSlot(
|
||||
input.kind != HermesCardInput.Kinds.CONFIRM)
|
||||
)
|
||||
|
||||
val submitFreeText = {
|
||||
val customAnswer = answerText.trim()
|
||||
if (customAnswer.isNotEmpty()) {
|
||||
onSubmit(
|
||||
if (isMultiSelect) {
|
||||
encodeClarifyMultiSelectAnswer(selectedChoices + customAnswer)
|
||||
} else {
|
||||
customAnswer
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
// Choice chips
|
||||
if (input.choices.isNotEmpty()) {
|
||||
@@ -515,11 +529,16 @@ private fun CardInputSlot(
|
||||
InlineAnswerField(
|
||||
value = answerText,
|
||||
onValueChange = { answerText = it },
|
||||
placeholder = stringResource(
|
||||
if (input.choices.isNotEmpty()) R.string.card_other_answer_placeholder
|
||||
else R.string.card_answer_placeholder,
|
||||
),
|
||||
onSubmit = submitFreeText,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!isMultiSelect) {
|
||||
IconButton(
|
||||
onClick = { onSubmit(answerText.trim()) },
|
||||
onClick = submitFreeText,
|
||||
enabled = answerText.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
@@ -593,6 +612,8 @@ private fun CardInputSlot(
|
||||
private fun InlineAnswerField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
placeholder: String,
|
||||
onSubmit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val shape = appearanceRoundedCornerShape(16.dp)
|
||||
@@ -605,7 +626,7 @@ private fun InlineAnswerField(
|
||||
) {
|
||||
if (value.isEmpty()) {
|
||||
Text(
|
||||
text = stringResource(R.string.card_answer_placeholder),
|
||||
text = placeholder,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
|
||||
)
|
||||
@@ -617,8 +638,12 @@ private fun InlineAnswerField(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||
keyboardActions = KeyboardActions(onSend = { onSubmit() }),
|
||||
maxLines = 3,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics { contentDescription = placeholder },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,8 +81,11 @@ import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import java.net.URI
|
||||
@@ -277,23 +280,52 @@ private val json = Json {
|
||||
*/
|
||||
fun parseHermesPairingQr(raw: String): HermesPairingPayload? {
|
||||
val trimmed = raw.trim()
|
||||
return parseHermesRelayQr(trimmed)
|
||||
?: parseGenericApiJsonQr(trimmed)
|
||||
parseHermesRelayQr(trimmed)?.let { return it }
|
||||
// Structured Hermes payloads fail closed. Falling through to the generic
|
||||
// parser would silently discard Relay credentials and route candidates.
|
||||
if (looksLikeStructuredHermesPayload(trimmed)) return null
|
||||
return parseGenericApiJsonQr(trimmed)
|
||||
?: parseGenericDashboardJsonQr(trimmed)
|
||||
?: parseGenericApiUrlQr(trimmed)
|
||||
}
|
||||
|
||||
private fun looksLikeStructuredHermesPayload(raw: String): Boolean = runCatching {
|
||||
val obj = json.decodeFromString<JsonObject>(raw)
|
||||
obj.keys.any { it in setOf("hermes", "relay", "endpoints", "sig") }
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun normalizeIntegralDuration(element: JsonElement): JsonElement {
|
||||
val numeric = (element as? JsonPrimitive)?.doubleOrNull ?: return element
|
||||
if (!numeric.isFinite() || numeric < 0 || numeric % 1.0 != 0.0) return element
|
||||
if (numeric > Long.MAX_VALUE.toDouble()) return element
|
||||
return JsonPrimitive(numeric.toLong())
|
||||
}
|
||||
|
||||
/** Accept older Relay emitters that wrote whole seconds as JSON floats. */
|
||||
private fun normalizeRelayDurationFields(obj: JsonObject): JsonObject {
|
||||
val relay = obj["relay"] as? JsonObject ?: return obj
|
||||
val normalizedRelay = relay.toMutableMap()
|
||||
relay["ttl_seconds"]?.let {
|
||||
normalizedRelay["ttl_seconds"] = normalizeIntegralDuration(it)
|
||||
}
|
||||
(relay["grants"] as? JsonObject)?.let { grants ->
|
||||
normalizedRelay["grants"] = JsonObject(
|
||||
grants.mapValues { (_, duration) -> normalizeIntegralDuration(duration) },
|
||||
)
|
||||
}
|
||||
return JsonObject(obj.toMutableMap().apply {
|
||||
put("relay", JsonObject(normalizedRelay))
|
||||
})
|
||||
}
|
||||
|
||||
private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
|
||||
return try {
|
||||
// Quick check: must contain a `host` field and be valid JSON. We no
|
||||
// longer reject based on the `hermes` version int — future v4+ QRs
|
||||
// should still parse so wire-format growth does not require an app
|
||||
// release for every compatible payload version.
|
||||
val obj = json.decodeFromString<JsonObject>(raw)
|
||||
// Future compatible versions remain accepted. The legacy top-level
|
||||
// API host is optional when Dashboard plus Relay identity is present.
|
||||
val obj = normalizeRelayDurationFields(json.decodeFromString<JsonObject>(raw))
|
||||
val version = obj["hermes"]?.jsonPrimitive?.intOrNull ?: 1
|
||||
if (version < 1) return null
|
||||
val decoded = json.decodeFromString<HermesPairingPayload>(raw)
|
||||
if (decoded.host.isBlank()) return null
|
||||
val decoded = json.decodeFromString<HermesPairingPayload>(obj.toString())
|
||||
val dashboardAlias = firstString(obj, "dashboardUrl")
|
||||
val decodedWithAliases =
|
||||
if (decoded.dashboardUrl.isNullOrBlank() && dashboardAlias != null) {
|
||||
@@ -301,6 +333,9 @@ private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
|
||||
} else {
|
||||
decoded
|
||||
}
|
||||
if (decodedWithAliases.host.isBlank() &&
|
||||
!decodedWithAliases.hasDashboardRelayIdentity()
|
||||
) return null
|
||||
val normalizedKey = normalizeCredentialForHeader(
|
||||
decodedWithAliases.key,
|
||||
"API credential",
|
||||
@@ -318,7 +353,13 @@ private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
|
||||
// v3+ payloads with an explicit array pass through untouched.
|
||||
if (decodedWithSafeCredential.endpoints.isNullOrEmpty()) {
|
||||
decodedWithSafeCredential.copy(
|
||||
endpoints = listOf(synthesizeLegacyEndpoint(decodedWithSafeCredential)),
|
||||
endpoints = listOf(
|
||||
if (decodedWithSafeCredential.hasApiServer) {
|
||||
synthesizeLegacyEndpoint(decodedWithSafeCredential)
|
||||
} else {
|
||||
synthesizeDashboardRelayEndpoint(decodedWithSafeCredential)
|
||||
},
|
||||
),
|
||||
)
|
||||
} else {
|
||||
decodedWithSafeCredential
|
||||
@@ -328,6 +369,30 @@ private fun parseHermesRelayQr(raw: String): HermesPairingPayload? {
|
||||
}
|
||||
}
|
||||
|
||||
private fun HermesPairingPayload.hasDashboardRelayIdentity(): Boolean {
|
||||
if (!hasUsableRelayPairing()) return false
|
||||
val uri = dashboardUrl
|
||||
?.trim()
|
||||
?.let { runCatching { URI(it) }.getOrNull() }
|
||||
?: return false
|
||||
return uri.scheme?.lowercase() in setOf("http", "https") && !uri.host.isNullOrBlank()
|
||||
}
|
||||
|
||||
private fun synthesizeDashboardRelayEndpoint(
|
||||
payload: HermesPairingPayload,
|
||||
): EndpointCandidate {
|
||||
val dashboardUrl = requireNotNull(payload.dashboardUrl).trim().trimEnd('/')
|
||||
return EndpointCandidate(
|
||||
role = Connection.inferRouteRole(dashboardUrl),
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint(dashboardUrl),
|
||||
relay = RelayEndpoint(
|
||||
url = requireNotNull(payload.relay).url,
|
||||
transportHint = payload.relay.transportHint,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseGenericApiJsonQr(raw: String): HermesPairingPayload? {
|
||||
return try {
|
||||
val obj = json.decodeFromString<JsonObject>(raw)
|
||||
|
||||
@@ -82,6 +82,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
@@ -122,6 +123,8 @@ import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
|
||||
internal enum class SessionDrawerFilter {
|
||||
All,
|
||||
@@ -196,6 +199,12 @@ internal fun resolveSessionDrawerFilter(
|
||||
else -> filter
|
||||
}
|
||||
|
||||
internal enum class SessionDrawerLoadPresentation {
|
||||
Loading,
|
||||
Unavailable,
|
||||
Content,
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SessionDrawerContent(
|
||||
sessions: List<ChatSession>,
|
||||
@@ -204,6 +213,10 @@ fun SessionDrawerContent(
|
||||
scopeSubtitle: String? = null,
|
||||
activeProfileName: String = "default",
|
||||
isLoading: Boolean = false,
|
||||
loadFailed: Boolean = false,
|
||||
isLoadingMore: Boolean = false,
|
||||
hasMore: Boolean = false,
|
||||
loadMoreFailed: Boolean = false,
|
||||
isOpen: Boolean = true,
|
||||
activityStates: Map<String, SessionActivityState> = emptyMap(),
|
||||
animationEnabled: Boolean = true,
|
||||
@@ -212,10 +225,11 @@ fun SessionDrawerContent(
|
||||
supervisedSessionActions: SupervisedSessionActions? = null,
|
||||
newChatEnabled: Boolean = true,
|
||||
onRefresh: (() -> Unit)? = null,
|
||||
onLoadMore: (() -> Unit)? = null,
|
||||
onRetryLoadMore: (() -> Unit)? = null,
|
||||
/** Opens the separate Bot Mode messenger workspace; never changes drawer filters. */
|
||||
onOpenBotMode: (() -> Unit)? = null,
|
||||
onNewChat: () -> Unit,
|
||||
onNewDefaultChat: (() -> Unit)? = null,
|
||||
onSelectSession: (String) -> Unit,
|
||||
onDeleteSession: (String) -> Unit,
|
||||
onRenameSession: (String, String) -> Unit,
|
||||
@@ -237,6 +251,8 @@ fun SessionDrawerContent(
|
||||
onNewThread: ((String) -> Unit)? = null,
|
||||
provisionalThreads: List<ProvisionalThreadRow> = emptyList(),
|
||||
onSelectProvisionalThread: ((String) -> Unit)? = null,
|
||||
/** Deletes only the local provisional inbox row; never a server session. */
|
||||
onDeleteProvisionalThread: ((String) -> Unit)? = null,
|
||||
/** Gateway sources currently hidden from the drawer (default: cron+webhook). */
|
||||
hiddenSources: Set<String> = emptySet(),
|
||||
/** Toggle a source's visibility (persisted). Null hides the source filter. */
|
||||
@@ -244,6 +260,7 @@ fun SessionDrawerContent(
|
||||
allProfilesSupported: Boolean = false,
|
||||
allProfileSessions: List<ProfileSessionRow> = emptyList(),
|
||||
allProfileSessionsLoading: Boolean = false,
|
||||
allProfileSessionsLoadFailed: Boolean = false,
|
||||
profileColors: Map<String, String> = emptyMap(),
|
||||
onProfileColorChange: ((String, String?) -> Unit)? = null,
|
||||
onRefreshAllProfiles: (() -> Unit)? = null,
|
||||
@@ -297,8 +314,10 @@ fun SessionDrawerContent(
|
||||
val activeFilter = resolveSessionDrawerFilter(filter, showThreads, effectiveArchiveSupported)
|
||||
// External gateway sources present (discord/telegram/cron/…) for the source
|
||||
// filter dropdown. Own chats (tui/api_server) + phone Threads aren't listed.
|
||||
val presentSources = sourceSessions
|
||||
.mapNotNull { it.source?.trim()?.lowercase()?.takeIf { s -> s.isNotBlank() } }
|
||||
val presentSources = (
|
||||
sourceSessions.mapNotNull { it.source?.trim()?.lowercase()?.takeIf { s -> s.isNotBlank() } } +
|
||||
hiddenSources
|
||||
)
|
||||
.distinct()
|
||||
.filter { sourceBadge(it) != null }
|
||||
.sorted()
|
||||
@@ -336,6 +355,29 @@ fun SessionDrawerContent(
|
||||
.toList()
|
||||
val visibleRows = filterAndSortSessionRows(categoryRows, viewOptions, scopedActivityStates)
|
||||
val groupedRows = groupSessionRows(visibleRows, viewOptions.grouping, scopedActivityStates)
|
||||
LaunchedEffect(
|
||||
listState,
|
||||
isOpen,
|
||||
showAllProfiles,
|
||||
hasMore,
|
||||
isLoadingMore,
|
||||
loadMoreFailed,
|
||||
visibleRows.size,
|
||||
onLoadMore,
|
||||
) {
|
||||
if (!isOpen || showAllProfiles || !hasMore || loadMoreFailed || onLoadMore == null) {
|
||||
return@LaunchedEffect
|
||||
}
|
||||
snapshotFlow {
|
||||
val layout = listState.layoutInfo
|
||||
val lastVisible = layout.visibleItemsInfo.lastOrNull()?.index ?: -1
|
||||
layout.totalItemsCount > 0 && lastVisible >= layout.totalItemsCount - 5
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
.collect { nearEnd ->
|
||||
if (nearEnd && !isLoadingMore) onLoadMore()
|
||||
}
|
||||
}
|
||||
val drawerNowMillis = rememberDrawerClock(
|
||||
isEnabled = isOpen && (
|
||||
viewOptions.showUpdated || viewOptions.grouping == SessionDrawerGrouping.Project
|
||||
@@ -535,13 +577,7 @@ fun SessionDrawerContent(
|
||||
|
||||
// New Chat button
|
||||
Button(
|
||||
onClick = {
|
||||
if (showAllProfiles) {
|
||||
onNewDefaultChat?.invoke() ?: onNewChat()
|
||||
} else {
|
||||
onNewChat()
|
||||
}
|
||||
},
|
||||
onClick = onNewChat,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = newChatEnabled,
|
||||
) {
|
||||
@@ -692,16 +728,23 @@ fun SessionDrawerContent(
|
||||
|
||||
// Crossfade the loading→content transition so the list fades in rather
|
||||
// than the spinner snapping straight to rows.
|
||||
val loadPresentation = when {
|
||||
showAllProfiles && allProfileSessionsLoading && allProfileSessions.isEmpty() ->
|
||||
SessionDrawerLoadPresentation.Loading
|
||||
!showAllProfiles && isLoading && sessions.isEmpty() ->
|
||||
SessionDrawerLoadPresentation.Loading
|
||||
showAllProfiles && allProfileSessionsLoadFailed && sourceRows.isEmpty() ->
|
||||
SessionDrawerLoadPresentation.Unavailable
|
||||
!showAllProfiles && loadFailed && sourceRows.isEmpty() ->
|
||||
SessionDrawerLoadPresentation.Unavailable
|
||||
else -> SessionDrawerLoadPresentation.Content
|
||||
}
|
||||
Crossfade(
|
||||
targetState = if (showAllProfiles) {
|
||||
allProfileSessionsLoading && allProfileSessions.isEmpty()
|
||||
} else {
|
||||
isLoading && sessions.isEmpty()
|
||||
},
|
||||
targetState = loadPresentation,
|
||||
animationSpec = tween(220),
|
||||
label = "drawerSessions",
|
||||
) { loading ->
|
||||
if (loading) {
|
||||
) { presentation ->
|
||||
if (presentation == SessionDrawerLoadPresentation.Loading) {
|
||||
// First load (or a profile switch) — show a quiet spinner instead of
|
||||
// flashing "No sessions yet" before the list arrives.
|
||||
Column(
|
||||
@@ -721,6 +764,26 @@ fun SessionDrawerContent(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else if (presentation == SessionDrawerLoadPresentation.Unavailable) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.drawer_activity_unavailable),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
val refresh = if (showAllProfiles) onRefreshAllProfiles else onRefresh
|
||||
refresh?.let {
|
||||
TextButton(onClick = it) {
|
||||
Text(stringResource(R.string.drawer_refresh_sessions))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (visibleRows.isEmpty()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -744,6 +807,28 @@ fun SessionDrawerContent(
|
||||
state = listState,
|
||||
modifier = Modifier.testTag(SESSION_DRAWER_LIST_TAG),
|
||||
) {
|
||||
if (!showAllProfiles && loadFailed && sourceRows.isNotEmpty()) {
|
||||
item(key = "sessions-stale") {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.drawer_activity_unavailable),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
onRefresh?.let { refresh ->
|
||||
TextButton(onClick = refresh) {
|
||||
Text(stringResource(R.string.drawer_refresh_sessions))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
groupedRows.forEach { group ->
|
||||
val isProjectGroup = viewOptions.grouping == SessionDrawerGrouping.Project
|
||||
val expanded = !isProjectGroup || group.key in expandedProjectGroups
|
||||
@@ -789,13 +874,17 @@ fun SessionDrawerContent(
|
||||
showTokens = viewOptions.showTokens,
|
||||
showCost = viewOptions.showCost,
|
||||
nowMillis = drawerNowMillis,
|
||||
actionsEnabled = !provisional && (
|
||||
actionsEnabled = if (provisional) {
|
||||
onDeleteProvisionalThread != null &&
|
||||
supervisedSessionActions?.delete != false
|
||||
} else {
|
||||
supervisedSessionActions == null ||
|
||||
supervisedSessionActions.pin ||
|
||||
supervisedSessionActions.rename ||
|
||||
supervisedSessionActions.delete ||
|
||||
(supervisedSessionActions.archive && archiveSupported)
|
||||
),
|
||||
},
|
||||
provisional = provisional,
|
||||
isActive = !showAllProfiles && session.sessionId == currentSessionId,
|
||||
activityState = activityState,
|
||||
animationEnabled = animationEnabled && isOpen,
|
||||
@@ -842,6 +931,32 @@ fun SessionDrawerContent(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!showAllProfiles && isLoadingMore) {
|
||||
item(key = "sessions-loading-more") {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!showAllProfiles && loadMoreFailed && onRetryLoadMore != null) {
|
||||
item(key = "sessions-load-more-retry") {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
TextButton(onClick = onRetryLoadMore) {
|
||||
Text(stringResource(R.string.chat_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -934,15 +1049,38 @@ fun SessionDrawerContent(
|
||||
// Delete confirmation dialog
|
||||
deleteDialogTarget?.let { (row, allProfiles) ->
|
||||
val session = row.session
|
||||
val provisional = session.sessionId.startsWith(PROVISIONAL_THREAD_PREFIX)
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleteDialogTarget = null },
|
||||
title = { Text(stringResource(R.string.drawer_delete_session_title)) },
|
||||
title = {
|
||||
Text(
|
||||
stringResource(
|
||||
if (provisional) {
|
||||
R.string.drawer_remove_provisional_thread_title
|
||||
} else {
|
||||
R.string.drawer_delete_session_title
|
||||
},
|
||||
),
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Text(stringResource(R.string.drawer_delete_session_prefix) + (session.title ?: stringResource(R.string.drawer_untitled)) + stringResource(R.string.drawer_delete_session_suffix))
|
||||
val title = session.title ?: stringResource(R.string.drawer_untitled)
|
||||
Text(
|
||||
if (provisional) {
|
||||
stringResource(R.string.drawer_remove_provisional_thread_message, title)
|
||||
} else {
|
||||
stringResource(R.string.drawer_delete_session_prefix) + title +
|
||||
stringResource(R.string.drawer_delete_session_suffix)
|
||||
},
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (allProfiles) {
|
||||
if (session.sessionId.startsWith(PROVISIONAL_THREAD_PREFIX)) {
|
||||
onDeleteProvisionalThread?.invoke(
|
||||
session.sessionId.removePrefix(PROVISIONAL_THREAD_PREFIX),
|
||||
)
|
||||
} else if (allProfiles) {
|
||||
onDeleteProfileSession?.invoke(row.profile, session.sessionId)
|
||||
} else {
|
||||
onDeleteSession(session.sessionId)
|
||||
@@ -1358,6 +1496,7 @@ private fun SessionItem(
|
||||
showCost: Boolean,
|
||||
nowMillis: Long,
|
||||
actionsEnabled: Boolean,
|
||||
provisional: Boolean,
|
||||
isActive: Boolean,
|
||||
activityState: SessionActivityState?,
|
||||
animationEnabled: Boolean,
|
||||
@@ -1528,7 +1667,7 @@ private fun SessionItem(
|
||||
expanded = menuOpen,
|
||||
onDismissRequest = { menuOpen = false },
|
||||
) {
|
||||
if (supervisedSessionActions?.pin != false) DropdownMenuItem(
|
||||
if (!provisional && supervisedSessionActions?.pin != false) DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
if (pinned) {
|
||||
@@ -1554,7 +1693,7 @@ private fun SessionItem(
|
||||
onTogglePinned()
|
||||
},
|
||||
)
|
||||
if (supervisedSessionActions == null) DropdownMenuItem(
|
||||
if (!provisional && supervisedSessionActions == null) DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.chat_copy_session_id)) },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Filled.ContentCopy, contentDescription = null)
|
||||
@@ -1564,7 +1703,7 @@ private fun SessionItem(
|
||||
onCopySessionId()
|
||||
},
|
||||
)
|
||||
if (supervisedSessionActions?.rename != false) DropdownMenuItem(
|
||||
if (!provisional && supervisedSessionActions?.rename != false) DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.drawer_rename)) },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Filled.Edit, contentDescription = null)
|
||||
@@ -1574,7 +1713,7 @@ private fun SessionItem(
|
||||
onRename()
|
||||
},
|
||||
)
|
||||
if (archiveSupported && supervisedSessionActions?.archive != false) {
|
||||
if (!provisional && archiveSupported && supervisedSessionActions?.archive != false) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (archived) stringResource(R.string.drawer_restore) else stringResource(R.string.drawer_archive)) },
|
||||
leadingIcon = {
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyListScope
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.HourglassTop
|
||||
import androidx.compose.material.icons.filled.PauseCircleOutline
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.viewmodel.SubagentChildPreview
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivity
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivityEvent
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivityEventKind
|
||||
import com.hermesandroid.relay.viewmodel.SubagentActivityPhase
|
||||
|
||||
internal data class SubagentPreviewVisibility(
|
||||
val showLifecycle: Boolean = true,
|
||||
val showReasoning: Boolean = true,
|
||||
val showToolNames: Boolean = true,
|
||||
val showToolDetails: Boolean = true,
|
||||
val showChildHistory: Boolean = true,
|
||||
)
|
||||
|
||||
internal fun LazyListScope.subagentActivityItems(
|
||||
activities: List<SubagentActivity>,
|
||||
expandedKeys: Set<String>,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
childPreview: SubagentChildPreview?,
|
||||
onToggle: (String) -> Unit,
|
||||
onOpenChild: (String) -> Unit,
|
||||
) {
|
||||
if (activities.isEmpty() || !visibility.showLifecycle) return
|
||||
item(key = "subagent-section") {
|
||||
Column(modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.agent_activity_section),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.agent_activity_disclosure),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
activities.forEach { activity ->
|
||||
val key = activity.stableKey
|
||||
item(key = "subagent-header-$key") {
|
||||
SubagentActivityHeader(
|
||||
activity = activity,
|
||||
expanded = key in expandedKeys,
|
||||
visibility = visibility,
|
||||
onClick = {
|
||||
if (key !in expandedKeys && visibility.showChildHistory) onOpenChild(key)
|
||||
onToggle(key)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (key in expandedKeys) {
|
||||
if (activity.truncated) {
|
||||
item(key = "subagent-truncated-$key") {
|
||||
SubagentMetaRow(stringResource(R.string.agent_activity_older_omitted))
|
||||
}
|
||||
}
|
||||
activity.events.forEach { event ->
|
||||
item(key = "subagent-event-$key-${event.sequence}") {
|
||||
SubagentEventRow(event, visibility)
|
||||
}
|
||||
}
|
||||
if (activity.partialAfterGap) {
|
||||
item(key = "subagent-gap-$key") {
|
||||
SubagentMetaRow(stringResource(R.string.agent_activity_partial))
|
||||
}
|
||||
}
|
||||
childPreview?.takeIf { visibility.showChildHistory && it.activityKey == key }?.let { preview ->
|
||||
when (preview.childWatchAvailable) {
|
||||
null -> item(key = "subagent-child-loading-$key") {
|
||||
SubagentMetaRow(stringResource(R.string.agent_activity_child_loading))
|
||||
}
|
||||
false -> item(key = "subagent-child-unavailable-$key") {
|
||||
SubagentMetaRow(
|
||||
preview.error?.takeIf(String::isNotBlank)
|
||||
?: stringResource(R.string.agent_activity_child_unavailable),
|
||||
)
|
||||
}
|
||||
true -> {
|
||||
item(key = "subagent-child-heading-$key") {
|
||||
SubagentMetaRow(
|
||||
if (preview.running) {
|
||||
stringResource(R.string.agent_activity_child_live)
|
||||
} else {
|
||||
stringResource(R.string.agent_activity_child_history)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (preview.historyTruncated) {
|
||||
item(key = "subagent-child-truncated-$key") {
|
||||
SubagentMetaRow(stringResource(R.string.agent_activity_child_truncated))
|
||||
}
|
||||
}
|
||||
preview.messages.filterNot { it.role == MessageRole.SYSTEM }.forEach { message ->
|
||||
item(key = "subagent-child-message-$key-${message.uiKey}") {
|
||||
SubagentChildMessageRow(message, visibility)
|
||||
}
|
||||
}
|
||||
preview.error?.takeIf(String::isNotBlank)?.let { error ->
|
||||
item(key = "subagent-child-error-$key") { SubagentMetaRow(error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
item(key = "subagent-child-tail-$key") {
|
||||
Spacer(Modifier.height(1.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun subagentActivityItemCount(
|
||||
activities: List<SubagentActivity>,
|
||||
expandedKeys: Set<String>,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
childPreview: SubagentChildPreview?,
|
||||
): Int {
|
||||
if (activities.isEmpty() || !visibility.showLifecycle) return 0
|
||||
return 1 + activities.sumOf { activity ->
|
||||
val expanded = activity.stableKey in expandedKeys
|
||||
val preview = childPreview?.takeIf {
|
||||
visibility.showChildHistory && it.activityKey == activity.stableKey
|
||||
}
|
||||
val previewRows = when (preview?.childWatchAvailable) {
|
||||
null -> if (preview != null) 1 else 0
|
||||
false -> 1
|
||||
true -> 1 + preview.messages.count { it.role != MessageRole.SYSTEM } +
|
||||
(if (preview.historyTruncated) 1 else 0) +
|
||||
(if (preview.error.isNullOrBlank()) 0 else 1)
|
||||
} + if (preview != null) 1 else 0 // explicit bottom anchor for growing rows
|
||||
1 + if (!expanded) 0 else activity.events.size +
|
||||
(if (activity.truncated) 1 else 0) +
|
||||
(if (activity.partialAfterGap) 1 else 0) + previewRows
|
||||
}
|
||||
}
|
||||
|
||||
internal fun subagentActivityFollowTarget(
|
||||
activities: List<SubagentActivity>,
|
||||
expandedKeys: Set<String>,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
childPreview: SubagentChildPreview?,
|
||||
): Int {
|
||||
if (activities.isEmpty() || !visibility.showLifecycle) return -1
|
||||
var index = 0 // section heading
|
||||
var selectedTarget = -1
|
||||
activities.forEach { activity ->
|
||||
index += 1 // lane header
|
||||
if (activity.stableKey in expandedKeys) {
|
||||
if (activity.truncated) index += 1
|
||||
index += activity.events.size
|
||||
if (activity.partialAfterGap) index += 1
|
||||
if (visibility.showChildHistory && childPreview?.activityKey == activity.stableKey) {
|
||||
index += when (childPreview.childWatchAvailable) {
|
||||
null, false -> 1
|
||||
true -> 1 + childPreview.messages.count { it.role != MessageRole.SYSTEM } +
|
||||
(if (childPreview.historyTruncated) 1 else 0) +
|
||||
(if (childPreview.error.isNullOrBlank()) 0 else 1)
|
||||
}
|
||||
index += 1 // explicit bottom anchor for growing child content
|
||||
selectedTarget = index
|
||||
}
|
||||
}
|
||||
}
|
||||
return if (selectedTarget >= 0) selectedTarget else index
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SubagentActivityHeader(
|
||||
activity: SubagentActivity,
|
||||
expanded: Boolean,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val title = activity.goal.takeIf { visibility.showReasoning && it.isNotBlank() }
|
||||
?: stringResource(R.string.agent_activity_fallback, activity.taskIndex + 1)
|
||||
val phaseLabel = phaseLabel(activity.phase)
|
||||
val description = stringResource(
|
||||
R.string.agent_activity_lane_a11y,
|
||||
title,
|
||||
phaseLabel,
|
||||
activity.taskIndex + 1,
|
||||
activity.taskCount,
|
||||
)
|
||||
val icon: ImageVector = when (activity.phase) {
|
||||
SubagentActivityPhase.COMPLETED -> Icons.Filled.CheckCircle
|
||||
SubagentActivityPhase.FAILED -> Icons.Filled.ErrorOutline
|
||||
SubagentActivityPhase.INTERRUPTED,
|
||||
SubagentActivityPhase.ENDED_WITH_PARENT,
|
||||
-> Icons.Filled.PauseCircleOutline
|
||||
SubagentActivityPhase.STARTED,
|
||||
SubagentActivityPhase.THINKING,
|
||||
SubagentActivityPhase.TOOL,
|
||||
SubagentActivityPhase.PROGRESS,
|
||||
-> Icons.Filled.HourglassTop
|
||||
}
|
||||
val tint = when (activity.phase) {
|
||||
SubagentActivityPhase.FAILED -> MaterialTheme.colorScheme.error
|
||||
SubagentActivityPhase.COMPLETED -> MaterialTheme.colorScheme.primary
|
||||
else -> MaterialTheme.colorScheme.tertiary
|
||||
}
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 3.dp)
|
||||
.heightIn(min = 48.dp)
|
||||
.semantics {
|
||||
contentDescription = description
|
||||
stateDescription = phaseLabel
|
||||
liveRegion = LiveRegionMode.Polite
|
||||
}
|
||||
.clickable(onClick = onClick),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(9.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
stringResource(
|
||||
R.string.agent_activity_task_position,
|
||||
activity.taskIndex + 1,
|
||||
activity.taskCount,
|
||||
phaseLabel,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
activity.durationSeconds?.takeIf { activity.isTerminal }?.let { seconds ->
|
||||
Text(
|
||||
stringResource(R.string.agent_activity_duration, seconds),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Icon(
|
||||
if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
|
||||
contentDescription = stringResource(
|
||||
if (expanded) R.string.cd_subagent_collapse else R.string.cd_subagent_expand,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SubagentEventRow(
|
||||
event: SubagentActivityEvent,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
) {
|
||||
val label = when (event.kind) {
|
||||
SubagentActivityEventKind.STARTED -> stringResource(R.string.agent_activity_event_started)
|
||||
SubagentActivityEventKind.UPDATE -> stringResource(R.string.agent_activity_event_update)
|
||||
SubagentActivityEventKind.TOOL -> stringResource(R.string.agent_activity_event_tool)
|
||||
SubagentActivityEventKind.COMPLETED -> phaseLabel(event.phase)
|
||||
}
|
||||
val showText = when (event.kind) {
|
||||
SubagentActivityEventKind.STARTED -> false
|
||||
SubagentActivityEventKind.UPDATE,
|
||||
SubagentActivityEventKind.COMPLETED,
|
||||
-> visibility.showReasoning
|
||||
SubagentActivityEventKind.TOOL -> visibility.showToolDetails
|
||||
}
|
||||
val toolName = event.toolName?.takeIf { visibility.showToolNames || visibility.showToolDetails }
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 38.dp, end = 20.dp, top = 5.dp, bottom = 5.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.AccountTree,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(label, style = MaterialTheme.typography.labelSmall)
|
||||
toolName?.let {
|
||||
Text(
|
||||
" · $it",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
event.text?.takeIf { showText && it.isNotBlank() }?.let { text ->
|
||||
Text(
|
||||
text,
|
||||
modifier = Modifier.padding(top = 3.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = if (event.kind == SubagentActivityEventKind.TOOL) {
|
||||
FontFamily.Monospace
|
||||
} else {
|
||||
FontFamily.Default
|
||||
},
|
||||
maxLines = 8,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SubagentMetaRow(text: String) {
|
||||
Text(
|
||||
text,
|
||||
modifier = Modifier.padding(start = 38.dp, end = 20.dp, top = 4.dp, bottom = 6.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SubagentChildMessageRow(
|
||||
message: ChatMessage,
|
||||
visibility: SubagentPreviewVisibility,
|
||||
) {
|
||||
if (message.role == MessageRole.SYSTEM) return
|
||||
val role = when (message.role) {
|
||||
MessageRole.USER -> stringResource(R.string.agent_activity_child_role_task)
|
||||
MessageRole.ASSISTANT -> stringResource(R.string.agent_activity_child_role_agent)
|
||||
MessageRole.SYSTEM -> stringResource(R.string.agent_activity_child_role_system)
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 38.dp, end = 20.dp, top = 6.dp, bottom = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
role,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
message.thinkingContent.takeIf { visibility.showReasoning && it.isNotBlank() }?.let { thought ->
|
||||
Text(
|
||||
thought,
|
||||
modifier = Modifier.padding(top = 3.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 10,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
message.content.takeIf(String::isNotBlank)?.let { content ->
|
||||
Text(
|
||||
content,
|
||||
modifier = Modifier.padding(top = 3.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 20,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (visibility.showToolNames || visibility.showToolDetails) {
|
||||
message.toolCalls.forEach { tool ->
|
||||
Text(
|
||||
buildString {
|
||||
append(tool.name)
|
||||
if (visibility.showToolDetails) {
|
||||
tool.args?.takeIf(String::isNotBlank)?.let { append(" · ").append(it.take(500)) }
|
||||
}
|
||||
},
|
||||
modifier = Modifier.padding(top = 3.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
maxLines = 5,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun phaseLabel(phase: SubagentActivityPhase): String = stringResource(
|
||||
when (phase) {
|
||||
SubagentActivityPhase.STARTED -> R.string.agent_activity_status_started
|
||||
SubagentActivityPhase.THINKING -> R.string.agent_activity_status_thinking
|
||||
SubagentActivityPhase.TOOL -> R.string.agent_activity_status_tool
|
||||
SubagentActivityPhase.PROGRESS -> R.string.agent_activity_status_progress
|
||||
SubagentActivityPhase.COMPLETED -> R.string.agent_activity_status_completed
|
||||
SubagentActivityPhase.FAILED -> R.string.agent_activity_status_failed
|
||||
SubagentActivityPhase.INTERRUPTED -> R.string.agent_activity_status_interrupted
|
||||
SubagentActivityPhase.ENDED_WITH_PARENT -> R.string.agent_activity_status_unavailable
|
||||
},
|
||||
)
|
||||
@@ -31,23 +31,54 @@ import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticLogEntry
|
||||
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||
import com.hermesandroid.relay.reliability.ReliabilityEnvironment
|
||||
import com.hermesandroid.relay.reliability.ReliabilityRedactor
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.reliability.ReliabilityReport
|
||||
import com.hermesandroid.relay.reliability.SupportBundleBuilder
|
||||
import com.hermesandroid.relay.util.IssueReport
|
||||
|
||||
data class SupportReviewState(
|
||||
val reportCount: Int,
|
||||
val recordCount: Int,
|
||||
val text: String,
|
||||
val shareEnabled: Boolean,
|
||||
)
|
||||
|
||||
internal fun buildSupportReviewState(reports: List<ReliabilityReport>): SupportReviewState =
|
||||
SupportReviewState(
|
||||
reportCount = reports.takeLast(SupportBundleBuilder.MAX_REPORTS).size,
|
||||
text = SupportBundleBuilder.build(reports),
|
||||
shareEnabled = reports.isNotEmpty(),
|
||||
internal fun buildSupportReviewState(
|
||||
reports: List<ReliabilityReport>,
|
||||
diagnostics: List<DiagnosticLogEntry> = emptyList(),
|
||||
environment: ReliabilityEnvironment? = reports.lastOrNull()?.environment,
|
||||
): SupportReviewState {
|
||||
val reportCount = reports.takeLast(SupportBundleBuilder.MAX_REPORTS).size
|
||||
val diagnosticCount = diagnostics.takeLast(DiagnosticsLog.SUPPORT_ENTRY_LIMIT).size
|
||||
val diagnosticText = DiagnosticsLog.supportText(diagnostics)
|
||||
val combined = buildString {
|
||||
append(SupportBundleBuilder.build(reports))
|
||||
environment?.let {
|
||||
appendLine()
|
||||
appendLine()
|
||||
appendLine("Current environment")
|
||||
appendLine("App: ${it.versionName} (code ${it.versionCode}) ${it.flavor}")
|
||||
append(
|
||||
"Device: ${it.manufacturer} ${it.model} — " +
|
||||
"Android ${it.androidRelease} (SDK ${it.sdkInt})",
|
||||
)
|
||||
}
|
||||
if (diagnosticText.isNotBlank()) {
|
||||
appendLine()
|
||||
appendLine()
|
||||
append(diagnosticText)
|
||||
}
|
||||
}
|
||||
val recordCount = reportCount + diagnosticCount
|
||||
return SupportReviewState(
|
||||
recordCount = recordCount,
|
||||
text = ReliabilityRedactor.redact(combined, 64_000),
|
||||
shareEnabled = recordCount > 0,
|
||||
)
|
||||
}
|
||||
|
||||
/** Exact review surface for the local text handed to clipboard/share. */
|
||||
@Composable
|
||||
@@ -70,7 +101,7 @@ fun SupportBundleDialog(state: SupportReviewState, onDismiss: () -> Unit) {
|
||||
Text(stringResource(R.string.support_bundle_title), style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
stringResource(R.string.support_bundle_privacy, state.reportCount),
|
||||
stringResource(R.string.support_bundle_privacy, state.recordCount),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -63,13 +64,20 @@ import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.composed
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -103,6 +111,8 @@ import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
|
||||
internal const val VOICE_MODE_MIC_TEST_TAG = "voiceModeMic"
|
||||
|
||||
/**
|
||||
* Full-screen voice-mode overlay. Renders the MorphingSphere in its voiceMode
|
||||
* expanded state plus a mic button that drives the [VoiceViewModel] turn
|
||||
@@ -152,6 +162,7 @@ fun VoiceModeOverlay(
|
||||
voiceOutputEnabled: Boolean? = null,
|
||||
voiceOutputFallbackEnabled: Boolean? = null,
|
||||
onOverlayRequest: () -> Unit = {},
|
||||
systemOverlayAvailable: Boolean = true,
|
||||
presentationMode: VoicePresentationMode = VoicePresentationMode.Focus,
|
||||
onPresentationModeChange: (VoicePresentationMode) -> Unit = {},
|
||||
// === END PHASE3-voice-mode-transcript ===
|
||||
@@ -238,6 +249,7 @@ fun VoiceModeOverlay(
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
onOverlayRequest = onOverlayRequest,
|
||||
systemOverlayAvailable = systemOverlayAvailable,
|
||||
onOpenSettings = onOpenSettings,
|
||||
onExit = onDismiss,
|
||||
modifier = Modifier
|
||||
@@ -622,6 +634,22 @@ private fun VoiceMicButton(
|
||||
) {
|
||||
if (!visible) return
|
||||
|
||||
val micActionDescription = when (uiState.state) {
|
||||
VoiceState.Idle, VoiceState.Error -> stringResource(R.string.voice_overlay_tap_action_idle)
|
||||
VoiceState.Listening ->
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
stringResource(R.string.voice_overlay_tap_action_pause)
|
||||
} else {
|
||||
stringResource(R.string.voice_overlay_tap_action_listening)
|
||||
}
|
||||
VoiceState.Transcribing, VoiceState.Thinking, VoiceState.Speaking ->
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
stringResource(R.string.voice_overlay_tap_action_pause)
|
||||
} else {
|
||||
stringResource(R.string.voice_overlay_tap_action_interrupt)
|
||||
}
|
||||
}
|
||||
|
||||
val pulseScale by animateFloatAsState(
|
||||
targetValue = when (uiState.state) {
|
||||
VoiceState.Listening -> 1f + uiState.amplitude * 0.15f
|
||||
@@ -656,34 +684,22 @@ private fun VoiceMicButton(
|
||||
else -> Icons.Filled.Mic
|
||||
}
|
||||
|
||||
val currentOnTap by rememberUpdatedState(onTap)
|
||||
val currentOnHoldPress by rememberUpdatedState(onHoldPress)
|
||||
val currentOnHoldRelease by rememberUpdatedState(onHoldRelease)
|
||||
|
||||
val gestureModifier = when (uiState.interactionMode) {
|
||||
InteractionMode.HoldToTalk -> Modifier.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false)
|
||||
currentOnHoldPress()
|
||||
// Hold until the finger genuinely lifts. Don't use
|
||||
// waitForUpOrCancellation(): it ends the hold on ANY cancel — a
|
||||
// consumed move event or the finger drifting just off the small
|
||||
// circle — which made the button feel like it released by
|
||||
// accident. Loop until no pointer is still pressed so drift and
|
||||
// minor consumption don't cut the recording short.
|
||||
do {
|
||||
val event = awaitPointerEvent()
|
||||
} while (event.changes.any { it.pressed })
|
||||
currentOnHoldRelease()
|
||||
}
|
||||
}
|
||||
else -> Modifier.clickable { currentOnTap() }
|
||||
InteractionMode.HoldToTalk -> Modifier.voiceHoldGesture(
|
||||
state = uiState.state,
|
||||
inactiveActionLabel = micActionDescription,
|
||||
activeActionLabel = stringResource(R.string.voice_overlay_tap_action_listening),
|
||||
onPress = onHoldPress,
|
||||
onRelease = onHoldRelease,
|
||||
)
|
||||
else -> Modifier.clickable(onClick = onTap)
|
||||
}
|
||||
|
||||
Surface(
|
||||
modifier = modifier
|
||||
.size((baseSize * pulseScale).dp)
|
||||
.clip(CircleShape)
|
||||
.testTag(VOICE_MODE_MIC_TEST_TAG)
|
||||
.then(gestureModifier),
|
||||
shape = CircleShape,
|
||||
color = containerColor,
|
||||
@@ -692,7 +708,11 @@ private fun VoiceMicButton(
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = stringResource(R.string.voice_overlay_mic_cd),
|
||||
contentDescription = if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
null
|
||||
} else {
|
||||
micActionDescription
|
||||
},
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(iconSize.dp),
|
||||
)
|
||||
@@ -700,6 +720,96 @@ private fun VoiceMicButton(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Hold-to-talk gesture for in-app and system-overlay voice controls.
|
||||
* The callback refs update across recomposition without restarting the active
|
||||
* gesture when its press changes VoiceUiState to Listening.
|
||||
*/
|
||||
internal fun Modifier.voiceHoldGesture(
|
||||
state: VoiceState,
|
||||
inactiveActionLabel: String,
|
||||
activeActionLabel: String,
|
||||
onPress: () -> Unit,
|
||||
onRelease: () -> Unit,
|
||||
inactiveContentDescription: String = inactiveActionLabel,
|
||||
activeContentDescription: String = activeActionLabel,
|
||||
): Modifier = composed {
|
||||
val currentOnPress by rememberUpdatedState(onPress)
|
||||
val currentOnRelease by rememberUpdatedState(onRelease)
|
||||
var semanticHoldActive by remember { mutableStateOf(state == VoiceState.Listening) }
|
||||
var semanticCaptureStarted by remember { mutableStateOf(state == VoiceState.Listening) }
|
||||
|
||||
LaunchedEffect(state) {
|
||||
when {
|
||||
state == VoiceState.Listening -> {
|
||||
semanticHoldActive = true
|
||||
semanticCaptureStarted = true
|
||||
}
|
||||
semanticCaptureStarted -> {
|
||||
semanticHoldActive = false
|
||||
semanticCaptureStarted = false
|
||||
}
|
||||
state == VoiceState.Error -> semanticHoldActive = false
|
||||
}
|
||||
}
|
||||
|
||||
val semanticToggle = {
|
||||
if (semanticHoldActive) {
|
||||
semanticHoldActive = false
|
||||
semanticCaptureStarted = false
|
||||
currentOnRelease()
|
||||
} else {
|
||||
semanticHoldActive = true
|
||||
currentOnPress()
|
||||
}
|
||||
}
|
||||
Modifier
|
||||
.semantics(mergeDescendants = true) {
|
||||
role = Role.Button
|
||||
contentDescription = if (semanticHoldActive) {
|
||||
activeContentDescription
|
||||
} else {
|
||||
inactiveContentDescription
|
||||
}
|
||||
onClick(
|
||||
label = if (semanticHoldActive) activeActionLabel else inactiveActionLabel,
|
||||
) {
|
||||
semanticToggle()
|
||||
true
|
||||
}
|
||||
}
|
||||
.onPreviewKeyEvent { event ->
|
||||
val native = event.nativeKeyEvent
|
||||
val activationKey = native.keyCode == android.view.KeyEvent.KEYCODE_ENTER ||
|
||||
native.keyCode == android.view.KeyEvent.KEYCODE_NUMPAD_ENTER ||
|
||||
native.keyCode == android.view.KeyEvent.KEYCODE_SPACE ||
|
||||
native.keyCode == android.view.KeyEvent.KEYCODE_DPAD_CENTER
|
||||
if (native.action == android.view.KeyEvent.ACTION_UP && activationKey) {
|
||||
semanticToggle()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
.focusable()
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false)
|
||||
currentOnPress()
|
||||
// Hold until the finger genuinely lifts. Don't use
|
||||
// waitForUpOrCancellation(): it ends the hold on ANY cancel — a
|
||||
// consumed move event or the finger drifting just off the small
|
||||
// circle — which made the button feel like it released by
|
||||
// accident. Loop until no pointer is still pressed so drift and
|
||||
// minor consumption don't cut the recording short.
|
||||
do {
|
||||
val event = awaitPointerEvent()
|
||||
} while (event.changes.any { it.pressed })
|
||||
currentOnRelease()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun voiceStateToSphereState(state: VoiceState): SphereState = when (state) {
|
||||
VoiceState.Listening -> SphereState.Listening
|
||||
VoiceState.Speaking -> SphereState.Speaking
|
||||
@@ -773,6 +883,7 @@ fun ConversationVoiceDock(
|
||||
onOverlayRequest: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onExit: () -> Unit,
|
||||
systemOverlayAvailable: Boolean = true,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
@@ -816,17 +927,19 @@ fun ConversationVoiceDock(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
TextButton(
|
||||
onClick = onOverlayRequest,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.height(40.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.voice_overlay_overlay),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (systemOverlayAvailable) {
|
||||
TextButton(
|
||||
onClick = onOverlayRequest,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.height(40.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.voice_overlay_overlay),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = onExit,
|
||||
@@ -1006,6 +1119,7 @@ private fun VoiceSessionPill(
|
||||
onInterrupt: () -> Unit,
|
||||
onPauseAutoMode: () -> Unit,
|
||||
onOverlayRequest: () -> Unit,
|
||||
systemOverlayAvailable: Boolean,
|
||||
onOpenSettings: () -> Unit,
|
||||
onExit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -1158,21 +1272,23 @@ private fun VoiceSessionPill(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
onFocusModeChange(false)
|
||||
onOverlayRequest()
|
||||
},
|
||||
modifier = Modifier
|
||||
.weight(0.95f)
|
||||
.height(40.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.voice_overlay_overlay),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (systemOverlayAvailable) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
onFocusModeChange(false)
|
||||
onOverlayRequest()
|
||||
},
|
||||
modifier = Modifier
|
||||
.weight(0.95f)
|
||||
.height(40.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.voice_overlay_overlay),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = onExit,
|
||||
@@ -1289,8 +1405,9 @@ internal fun dispatchVoiceMicHoldPress(
|
||||
) {
|
||||
when (uiState.state) {
|
||||
VoiceState.Idle, VoiceState.Error -> onStartListening()
|
||||
VoiceState.Speaking -> onInterruptAndStart()
|
||||
VoiceState.Listening, VoiceState.Transcribing, VoiceState.Thinking -> Unit
|
||||
VoiceState.Speaking, VoiceState.Transcribing, VoiceState.Thinking ->
|
||||
onInterruptAndStart()
|
||||
VoiceState.Listening -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ private val OnboardingAccent = Color(0xFF7B55F6)
|
||||
* Hermes API/dashboard features first, Relay-only power tools second.
|
||||
* 2. **Connect page** — embeds the shared [ConnectionWizard] so onboarding
|
||||
* uses the exact same Standard API/dashboard and optional Relay pairing
|
||||
* flow as Settings → Connections.
|
||||
* flow as Settings → Gateways.
|
||||
*
|
||||
* The previous separate "ConnectPage" + "RelayPage" pair has been removed —
|
||||
* it discarded the QR's relay block, never applied per-channel grants, never
|
||||
@@ -177,6 +177,7 @@ fun OnboardingScreen(
|
||||
) { granted ->
|
||||
notificationsPermitted =
|
||||
granted || AppPermissionStatusProbe.snapshot(context).notificationsPermitted
|
||||
connectionViewModel.setNotifyTurnComplete(notificationsPermitted)
|
||||
}
|
||||
|
||||
Surface(
|
||||
@@ -288,7 +289,14 @@ fun OnboardingScreen(
|
||||
)
|
||||
},
|
||||
onReviewPermissions = onOpenPermissions,
|
||||
onFinish = onComplete,
|
||||
onFinish = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
!notificationsPermitted
|
||||
) {
|
||||
connectionViewModel.setNotifyTurnComplete(false)
|
||||
}
|
||||
onComplete()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +169,7 @@ import com.hermesandroid.relay.util.AttachmentTooLargeException
|
||||
import com.hermesandroid.relay.util.readBase64Bounded
|
||||
import com.hermesandroid.relay.data.ChatComposerDraftKey
|
||||
import com.hermesandroid.relay.data.ChatQuoteReference
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.LARGE_PASTE_THRESHOLD_CHARS
|
||||
import com.hermesandroid.relay.data.buildChatQuotedPrompt
|
||||
import com.hermesandroid.relay.data.largePasteAttachment
|
||||
@@ -216,6 +217,7 @@ import com.hermesandroid.relay.ui.components.CHAT_PET_STEP_MESSAGE_MARKER
|
||||
import com.hermesandroid.relay.ui.components.CHAT_PET_USER_MESSAGE_PERCH_PREFIX
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessSheet
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||
import com.hermesandroid.relay.ui.components.InjectedContextSheet
|
||||
import com.hermesandroid.relay.ui.components.InlineAutocomplete
|
||||
import com.hermesandroid.relay.ui.components.loadedContentTransform
|
||||
@@ -437,6 +439,29 @@ internal fun ownedBottomFollowScroll(
|
||||
return requiredBottomFollowScroll(previous, current)
|
||||
}
|
||||
|
||||
internal fun shouldShowRetainedHistoryDashboardSignIn(
|
||||
hasMessages: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiReachable: Boolean,
|
||||
supervised: Boolean,
|
||||
): Boolean = hasMessages &&
|
||||
!supervised &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
!apiReachable
|
||||
|
||||
internal fun shouldPresentChatFailureDuringDashboardSignIn(
|
||||
failure: ChatFailureNotice,
|
||||
dashboardSignInRequired: Boolean,
|
||||
): Boolean {
|
||||
if (!dashboardSignInRequired || failure.route != ChatFailureRoute.GATEWAY) return true
|
||||
val authFailure = failure.rawError.contains("no_cookie", ignoreCase = true) ||
|
||||
(
|
||||
failure.rawError.contains("Auth provider", ignoreCase = true) &&
|
||||
failure.rawError.contains("unreachable", ignoreCase = true)
|
||||
)
|
||||
return !authFailure && !failure.turnId.startsWith("history-")
|
||||
}
|
||||
|
||||
/**
|
||||
* One frame of the live bottom-follow ramp. The maximum step is derived from
|
||||
* the viewport, never the transcript distance, so a long session cannot make
|
||||
@@ -708,7 +733,7 @@ fun ChatScreen(
|
||||
// Offline demo entry, surfaced on the empty-chat "needs connection" card so a
|
||||
// skipped / never-connected first run can explore without a server. null hides it.
|
||||
onTryDemo: (() -> Unit)? = null,
|
||||
onNavigateToManage: () -> Unit = {},
|
||||
onNavigateToDashboardSignIn: () -> Unit = {},
|
||||
onNavigateToBridge: () -> Unit = {},
|
||||
onNavigateToTerminal: () -> Unit = {},
|
||||
onNavigateToSettings: () -> Unit = {},
|
||||
@@ -928,8 +953,14 @@ fun ChatScreen(
|
||||
val backgroundProcesses by chatViewModel.backgroundProcesses.collectAsState()
|
||||
val backgroundProcessesLoading by chatViewModel.backgroundProcessesLoading.collectAsState()
|
||||
val stoppingProcessIds by chatViewModel.stoppingProcessIds.collectAsState()
|
||||
val subagentActivities by chatViewModel.subagentActivities.collectAsState()
|
||||
val subagentChildPreview by chatViewModel.subagentChildPreview.collectAsState()
|
||||
val isLoadingHistory by chatViewModel.isLoadingHistory.collectAsState()
|
||||
val isLoadingSessions by chatViewModel.isLoadingSessions.collectAsState()
|
||||
val isLoadingMoreSessions by chatViewModel.isLoadingMoreSessions.collectAsState()
|
||||
val hasMoreSessions by chatViewModel.hasMoreSessions.collectAsState()
|
||||
val sessionPageLoadFailed by chatViewModel.sessionPageLoadFailed.collectAsState()
|
||||
val sessionListUnavailable by chatViewModel.sessionListUnavailable.collectAsState()
|
||||
val selectedPersonality by chatViewModel.selectedPersonality.collectAsState()
|
||||
val personalityNames by chatViewModel.personalityNames.collectAsState()
|
||||
val defaultPersonality by chatViewModel.defaultPersonality.collectAsState()
|
||||
@@ -948,53 +979,69 @@ fun ChatScreen(
|
||||
val agentProfiles by connectionViewModel.agentProfiles.collectAsState()
|
||||
var allProfileSessions by remember { mutableStateOf<List<ProfileSessionRow>>(emptyList()) }
|
||||
var allProfileSessionsLoading by remember { mutableStateOf(false) }
|
||||
var allProfileSessionsUnavailable by remember { mutableStateOf(false) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
suspend fun refreshAllProfileSessions(showError: Boolean) {
|
||||
if (isProfileLocked || allProfileSessionsLoading) return
|
||||
allProfileSessionsLoading = true
|
||||
val result = connectionViewModel.listAllProfileSessions()
|
||||
result?.fold(
|
||||
onSuccess = { items ->
|
||||
allProfileSessions = items.mapNotNull { item ->
|
||||
val owner = item.profile?.takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
ProfileSessionRow(
|
||||
profile = owner,
|
||||
session = com.hermesandroid.relay.data.ChatSession(
|
||||
sessionId = item.id,
|
||||
title = item.title ?: item.preview,
|
||||
model = item.model,
|
||||
messageCount = item.messageCount ?: 0,
|
||||
inputTokens = item.inputTokens ?: 0,
|
||||
outputTokens = item.outputTokens ?: 0,
|
||||
actualCostUsd = item.actualCostUsd,
|
||||
estimatedCostUsd = item.estimatedCostUsd,
|
||||
recentlyActive = item.isActive,
|
||||
startedAt = ((item.startedAt ?: 0.0) * 1000).toLong(),
|
||||
lastActivityAt = ((item.resolvedLastActivity ?: 0.0) * 1000).toLong(),
|
||||
source = item.source,
|
||||
pinned = item.pinned,
|
||||
archived = item.archived,
|
||||
workingDirectory = item.cwd,
|
||||
gitBranch = item.gitBranch,
|
||||
gitRepoRoot = item.gitRepoRoot,
|
||||
pullRequestNumber = item.pullRequest?.number,
|
||||
pullRequestUrl = item.pullRequest?.url,
|
||||
pullRequestState = item.pullRequest?.state,
|
||||
pullRequestDraft = item.pullRequest?.draft == true,
|
||||
),
|
||||
allProfileSessionsUnavailable = false
|
||||
try {
|
||||
val result = connectionViewModel.listAllProfileSessions()
|
||||
if (result == null) allProfileSessionsUnavailable = true
|
||||
result?.fold(
|
||||
onSuccess = { items ->
|
||||
allProfileSessionsUnavailable = false
|
||||
allProfileSessions = items.mapNotNull { item ->
|
||||
val owner = item.profile?.takeIf { it.isNotBlank() }
|
||||
?: return@mapNotNull null
|
||||
ProfileSessionRow(
|
||||
profile = owner,
|
||||
session = com.hermesandroid.relay.data.ChatSession(
|
||||
sessionId = item.id,
|
||||
title = item.title ?: item.preview,
|
||||
model = item.model,
|
||||
messageCount = item.messageCount ?: 0,
|
||||
inputTokens = item.inputTokens ?: 0,
|
||||
outputTokens = item.outputTokens ?: 0,
|
||||
actualCostUsd = item.actualCostUsd,
|
||||
estimatedCostUsd = item.estimatedCostUsd,
|
||||
recentlyActive = item.isActive,
|
||||
startedAt = ((item.startedAt ?: 0.0) * 1000).toLong(),
|
||||
lastActivityAt = ((item.resolvedLastActivity ?: 0.0) * 1000).toLong(),
|
||||
source = item.source,
|
||||
pinned = item.pinned,
|
||||
archived = item.archived,
|
||||
workingDirectory = item.cwd,
|
||||
gitBranch = item.gitBranch,
|
||||
gitRepoRoot = item.gitRepoRoot,
|
||||
pullRequestNumber = item.pullRequest?.number,
|
||||
pullRequestUrl = item.pullRequest?.url,
|
||||
pullRequestState = item.pullRequest?.state,
|
||||
pullRequestDraft = item.pullRequest?.draft == true,
|
||||
),
|
||||
)
|
||||
}
|
||||
chatViewModel.updateSessionActivityDirectory(
|
||||
rows = allProfileSessions.map { it.profile to it.session.sessionId },
|
||||
)
|
||||
}
|
||||
chatViewModel.updateSessionActivityDirectory(
|
||||
rows = allProfileSessions.map { it.profile to it.session.sessionId },
|
||||
)
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (showError) snackbarHostState.showSnackbar(
|
||||
"Couldn't load all profiles: ${error.message ?: "unsupported"}",
|
||||
)
|
||||
},
|
||||
)
|
||||
allProfileSessionsLoading = false
|
||||
},
|
||||
onFailure = { error ->
|
||||
allProfileSessionsUnavailable = true
|
||||
if (showError) snackbarHostState.showSnackbar(
|
||||
"Couldn't load all profiles: ${error.message ?: "unsupported"}",
|
||||
)
|
||||
},
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
allProfileSessionsUnavailable = true
|
||||
if (showError) snackbarHostState.showSnackbar(
|
||||
"Couldn't load all profiles: ${e.message ?: "unsupported"}",
|
||||
)
|
||||
} finally {
|
||||
allProfileSessionsLoading = false
|
||||
}
|
||||
}
|
||||
val conversationBinding by chatViewModel.conversationBinding.collectAsState()
|
||||
val explicitBindingProfileName = conversationBinding.profileName
|
||||
@@ -1062,6 +1109,13 @@ fun ChatScreen(
|
||||
supervisedVisibility.showToolNames -> "compact"
|
||||
else -> "off"
|
||||
}
|
||||
val subagentPreviewVisibility = SubagentPreviewVisibility(
|
||||
showLifecycle = !supervised || supervisedVisibility.showWorkingStatus,
|
||||
showReasoning = showThinking,
|
||||
showToolNames = toolDisplay == "compact" || toolDisplay == "detailed",
|
||||
showToolDetails = toolDisplay == "detailed",
|
||||
showChildHistory = !supervised,
|
||||
)
|
||||
val smoothAutoScroll by connectionViewModel.smoothAutoScroll.collectAsState()
|
||||
val closeDrawerOnSend by connectionViewModel.closeDrawerOnSend.collectAsState()
|
||||
val keepComposerFocusedOnSend by
|
||||
@@ -1112,6 +1166,8 @@ fun ChatScreen(
|
||||
val streamingEndpointPref by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
val chatServerCapabilities by connectionViewModel.serverCapabilities.collectAsState()
|
||||
val chatGatewayAvailability by connectionViewModel.gatewayAvailability.collectAsState()
|
||||
val dashboardSignInRequired =
|
||||
chatGatewayAvailability == GatewayAvailability.SignInRequired && !apiReachable
|
||||
val isGatewayTransport = remember(
|
||||
streamingEndpointPref, chatServerCapabilities, chatGatewayAvailability,
|
||||
) {
|
||||
@@ -1119,18 +1175,15 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
// Recover any durable in-flight chat checkpoint whenever Chat returns to
|
||||
// the foreground. On Gateway this also pre-warms/re-attaches the socket;
|
||||
// sessions-SSE falls back to bounded persisted-history reconciliation.
|
||||
// the foreground. setChatVisible owns that edge; an ordinary Gateway open
|
||||
// warms only the observation socket and never attaches a saved session.
|
||||
val appForeground by com.hermesandroid.relay.util.AppForegroundTracker.isForeground.collectAsState()
|
||||
LaunchedEffect(isGatewayTransport, appForeground, chatReady) {
|
||||
chatViewModel.setChatVisible(appForeground && chatReady)
|
||||
if (appForeground && chatReady) {
|
||||
chatViewModel.prewarmGateway()
|
||||
}
|
||||
if (isGatewayTransport && appForeground && chatReady) {
|
||||
chatViewModel.refreshModelOptions()
|
||||
chatViewModel.refreshReasoningSettings()
|
||||
}
|
||||
val visibleGatewayOwner = appForeground && chatReady && isGatewayTransport
|
||||
chatViewModel.setChatVisible(visibleGatewayOwner)
|
||||
// updateGatewayClient owns the one-time catalog/reasoning bootstrap for
|
||||
// a newly-ready socket. Repeating it here created a duplicate cold-open
|
||||
// RPC burst while the session directory was also trying to hydrate.
|
||||
}
|
||||
DisposableEffect(chatViewModel) {
|
||||
onDispose { chatViewModel.setChatVisible(false) }
|
||||
@@ -1362,6 +1415,7 @@ fun ChatScreen(
|
||||
// A process inventory is scoped to one gateway session. Never leave a
|
||||
// sheet opened onto a different chat after a drawer/profile switch.
|
||||
LaunchedEffect(currentSessionId, selectedProfile?.name, activeConnection?.id) {
|
||||
chatViewModel.closeSubagentChildPreview()
|
||||
showBackgroundProcesses = false
|
||||
}
|
||||
|
||||
@@ -1559,8 +1613,11 @@ fun ChatScreen(
|
||||
voiceOutputConfig?.enabled
|
||||
}
|
||||
|
||||
val voiceSystemOverlayAvailable = BuildFlavor.isSideload
|
||||
val showVoiceSystemOverlay: () -> Unit = {
|
||||
if (assistantSessionActive) {
|
||||
if (!voiceSystemOverlayAvailable) {
|
||||
pendingVoiceOverlayPermission = false
|
||||
} else if (assistantSessionActive) {
|
||||
voiceOverlayHost.hide()
|
||||
} else if (!voiceOverlayHost.hasOverlayPermission()) {
|
||||
pendingVoiceOverlayPermission = true
|
||||
@@ -2102,13 +2159,6 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh sessions when screen appears and API is ready
|
||||
LaunchedEffect(chatReady) {
|
||||
if (chatReady) {
|
||||
chatViewModel.refreshSessions()
|
||||
}
|
||||
}
|
||||
|
||||
// The drawer and composer share this screen's focus owner. Clear the
|
||||
// composer's input focus as soon as an open transition is committed so
|
||||
// menu activation, accessibility activation, and edge swipes all dismiss
|
||||
@@ -2131,8 +2181,11 @@ fun ChatScreen(
|
||||
// row for the active session is preserved by ChatHandler.updateSessions.
|
||||
LaunchedEffect(drawerState.isOpen) {
|
||||
chatViewModel.setSessionActivityDrawerOpen(drawerState.isOpen)
|
||||
if (drawerState.isOpen && chatReady) {
|
||||
chatViewModel.refreshSessions()
|
||||
// Session history is Dashboard HTTP state and remains usable while the
|
||||
// independent Gateway socket is reconnecting. Never gate drawer-open
|
||||
// refresh on chatReady; owner/generation fencing lives in ChatViewModel.
|
||||
if (drawerState.isOpen) {
|
||||
chatViewModel.refreshSessionsIfStale()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2385,8 +2438,15 @@ fun ChatScreen(
|
||||
}
|
||||
val selectProfileFromShelf: (com.hermesandroid.relay.data.Profile?) -> Unit = { profile ->
|
||||
if (AgentDisplay.profileSessionKey(profile?.name) != selectedProfileKey) {
|
||||
connectionViewModel.selectProfile(profile)
|
||||
chatViewModel.activateGatewayProfile(profile)
|
||||
val profileName = profile?.name
|
||||
chatViewModel.selectProfileFromHeader(
|
||||
profileName = profileName,
|
||||
profile = profile,
|
||||
contextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = activeConnection?.id,
|
||||
profileName = profileName,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val hasLiveConversationSurface = messages.isNotEmpty() || isStreaming
|
||||
@@ -2431,6 +2491,26 @@ fun ChatScreen(
|
||||
activeConnectionId = activeConnection?.id,
|
||||
realThreadChatIds = phoneThreadChatIds.values,
|
||||
)
|
||||
val realPhoneSessionIds = remember(sessions) {
|
||||
sessions.asSequence()
|
||||
.filter { it.source.equals("phone", ignoreCase = true) }
|
||||
.map { it.sessionId }
|
||||
.toSet()
|
||||
}
|
||||
val provisionalThreadChatIds = provisionalThreadEntries.keys
|
||||
LaunchedEffect(
|
||||
activeConnection?.id,
|
||||
realPhoneSessionIds,
|
||||
provisionalThreadChatIds,
|
||||
) {
|
||||
// A reply promotes the local provisional row to a real Gateway
|
||||
// source=phone session. Refresh the relay-owned chat_id index at
|
||||
// that boundary so the local duplicate disappears immediately,
|
||||
// without guessing a chat_id from the opaque session id.
|
||||
if (realPhoneSessionIds.isNotEmpty() && provisionalThreadChatIds.isNotEmpty()) {
|
||||
connectionViewModel.refreshPhoneThreadChatIds()
|
||||
}
|
||||
}
|
||||
val provisionalThreads = provisionalThreadEntries.map { (chatId, entries) ->
|
||||
val latest = entries.maxBy { it.receivedAt }
|
||||
ProvisionalThreadRow(
|
||||
@@ -2450,6 +2530,10 @@ fun ChatScreen(
|
||||
scopeSubtitle = drawerSubtitle,
|
||||
activeProfileName = drawerProfileName ?: "default",
|
||||
isLoading = isLoadingSessions,
|
||||
loadFailed = sessionListUnavailable,
|
||||
isLoadingMore = isLoadingMoreSessions,
|
||||
hasMore = hasMoreSessions,
|
||||
loadMoreFailed = sessionPageLoadFailed,
|
||||
isOpen = drawerState.isOpen,
|
||||
activityStates = sessionActivityStates,
|
||||
animationEnabled = animationEnabled,
|
||||
@@ -2459,6 +2543,8 @@ fun ChatScreen(
|
||||
.takeIf { supervised },
|
||||
newChatEnabled = !supervised || supervisedPolicy.capabilities.newChat,
|
||||
onRefresh = { chatViewModel.refreshSessions() },
|
||||
onLoadMore = { chatViewModel.loadMoreSessions() },
|
||||
onRetryLoadMore = { chatViewModel.retryLoadMoreSessions() },
|
||||
onOpenBotMode = {
|
||||
scope.launch { drawerState.close() }
|
||||
onNavigateToBotMode()
|
||||
@@ -2469,25 +2555,6 @@ fun ChatScreen(
|
||||
scope.launch { drawerState.close() }
|
||||
}
|
||||
},
|
||||
onNewDefaultChat = {
|
||||
if (isProfileLocked) return@SessionDrawerContent
|
||||
val defaultProfile = agentProfiles.firstOrNull {
|
||||
it.name.equals("default", ignoreCase = true)
|
||||
} ?: com.hermesandroid.relay.data.Profile(
|
||||
name = "default",
|
||||
model = "",
|
||||
description = "Default",
|
||||
)
|
||||
val opened = chatViewModel.createProfileChat(
|
||||
profileName = "default",
|
||||
profile = defaultProfile,
|
||||
contextKey = AgentDisplay.profileContextKey(
|
||||
connectionId = activeConnection?.id,
|
||||
profileName = "default",
|
||||
),
|
||||
)
|
||||
if (opened) scope.launch { drawerState.close() }
|
||||
},
|
||||
onSelectSession = { sessionId ->
|
||||
chatViewModel.switchSession(sessionId)
|
||||
scope.launch { drawerState.close() }
|
||||
@@ -2549,6 +2616,11 @@ fun ChatScreen(
|
||||
)
|
||||
scope.launch { drawerState.close() }
|
||||
},
|
||||
onDeleteProvisionalThread = { chatId ->
|
||||
activeConnection?.id?.let { connectionId ->
|
||||
connectionViewModel.removeProvisionalThread(chatId, connectionId)
|
||||
}
|
||||
},
|
||||
hiddenSources = hiddenSources,
|
||||
onToggleSourceHidden = { source, hidden ->
|
||||
connectionViewModel.setSourceHidden(source, hidden)
|
||||
@@ -2557,6 +2629,7 @@ fun ChatScreen(
|
||||
!activeConnection?.resolvedDashboardUrl.isNullOrBlank(),
|
||||
allProfileSessions = allProfileSessions,
|
||||
allProfileSessionsLoading = allProfileSessionsLoading,
|
||||
allProfileSessionsLoadFailed = allProfileSessionsUnavailable,
|
||||
profileColors = profilePresentation.colors,
|
||||
onProfileColorChange = connectionViewModel::setProfileColor,
|
||||
onRefreshAllProfiles = {
|
||||
@@ -2883,90 +2956,45 @@ fun ChatScreen(
|
||||
modifier = Modifier.animateContentSize(
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
),
|
||||
verticalArrangement = if (isChatConnecting) {
|
||||
Arrangement.spacedBy(6.dp)
|
||||
} else {
|
||||
Arrangement.Top
|
||||
},
|
||||
verticalArrangement = Arrangement.Top,
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = isChatConnecting,
|
||||
transitionSpec = {
|
||||
(
|
||||
fadeIn(tween(180)) +
|
||||
slideInVertically(tween(220)) { it / 6 }
|
||||
) togetherWith (
|
||||
fadeOut(tween(140)) +
|
||||
slideOutVertically(tween(180)) { -it / 8 }
|
||||
)
|
||||
},
|
||||
label = "chatHeaderIdentityTransition",
|
||||
) { connecting ->
|
||||
if (connecting) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ChatSkeletonLine(
|
||||
modifier = Modifier.width(112.dp),
|
||||
height = 15.dp,
|
||||
)
|
||||
ChatSkeletonLine(
|
||||
modifier = Modifier.width(156.dp),
|
||||
height = 11.dp,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = if (supervised && !supervisedVisibility.showAgentIdentity) {
|
||||
stringResource(R.string.screen_chat_label)
|
||||
} else if (agentDisplayName.isNotBlank()) {
|
||||
agentDisplayName
|
||||
} else {
|
||||
Column {
|
||||
Text(
|
||||
text = if (supervised && !supervisedVisibility.showAgentIdentity) {
|
||||
stringResource(R.string.screen_chat_label)
|
||||
} else if (agentDisplayName.isNotBlank()) {
|
||||
agentDisplayName
|
||||
} else {
|
||||
stringResource(R.string.chat_agent_default)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
stringResource(R.string.chat_agent_default)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
)
|
||||
// Keep the exact persisted identity visible while the
|
||||
// Gateway wakes. The existing loaded-content motion
|
||||
// animates status → confirmed model/personality without
|
||||
// replacing the whole header with anonymous skeletons.
|
||||
AnimatedContent(
|
||||
targetState = subtitleText,
|
||||
transitionSpec = { loadedContentTransform() },
|
||||
label = "chatHeaderSubtitle",
|
||||
) { line ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text(
|
||||
text = line,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = subtitleColor,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
)
|
||||
if (showStreamingState && animationEnabled) {
|
||||
StreamingDots(
|
||||
color = subtitleColor,
|
||||
modifier = Modifier.clearAndSetSemantics { },
|
||||
)
|
||||
// Context % lives in the per-session
|
||||
// ContextMeterBar, and the approval-bypass
|
||||
// marker now rides a compact ⚡ icon in the
|
||||
// app bar actions (full detail in the agent
|
||||
// sheet) instead of being appended here —
|
||||
// so the subtitle stays a clean single line
|
||||
// (`personality · model`) and no longer gets
|
||||
// squeezed out by the trailing action icons.
|
||||
// Fade the subtitle whenever it changes
|
||||
// — most importantly the honest
|
||||
// "Connected" → confirmed-model reveal
|
||||
// once /api/config lands (the model
|
||||
// arrives later than the identity, and
|
||||
// used to pop in). AnimatedContent doesn't
|
||||
// animate its initial state, so this only
|
||||
// smooths real changes, not first paint.
|
||||
AnimatedContent(
|
||||
targetState = subtitleText,
|
||||
transitionSpec = { loadedContentTransform() },
|
||||
label = "chatHeaderSubtitle",
|
||||
) { line ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text(
|
||||
text = line,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = subtitleColor,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
)
|
||||
if (showStreamingState && animationEnabled) {
|
||||
StreamingDots(
|
||||
color = subtitleColor,
|
||||
modifier = Modifier.clearAndSetSemantics { },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3150,6 +3178,22 @@ fun ChatScreen(
|
||||
onClick = if (supervised) null else ({ showContextSheet = true }),
|
||||
)
|
||||
}
|
||||
if (
|
||||
shouldShowRetainedHistoryDashboardSignIn(
|
||||
hasMessages = messages.isNotEmpty(),
|
||||
gatewayAvailability = chatGatewayAvailability,
|
||||
apiReachable = apiReachable,
|
||||
supervised = supervised,
|
||||
)
|
||||
) {
|
||||
ChatDashboardSignInCard(
|
||||
dashboardRouteMovedHint = dashboardRouteMovedHint,
|
||||
onNavigateToDashboardSignIn = onNavigateToDashboardSignIn,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
if (!supervised && showContextSheet) {
|
||||
// Live audit of the exact extra context the agent will be
|
||||
// injected with on the next turn (transparency / auditability).
|
||||
@@ -3241,6 +3285,7 @@ fun ChatScreen(
|
||||
?: activeConnection
|
||||
?.apiServerUrl
|
||||
?.let(Connection::extractDefaultLabel),
|
||||
agentDisplayName = agentDisplayName,
|
||||
chatMode = chatMode,
|
||||
apiReachable = apiReachable,
|
||||
chatReady = chatReady,
|
||||
@@ -3248,7 +3293,7 @@ fun ChatScreen(
|
||||
isLoadingSessions = isLoadingSessions,
|
||||
gatewayAvailability = chatGatewayAvailability,
|
||||
dashboardRouteMovedHint = dashboardRouteMovedHint,
|
||||
onNavigateToManage = onNavigateToManage,
|
||||
onNavigateToDashboardSignIn = onNavigateToDashboardSignIn,
|
||||
onNavigateToConnections = onNavigateToConnections,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
@@ -3310,6 +3355,7 @@ fun ChatScreen(
|
||||
stringResource(R.string.chat_start_conversation)
|
||||
}
|
||||
ChatConnectState.Connecting -> stringResource(R.string.chat_connect_to_hermes_dots)
|
||||
ChatConnectState.Unavailable -> stringResource(R.string.chat_disconnected_label)
|
||||
ChatConnectState.NeedsConnection -> stringResource(R.string.chat_needs_connection)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
@@ -3378,6 +3424,31 @@ fun ChatScreen(
|
||||
|
||||
ChatConnectState.Connecting -> Unit
|
||||
|
||||
ChatConnectState.Unavailable -> {
|
||||
if (dashboardSignInRequired) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
ChatDashboardSignInCard(
|
||||
dashboardRouteMovedHint = dashboardRouteMovedHint,
|
||||
onNavigateToDashboardSignIn = onNavigateToDashboardSignIn,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Button(
|
||||
onClick = connectionViewModel::probeNow,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.chat_retry))
|
||||
}
|
||||
TextButton(
|
||||
onClick = onNavigateToConnections,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.settings_connections))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ChatConnectState.Ready -> {
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
@@ -3954,6 +4025,8 @@ fun ChatScreen(
|
||||
if (isGatewayTransport) {
|
||||
GatewayBackgroundProcessStrip(
|
||||
processes = backgroundProcesses,
|
||||
subagentActivities = subagentActivities,
|
||||
subagentPreviewVisibility = subagentPreviewVisibility,
|
||||
loading = backgroundProcessesLoading,
|
||||
onClick = { showBackgroundProcesses = true },
|
||||
)
|
||||
@@ -4387,7 +4460,14 @@ fun ChatScreen(
|
||||
null
|
||||
}
|
||||
|
||||
visibleChatFailure?.let { failure ->
|
||||
visibleChatFailure
|
||||
?.takeIf { failure ->
|
||||
shouldPresentChatFailureDuringDashboardSignIn(
|
||||
failure = failure,
|
||||
dashboardSignInRequired = dashboardSignInRequired,
|
||||
)
|
||||
}
|
||||
?.let { failure ->
|
||||
val displayFailure = if (!supervised) failure else failure.copy(
|
||||
model = failure.model.takeIf { supervisedVisibility.showModelName },
|
||||
provider = failure.provider.takeIf { supervisedVisibility.showTechnicalRoute },
|
||||
@@ -4656,6 +4736,7 @@ fun ChatScreen(
|
||||
setVoicePresentationMode(VoicePresentationMode.Focus)
|
||||
},
|
||||
onOverlayRequest = showVoiceSystemOverlay,
|
||||
systemOverlayAvailable = voiceSystemOverlayAvailable,
|
||||
onOpenSettings = onNavigateToVoiceSettings,
|
||||
onExit = { voiceViewModel.exitVoiceMode() },
|
||||
)
|
||||
@@ -4812,6 +4893,7 @@ fun ChatScreen(
|
||||
presentationMode = effectiveVoicePresentationMode,
|
||||
onPresentationModeChange = setVoicePresentationMode,
|
||||
onOverlayRequest = showVoiceSystemOverlay,
|
||||
systemOverlayAvailable = voiceSystemOverlayAvailable,
|
||||
// Gear button in the overlay's expanded controls. The overlay
|
||||
// exits voice mode before invoking this, so navigation lands
|
||||
// on Voice Settings with no overlay left on top.
|
||||
@@ -4863,12 +4945,19 @@ fun ChatScreen(
|
||||
if (showBackgroundProcesses) {
|
||||
GatewayBackgroundProcessSheet(
|
||||
processes = backgroundProcesses,
|
||||
subagentActivities = subagentActivities,
|
||||
subagentChildPreview = subagentChildPreview,
|
||||
subagentPreviewVisibility = subagentPreviewVisibility,
|
||||
loading = backgroundProcessesLoading,
|
||||
stoppingProcessIds = stoppingProcessIds,
|
||||
onRefresh = chatViewModel::refreshBackgroundProcesses,
|
||||
onStop = chatViewModel::stopBackgroundProcess,
|
||||
onDismissProcess = chatViewModel::dismissBackgroundProcess,
|
||||
onDismiss = { showBackgroundProcesses = false },
|
||||
onOpenSubagentChild = chatViewModel::openSubagentChildPreview,
|
||||
onDismiss = {
|
||||
chatViewModel.closeSubagentChildPreview()
|
||||
showBackgroundProcesses = false
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4978,6 +5067,7 @@ private fun ChatColdStartLoadingState(
|
||||
streamingIntensity: Float,
|
||||
toolCallBurst: Float,
|
||||
connectionLabel: String?,
|
||||
agentDisplayName: String,
|
||||
chatMode: ChatMode,
|
||||
apiReachable: Boolean,
|
||||
chatReady: Boolean,
|
||||
@@ -4985,13 +5075,14 @@ private fun ChatColdStartLoadingState(
|
||||
isLoadingSessions: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
dashboardRouteMovedHint: String?,
|
||||
onNavigateToManage: () -> Unit,
|
||||
onNavigateToDashboardSignIn: () -> Unit,
|
||||
onNavigateToConnections: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val commands = remember(
|
||||
connectionLabel,
|
||||
agentDisplayName,
|
||||
chatMode,
|
||||
apiReachable,
|
||||
chatReady,
|
||||
@@ -5001,6 +5092,7 @@ private fun ChatColdStartLoadingState(
|
||||
buildChatLoadingCommands(
|
||||
context = context,
|
||||
connectionLabel = connectionLabel,
|
||||
agentDisplayName = agentDisplayName,
|
||||
chatMode = chatMode,
|
||||
apiReachable = apiReachable,
|
||||
chatReady = chatReady,
|
||||
@@ -5054,38 +5146,14 @@ private fun ChatColdStartLoadingState(
|
||||
val dashboardSignInRequired =
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired && !apiReachable
|
||||
if (dashboardSignInRequired) {
|
||||
ElevatedCard(
|
||||
colors = CardDefaults.elevatedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.92f),
|
||||
),
|
||||
ChatDashboardSignInCard(
|
||||
dashboardRouteMovedHint = dashboardRouteMovedHint,
|
||||
onNavigateToDashboardSignIn = onNavigateToDashboardSignIn,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_signin_required_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = dashboardRouteMovedHint?.let { route ->
|
||||
stringResource(R.string.dashboard_signin_route_hint, route)
|
||||
} ?: stringResource(R.string.chat_settings_gateway_needs_signin_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = onNavigateToManage,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.voice_settings_sign_in_via_manage))
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
ChatLoadingCommandPanel(
|
||||
commands = commands,
|
||||
@@ -5099,9 +5167,47 @@ private fun ChatColdStartLoadingState(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChatDashboardSignInCard(
|
||||
dashboardRouteMovedHint: String?,
|
||||
onNavigateToDashboardSignIn: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
ElevatedCard(
|
||||
colors = CardDefaults.elevatedCardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.92f),
|
||||
),
|
||||
modifier = modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_signin_required_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = dashboardRouteMovedHint?.let { route ->
|
||||
stringResource(R.string.dashboard_signin_route_hint, route)
|
||||
} ?: stringResource(R.string.chat_settings_gateway_needs_signin_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = onNavigateToDashboardSignIn,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.cw_sign_in_to_hermes))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildChatLoadingCommands(
|
||||
context: android.content.Context,
|
||||
connectionLabel: String?,
|
||||
agentDisplayName: String,
|
||||
chatMode: ChatMode,
|
||||
apiReachable: Boolean,
|
||||
chatReady: Boolean,
|
||||
@@ -5130,12 +5236,16 @@ private fun buildChatLoadingCommands(
|
||||
),
|
||||
ChatLoadingCommand(
|
||||
state = when {
|
||||
apiReachable -> ChatLoadingCommandState.Done
|
||||
chatReady -> ChatLoadingCommandState.Done
|
||||
hasConnection -> ChatLoadingCommandState.Active
|
||||
else -> ChatLoadingCommandState.Pending
|
||||
},
|
||||
command = "/hermes ping",
|
||||
detail = if (apiReachable) "online" else context.getString(R.string.chat_contacting_server),
|
||||
command = "/gateway wake",
|
||||
detail = if (chatReady) {
|
||||
"${agentDisplayName.ifBlank { "Hermes" }} online"
|
||||
} else {
|
||||
"waking ${agentDisplayName.ifBlank { "Hermes" }}"
|
||||
},
|
||||
),
|
||||
ChatLoadingCommand(
|
||||
state = when {
|
||||
@@ -5143,8 +5253,13 @@ private fun buildChatLoadingCommands(
|
||||
apiReachable || isLoadingHistory || isLoadingSessions -> ChatLoadingCommandState.Active
|
||||
else -> ChatLoadingCommandState.Pending
|
||||
},
|
||||
command = "/chat hydrate",
|
||||
detail = if (chatReady) "ready via $chatModeDetail" else "loading conversation",
|
||||
command = "/sessions load",
|
||||
detail = when {
|
||||
isLoadingSessions -> context.getString(R.string.drawer_loading_sessions)
|
||||
isLoadingHistory -> context.getString(R.string.chat_loading_messages)
|
||||
chatReady -> "ready via $chatModeDetail"
|
||||
else -> "waiting for gateway"
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -549,7 +549,7 @@ fun ChatSettingsScreen(
|
||||
val settingsContext = LocalContext.current
|
||||
val notifyPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { /* Notifier re-checks the grant at post time. */ }
|
||||
) { granted -> connectionViewModel.setNotifyTurnComplete(granted) }
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
|
||||
+447
-103
@@ -1,6 +1,8 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
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
|
||||
@@ -14,13 +16,20 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Chat
|
||||
import androidx.compose.material.icons.filled.ChevronRight
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.QrCodeScanner
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Badge
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
@@ -43,28 +52,38 @@ 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.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
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.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.ui.components.ActiveCardAdvancedSection
|
||||
import com.hermesandroid.relay.ui.components.ActiveCardFeaturesSection
|
||||
import com.hermesandroid.relay.ui.components.ActiveCardRoutesSection
|
||||
import com.hermesandroid.relay.ui.components.ActiveCardSecurityPosture
|
||||
import com.hermesandroid.relay.ui.components.ApiServerInfoSheet
|
||||
import com.hermesandroid.relay.ui.components.DashboardAddressEditorDialog
|
||||
import com.hermesandroid.relay.ui.components.InsecureConnectionAckDialog
|
||||
import com.hermesandroid.relay.ui.components.RelayInfoSheet
|
||||
import com.hermesandroid.relay.ui.components.SessionInfoSheet
|
||||
import com.hermesandroid.relay.ui.components.sameGatewayRouteBase
|
||||
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
||||
import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
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 kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Tabbed detail for a single Hermes connection — the level-2 screen the
|
||||
@@ -75,10 +94,9 @@ import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
* - TopAppBar: back + connection label + an `Active` badge (active conn) +
|
||||
* an overflow `⋮` menu (Rename / Re-pair / Revoke / Remove).
|
||||
* - When this connection is the **active** one, a 4-tab segmented bar:
|
||||
* **Overview** (status header + the steps/timeline capability list) ·
|
||||
* **Routes** (ADR 24 endpoint management) · **Advanced** (manual URL /
|
||||
* insecure / manual pairing) · **Security** (transport posture + the
|
||||
* prominent Relay sessions entry).
|
||||
* **Overview** (current route + capability outcomes) · **Routes** (ADR 24
|
||||
* endpoint management) · **Access** (transport posture + Relay sessions) ·
|
||||
* **Advanced** (manual URL / insecure / manual pairing).
|
||||
* - When this connection is **not** active, only Overview shows — the deep
|
||||
* live content reads the single active-connection VM state, so we surface
|
||||
* a "Switch to this connection" CTA instead of stale/foreign data.
|
||||
@@ -105,34 +123,41 @@ fun ConnectionDetailScreen(
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val snackbarHost = LocalSnackbarHost.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val routeResetFailed = stringResource(R.string.active_section_use_selected_route_failed)
|
||||
|
||||
val connections by connectionViewModel.connections.collectAsState()
|
||||
val connectionsHydrated by connectionViewModel.connectionsHydrated.collectAsState()
|
||||
val activeConnectionId by connectionViewModel.activeConnectionId.collectAsState()
|
||||
val relayUiState by connectionViewModel.relayUiState.collectAsState()
|
||||
val connection = connections.firstOrNull { it.id == connectionId }
|
||||
// Connection was removed (e.g. via the overflow menu) — leave the screen.
|
||||
LaunchedEffect(connection == null) {
|
||||
if (connection == null) onBack()
|
||||
if (!connectionsHydrated) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
return
|
||||
}
|
||||
// Connection was removed (e.g. via the overflow menu) — leave the screen
|
||||
// only after the store has authoritatively hydrated.
|
||||
LaunchedEffect(connectionsHydrated, connection == null) {
|
||||
if (connectionsHydrated && connection == null) onBack()
|
||||
}
|
||||
if (connection == null) return
|
||||
|
||||
val isActive = connectionId == activeConnectionId
|
||||
|
||||
// Screen-scoped sheet/dialog visibility (survives tab switches + scroll).
|
||||
var showSessionInfoSheet by remember { mutableStateOf(false) }
|
||||
var showApiInfoSheet by remember { mutableStateOf(false) }
|
||||
var showRelayInfoSheet by remember { mutableStateOf(false) }
|
||||
var showInsecureAckDialog by remember { mutableStateOf(false) }
|
||||
var showRenameDialog by remember { mutableStateOf(false) }
|
||||
var showDashboardEditor by remember { mutableStateOf(false) }
|
||||
var showRevokeConfirm by remember { mutableStateOf(false) }
|
||||
var showRemoveConfirm by remember { mutableStateOf(false) }
|
||||
var menuExpanded by remember { mutableStateOf(false) }
|
||||
|
||||
val tabs = if (isActive) {
|
||||
listOf(DetailTab.Overview, DetailTab.Routes, DetailTab.Advanced, DetailTab.Security)
|
||||
} else {
|
||||
listOf(DetailTab.Overview)
|
||||
}
|
||||
val tabs = detailTabs(isActive)
|
||||
// Reset selection when the active/non-active shape changes so we never
|
||||
// index past the available tabs.
|
||||
var selectedTab by remember(isActive) { mutableStateOf(0) }
|
||||
@@ -247,8 +272,8 @@ fun ConnectionDetailScreen(
|
||||
Text(when (tab) {
|
||||
DetailTab.Overview -> stringResource(R.string.detail_tab_overview)
|
||||
DetailTab.Routes -> stringResource(R.string.detail_tab_routes)
|
||||
DetailTab.Access -> stringResource(R.string.detail_tab_access)
|
||||
DetailTab.Advanced -> stringResource(R.string.detail_tab_advanced)
|
||||
DetailTab.Security -> stringResource(R.string.detail_tab_security)
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -276,7 +301,11 @@ fun ConnectionDetailScreen(
|
||||
onOpenApiInfo = { showApiInfoSheet = true },
|
||||
onOpenDashboard = onNavigateToManage,
|
||||
onOpenRelayInfo = { showRelayInfoSheet = true },
|
||||
onOpenSessionInfo = { showSessionInfoSheet = true },
|
||||
onOpenRoutes = {
|
||||
selectedTab = tabs.indexOf(DetailTab.Routes)
|
||||
.takeIf { it >= 0 }
|
||||
?: selectedTab
|
||||
},
|
||||
)
|
||||
} else {
|
||||
InactiveOverview(
|
||||
@@ -291,8 +320,22 @@ fun ConnectionDetailScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
connection = connection,
|
||||
liveState = relayUiState,
|
||||
onEditDashboard = {
|
||||
selectedTab = tabs.indexOf(DetailTab.Advanced)
|
||||
onEditDashboard = { showDashboardEditor = true },
|
||||
)
|
||||
|
||||
DetailTab.Access -> ActiveCardSecurityPosture(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onNavigateToPairedDevices = onNavigateToPairedDevices,
|
||||
onRevokeRelay = { showRevokeConfirm = true },
|
||||
onOpenDashboardSignIn = onNavigateToManage,
|
||||
onUseSelectedRoute = {
|
||||
connectionViewModel.useSelectedDashboardRoute { result ->
|
||||
result.onFailure {
|
||||
scope.launch {
|
||||
snackbarHost.showSnackbar(routeResetFailed)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -302,12 +345,6 @@ fun ConnectionDetailScreen(
|
||||
onPairRelay = { onRepair(connectionId) },
|
||||
onInsecureAckRequested = { showInsecureAckDialog = true },
|
||||
)
|
||||
|
||||
DetailTab.Security -> ActiveCardSecurityPosture(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onNavigateToPairedDevices = onNavigateToPairedDevices,
|
||||
onRevokeRelay = { showRevokeConfirm = true },
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
@@ -316,12 +353,6 @@ fun ConnectionDetailScreen(
|
||||
}
|
||||
|
||||
// ── Screen-scope sheets + dialogs ────────────────────────────────────
|
||||
if (showSessionInfoSheet) {
|
||||
SessionInfoSheet(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onDismiss = { showSessionInfoSheet = false },
|
||||
)
|
||||
}
|
||||
if (showApiInfoSheet) {
|
||||
ApiServerInfoSheet(
|
||||
connectionViewModel = connectionViewModel,
|
||||
@@ -344,6 +375,15 @@ fun ConnectionDetailScreen(
|
||||
onCancel = { showInsecureAckDialog = false },
|
||||
)
|
||||
}
|
||||
if (showDashboardEditor) {
|
||||
DashboardAddressEditorDialog(
|
||||
initialUrl = connection.resolvedDashboardUrl,
|
||||
onSave = { dashboardUrl, onResult ->
|
||||
connectionViewModel.updateDashboardAddress(dashboardUrl, onResult)
|
||||
},
|
||||
onDismiss = { showDashboardEditor = false },
|
||||
)
|
||||
}
|
||||
if (showRenameDialog) {
|
||||
RenameConnectionDialog(
|
||||
initialLabel = connection.label,
|
||||
@@ -400,17 +440,22 @@ fun ConnectionDetailScreen(
|
||||
}
|
||||
}
|
||||
|
||||
private enum class DetailTab {
|
||||
internal enum class DetailTab {
|
||||
Overview,
|
||||
Routes,
|
||||
Access,
|
||||
Advanced,
|
||||
Security,
|
||||
}
|
||||
|
||||
internal fun detailTabs(isActive: Boolean): List<DetailTab> = if (isActive) {
|
||||
listOf(DetailTab.Overview, DetailTab.Routes, DetailTab.Access, DetailTab.Advanced)
|
||||
} else {
|
||||
listOf(DetailTab.Overview)
|
||||
}
|
||||
|
||||
/**
|
||||
* Overview for the **active** connection: a one-line status header followed
|
||||
* by the steps/timeline capability list ([ActiveCardFeaturesSection]) and
|
||||
* quick actions. The timeline is intentionally the hero of this tab.
|
||||
* Overview for the **active** connection: the selected route, the three
|
||||
* standard upstream outcomes, and optional Relay/API drill-down rows.
|
||||
*/
|
||||
@Composable
|
||||
private fun ActiveOverview(
|
||||
@@ -422,80 +467,165 @@ private fun ActiveOverview(
|
||||
onOpenApiInfo: () -> Unit,
|
||||
onOpenDashboard: () -> Unit,
|
||||
onOpenRelayInfo: () -> Unit,
|
||||
onOpenSessionInfo: () -> Unit,
|
||||
onOpenRoutes: () -> Unit,
|
||||
) {
|
||||
val hostname = connection.primaryHost.ifBlank { connection.label }
|
||||
val dashboardReady = connection.dashboardLastStatus?.reachable == true
|
||||
val gatewayAvailability by connectionViewModel.gatewayAvailability.collectAsState()
|
||||
val apiReachable by connectionViewModel.apiServerReachable.collectAsState()
|
||||
val apiHealth by connectionViewModel.apiServerHealth.collectAsState()
|
||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||
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) {
|
||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||
} else {
|
||||
effectiveDashboardUrl
|
||||
}
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
val route = resolveDetailRoutePresentation(
|
||||
activeEndpoint = activeEndpoint,
|
||||
effectiveDashboardUrl = currentRouteUrl,
|
||||
)
|
||||
val routeStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
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 ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
val dashboardStatus = connection.dashboardLastStatus
|
||||
val dashboardSignInRequired =
|
||||
dashboardStatus?.authRequired == true && dashboardStatus.authenticated != true
|
||||
val manageStatus = when {
|
||||
connection.resolvedDashboardUrl.isBlank() ->
|
||||
OverviewStatus(stringResource(R.string.active_section_missing), OverviewTone.Warning)
|
||||
dashboardStatus == null ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unchecked), OverviewTone.Neutral)
|
||||
!dashboardStatus.reachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
dashboardSignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
}
|
||||
val voiceStatus = when (standardVoiceAvailability) {
|
||||
StandardVoiceAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
StandardVoiceAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
StandardVoiceAvailability.Unsupported ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||
StandardVoiceAvailability.Unreachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
StandardVoiceAvailability.Unknown ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
val relayStatus = when (relayUiState) {
|
||||
RelayUiState.NotConfigured ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_optional), OverviewTone.Neutral)
|
||||
RelayUiState.Connected ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_ready), OverviewTone.Good)
|
||||
RelayUiState.Connecting ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_reconnecting), OverviewTone.Info)
|
||||
RelayUiState.Stale,
|
||||
RelayUiState.Disconnected ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_unavailable), OverviewTone.Warning)
|
||||
RelayUiState.Expired ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_needs_repair), OverviewTone.Warning)
|
||||
}
|
||||
val apiStatus = when (
|
||||
resolveOptionalApiPresentation(
|
||||
gatewayReady = gatewayAvailability == GatewayAvailability.Ready,
|
||||
apiReachable = apiReachable,
|
||||
apiConfigured = connection.apiServerUrl.isNotBlank(),
|
||||
apiProbing = apiHealth == ConnectionViewModel.HealthStatus.Probing,
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Dashboard,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.detail_dashboard_primary),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = connection.resolvedDashboardUrl.ifBlank { hostname },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = if (dashboardReady) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = if (dashboardReady) {
|
||||
stringResource(R.string.detail_core_ready)
|
||||
} else {
|
||||
stringResource(R.string.detail_core_configured)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (dashboardReady) Color(0xFF4CAF50) else MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
OptionalApiPresentation.Checking ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
OptionalApiPresentation.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
OptionalApiPresentation.Optional ->
|
||||
OverviewStatus(stringResource(R.string.relay_state_optional), OverviewTone.Neutral)
|
||||
OptionalApiPresentation.Offline ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.detail_overview_summary),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
text = stringResource(R.string.detail_current_route),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
CurrentRouteOverviewCard(
|
||||
route = route,
|
||||
status = routeStatus,
|
||||
onEdit = onOpenRoutes,
|
||||
)
|
||||
|
||||
ActiveCardFeaturesSection(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onOpenApiInfo = onOpenApiInfo,
|
||||
onOpenDashboard = onOpenDashboard,
|
||||
onOpenRelayInfo = onOpenRelayInfo,
|
||||
onOpenSessionInfo = onOpenSessionInfo,
|
||||
onPairRelay = onRepair,
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
OverviewCapabilityCard(
|
||||
icon = Icons.Filled.Chat,
|
||||
label = stringResource(R.string.conn_chat_label),
|
||||
status = chatStatus,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
OverviewCapabilityCard(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
label = stringResource(R.string.conn_manage_label),
|
||||
status = manageStatus,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = onOpenDashboard,
|
||||
)
|
||||
OverviewCapabilityCard(
|
||||
icon = Icons.Filled.GraphicEq,
|
||||
label = stringResource(R.string.conn_voice_label),
|
||||
status = voiceStatus,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = if (
|
||||
standardVoiceAvailability == StandardVoiceAvailability.SignInRequired
|
||||
) {
|
||||
onOpenDashboard
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider(modifier = Modifier.padding(top = 4.dp))
|
||||
OverviewOptionalRow(
|
||||
icon = Icons.Filled.Link,
|
||||
label = stringResource(R.string.active_section_relay_connected_features),
|
||||
description = stringResource(R.string.active_section_relay_optional_summary),
|
||||
status = relayStatus,
|
||||
onClick = if (relayConfigured) onOpenRelayInfo else onRepair,
|
||||
)
|
||||
HorizontalDivider()
|
||||
OverviewOptionalRow(
|
||||
icon = Icons.Filled.Code,
|
||||
label = stringResource(R.string.api_fallback_title),
|
||||
description = stringResource(R.string.active_section_api_not_required),
|
||||
status = apiStatus,
|
||||
onClick = onOpenApiInfo,
|
||||
)
|
||||
|
||||
Row(
|
||||
@@ -508,6 +638,220 @@ private fun ActiveOverview(
|
||||
}
|
||||
}
|
||||
|
||||
private enum class OverviewTone { Neutral, Good, Info, Warning }
|
||||
|
||||
internal enum class OptionalApiPresentation { Checking, Ready, Optional, Offline }
|
||||
|
||||
internal fun resolveOptionalApiPresentation(
|
||||
gatewayReady: Boolean,
|
||||
apiReachable: Boolean,
|
||||
apiConfigured: Boolean,
|
||||
apiProbing: Boolean,
|
||||
): OptionalApiPresentation = when {
|
||||
apiProbing -> OptionalApiPresentation.Checking
|
||||
apiReachable -> OptionalApiPresentation.Ready
|
||||
gatewayReady || !apiConfigured -> OptionalApiPresentation.Optional
|
||||
else -> OptionalApiPresentation.Offline
|
||||
}
|
||||
|
||||
private data class OverviewStatus(
|
||||
val text: String,
|
||||
val tone: OverviewTone,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun overviewStatusColor(status: OverviewStatus): Color = when (status.tone) {
|
||||
OverviewTone.Good -> com.hermesandroid.relay.ui.theme.RelayRefresh.Green
|
||||
OverviewTone.Info -> MaterialTheme.colorScheme.primary
|
||||
OverviewTone.Warning -> MaterialTheme.colorScheme.error
|
||||
OverviewTone.Neutral -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
|
||||
internal data class DetailRoutePresentation(
|
||||
val label: String,
|
||||
val address: String,
|
||||
)
|
||||
|
||||
internal fun resolveDetailRoutePresentation(
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
effectiveDashboardUrl: String,
|
||||
): DetailRoutePresentation {
|
||||
val candidateGatewayUrl = activeEndpoint?.gatewayRouteUrl()
|
||||
val address = effectiveDashboardUrl.trim().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
?: candidateGatewayUrl.orEmpty()
|
||||
val candidateOwnsAddress = candidateGatewayUrl != null &&
|
||||
address.isNotBlank() &&
|
||||
sameGatewayRouteBase(candidateGatewayUrl, address)
|
||||
val inferredRole = activeEndpoint?.role
|
||||
?.lowercase()
|
||||
?.takeIf { candidateOwnsAddress }
|
||||
?: Connection.inferRouteRole(address)
|
||||
val role = when (inferredRole) {
|
||||
"lan" -> "LAN"
|
||||
"tailscale" -> "Tailscale"
|
||||
"public" -> "Public"
|
||||
"https" -> "Public"
|
||||
"dashboard", "authenticated_dashboard" -> "Dashboard"
|
||||
else -> activeEndpoint?.displayLabel()?.takeIf { candidateOwnsAddress } ?: "Gateway"
|
||||
}
|
||||
val transport = when {
|
||||
address.startsWith("https://", ignoreCase = true) -> "HTTPS"
|
||||
address.startsWith("http://", ignoreCase = true) -> "HTTP"
|
||||
else -> null
|
||||
}
|
||||
val label = transport?.let { if (role.equals(it, ignoreCase = true)) role else "$role ($it)" }
|
||||
?: role
|
||||
return DetailRoutePresentation(label = label, address = address)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CurrentRouteOverviewCard(
|
||||
route: DetailRoutePresentation,
|
||||
status: OverviewStatus,
|
||||
onEdit: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Language,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(26.dp),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(text = route.label, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
text = status.text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = overviewStatusColor(status),
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onEdit) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Edit,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.size(6.dp))
|
||||
Text(stringResource(R.string.active_section_edit))
|
||||
}
|
||||
}
|
||||
Text(
|
||||
text = route.address.ifBlank { stringResource(R.string.active_section_not_configured) },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverviewCapabilityCard(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
status: OverviewStatus,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: (() -> Unit)? = null,
|
||||
) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = modifier.then(
|
||||
if (onClick != null) {
|
||||
Modifier.clickable(onClickLabel = label, onClick = onClick)
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = status.text,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = overviewStatusColor(status),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverviewOptionalRow(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
description: String,
|
||||
status: OverviewStatus,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClickLabel = label, onClick = onClick)
|
||||
.padding(vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(text = label, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
text = description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = status.text,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = overviewStatusColor(status),
|
||||
maxLines = 1,
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overview for a **non-active** connection. The deep live content reads the
|
||||
* single active-connection VM state, so rather than show stale/foreign data
|
||||
|
||||
+524
-428
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -248,7 +248,11 @@ fun DiagnosticsScreen(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
supportReview = withContext(Dispatchers.IO) {
|
||||
buildSupportReviewState(ReliabilityCenter.reports(context))
|
||||
buildSupportReviewState(
|
||||
reports = ReliabilityCenter.reports(context),
|
||||
diagnostics = entries,
|
||||
environment = ReliabilityCenter.environment(),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
@@ -52,6 +53,7 @@ import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
@@ -68,6 +70,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
@@ -98,7 +101,11 @@ private data class DisplayFile(
|
||||
/** First-class native Git workspace backed by the optional Relay contribution. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
fun GitStateScreen(
|
||||
viewModel: GitStateViewModel,
|
||||
onScanningEnabledChange: (Boolean) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val reposState by viewModel.repos.collectAsState()
|
||||
val detailState by viewModel.detail.collectAsState()
|
||||
val contentState by viewModel.content.collectAsState()
|
||||
@@ -107,6 +114,7 @@ fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
val stashNotice by viewModel.stashNotice.collectAsState()
|
||||
val hasGrant by viewModel.writeGrant.collectAsState()
|
||||
val selectedRepoId by viewModel.selectedRepoId.collectAsState()
|
||||
val scanningEnabled by viewModel.scanningEnabled.collectAsState()
|
||||
|
||||
// A path can be staged and modified at the same time. Keep the category in
|
||||
// the selection identity so selecting one row never silently selects the
|
||||
@@ -122,6 +130,10 @@ fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
var pushAfter by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingConfirm by remember { mutableStateOf<ConfirmationRequest?>(null) }
|
||||
|
||||
LaunchedEffect(scanningEnabled) {
|
||||
if (scanningEnabled) viewModel.loadRepos()
|
||||
}
|
||||
|
||||
val repos = (reposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
val selectedRepo = repos.firstOrNull { it.id == selectedRepoId }
|
||||
val detail = detailState as? GitRepoDetailState.Ready
|
||||
@@ -190,21 +202,23 @@ fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
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 })
|
||||
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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (detail != null) {
|
||||
if (scanningEnabled && detail != null) {
|
||||
Surface(shadowElevation = 8.dp, tonalElevation = 2.dp) {
|
||||
Column {
|
||||
if (selection.isNotEmpty()) {
|
||||
@@ -229,47 +243,55 @@ fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.padding(padding), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.padding(padding), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.padding(padding), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.padding(padding), false, "No Git repositories found", "Add a repository to the host's configured Git roots, then refresh.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.padding(padding), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
modifier = Modifier.padding(padding),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
selection = selection,
|
||||
onToggleSelected = { file ->
|
||||
selection = if (file in selection) selection - file else selection + file
|
||||
},
|
||||
expandedPath = expandedPath,
|
||||
contentMode = contentMode,
|
||||
contentState = contentState,
|
||||
onOpen = { file, mode ->
|
||||
if (file.filter != FileFilter.Untracked) {
|
||||
val opening = expandedPath != file.path || contentMode != mode
|
||||
expandedPath = if (opening) file.path else null
|
||||
contentMode = mode
|
||||
if (opening) {
|
||||
if (mode == ContentMode.File) viewModel.loadFile(file.path)
|
||||
else viewModel.loadDiff(file.path, if (file.filter == FileFilter.Staged) "staged" else "unstaged")
|
||||
}
|
||||
}
|
||||
},
|
||||
onFetch = viewModel::fetch,
|
||||
onPull = viewModel::pull,
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
GitScanningConsentCard(
|
||||
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(
|
||||
modifier = Modifier.weight(1f),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
selection = selection,
|
||||
onToggleSelected = { file ->
|
||||
selection = if (file in selection) selection - file else selection + file
|
||||
},
|
||||
expandedPath = expandedPath,
|
||||
contentMode = contentMode,
|
||||
contentState = contentState,
|
||||
onOpen = { file, mode ->
|
||||
if (file.filter != FileFilter.Untracked) {
|
||||
val opening = expandedPath != file.path || contentMode != mode
|
||||
expandedPath = if (opening) file.path else null
|
||||
contentMode = mode
|
||||
if (opening) {
|
||||
if (mode == ContentMode.File) viewModel.loadFile(file.path)
|
||||
else viewModel.loadDiff(file.path, if (file.filter == FileFilter.Staged) "staged" else "unstaged")
|
||||
}
|
||||
}
|
||||
},
|
||||
onFetch = viewModel::fetch,
|
||||
onPull = viewModel::pull,
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,6 +339,51 @@ fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GitScanningConsentCard(
|
||||
enabled: Boolean,
|
||||
onEnabledChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.toggleable(
|
||||
value = enabled,
|
||||
role = Role.Switch,
|
||||
onValueChange = onEnabledChange,
|
||||
),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(Icons.Filled.AccountTree, contentDescription = null)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.git_state_host_scanning),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (enabled) {
|
||||
R.string.git_state_host_scanning_on_desc
|
||||
} else {
|
||||
R.string.git_state_host_scanning_off_desc
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(checked = enabled, onCheckedChange = null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WorkspaceBody(
|
||||
modifier: Modifier,
|
||||
|
||||
@@ -48,7 +48,7 @@ private const val PAIR_SETUP_TIMEOUT_MS = 15_000L
|
||||
* Full-screen connection route. Wraps [ConnectionWizard] in a real Scaffold so
|
||||
* the chooser tiles, manual-entry forms, and camera viewport all get the
|
||||
* actual window — not a Compose Dialog that leaked the Settings cards
|
||||
* underneath. Reached via Settings → Connections → Add/Pair Relay (or any "Re-pair"
|
||||
* underneath. Reached via Settings → Gateways → Access → Pair Relay (or any "Re-pair"
|
||||
* button), and pops back to wherever it came from on complete or cancel.
|
||||
*
|
||||
* [autoStart] lets the caller deep-link into a specific pair method. When
|
||||
@@ -70,8 +70,8 @@ fun PairScreen(
|
||||
onConnectionTargetChanged: (String) -> Unit = {},
|
||||
/**
|
||||
* Optional offline "Try the demo" entry, forwarded to [ConnectionWizard].
|
||||
* Wired by [RelayApp] only for the bare Connect entry (no placeholder
|
||||
* connection in flight); null on add-connection / re-pair flows.
|
||||
* Wired by [RelayApp] only for the bare Connect entry (no connection draft
|
||||
* in flight); null on add-connection / re-pair flows.
|
||||
*/
|
||||
onTryDemo: (() -> Unit)? = null,
|
||||
) {
|
||||
@@ -88,12 +88,10 @@ fun PairScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// Route system back / predictive back through the same discard path
|
||||
// Route system back / predictive back through the same draft-discard path
|
||||
// the TopAppBar arrow uses. Without this, the NavController just pops
|
||||
// the backstack and [RelayApp]'s wired `discardPlaceholderConnection`
|
||||
// in the Pair route's `onCancel` never fires — leaving the placeholder
|
||||
// orphaned in the connection list. Matches the defensive sweep in
|
||||
// [ConnectionViewModel.init] but fires at the right moment.
|
||||
// in the Pair route's `onCancel` never fires.
|
||||
BackHandler(enabled = true) { onCancel() }
|
||||
|
||||
Scaffold(
|
||||
|
||||
@@ -172,6 +172,7 @@ fun SettingsScreen(
|
||||
// `connection · model · personality` without re-reading ChatViewModel
|
||||
// state from a different place.
|
||||
chatViewModel: ChatViewModel,
|
||||
gitRepoScanningEnabled: Boolean,
|
||||
// (The `onNavigateToChatWithAgentSheet` param that used to live here
|
||||
// was removed as part of the 2026-04-21 pairing-audit fix. Tapping the
|
||||
// Active Agent card now opens the consolidated AgentInfoSheet INLINE
|
||||
@@ -608,7 +609,13 @@ fun SettingsScreen(
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
title = stringResource(R.string.settings_git_workspace),
|
||||
subtitle = stringResource(R.string.settings_git_workspace_desc),
|
||||
subtitle = stringResource(
|
||||
if (gitRepoScanningEnabled) {
|
||||
R.string.settings_git_workspace_desc
|
||||
} else {
|
||||
R.string.settings_git_workspace_off_desc
|
||||
},
|
||||
),
|
||||
onClick = onNavigateToGitWorkspace,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
@@ -1017,7 +1024,7 @@ private fun QuickControlsCard(
|
||||
val context = LocalContext.current
|
||||
val notificationPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { /* Posting re-checks the grant. */ }
|
||||
) { granted -> connectionViewModel.setNotifyTurnComplete(granted) }
|
||||
val requestNotificationPermission = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
androidx.core.content.ContextCompat.checkSelfPermission(
|
||||
|
||||
@@ -257,7 +257,10 @@ private fun classifyErrorInternal(t: Throwable?, context: String?, ctx: Context?
|
||||
|
||||
val msg = t.message.orEmpty().lowercase()
|
||||
|
||||
if ("cannot create audiorecord" in msg || "audiorecord failed to initialize" in msg) {
|
||||
if ("cannot create audiorecord" in msg ||
|
||||
"audiorecord failed to initialize" in msg ||
|
||||
"microphone is in use by another voice feature" in msg
|
||||
) {
|
||||
return HumanError(
|
||||
title = ctx?.getString(R.string.error_classify_mic_unavailable) ?: "Microphone unavailable",
|
||||
body = ctx?.getString(R.string.error_classify_mic_unavailable_body)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+12
@@ -102,6 +102,18 @@ internal class ConversationBindingController {
|
||||
)
|
||||
}
|
||||
|
||||
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
|
||||
fun startFreshDraft() {
|
||||
val current = _state.value
|
||||
if (!current.isBound) return
|
||||
if (current.sessionId == null && current.hasExplicitOwner) return
|
||||
_state.value = current.copy(
|
||||
sessionId = null,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
}
|
||||
|
||||
fun releaseExplicitOwner() {
|
||||
if (!_state.value.hasExplicitOwner) return
|
||||
reset()
|
||||
|
||||
@@ -109,6 +109,8 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
|
||||
private val _selectedRepoId = MutableStateFlow<String?>(null)
|
||||
val selectedRepoId: StateFlow<String?> = _selectedRepoId.asStateFlow()
|
||||
private val _scanningEnabled = MutableStateFlow(false)
|
||||
val scanningEnabled: StateFlow<Boolean> = _scanningEnabled.asStateFlow()
|
||||
|
||||
private var api: GitStateApiClient? = null
|
||||
private var reposJob: Job? = null
|
||||
@@ -118,31 +120,33 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
private var messageJob: Job? = null
|
||||
private var scopeKey: 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)
|
||||
}
|
||||
|
||||
fun configure(dashboard: DashboardApiClient?, ownerKey: String?) {
|
||||
reposJob?.cancel()
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
mutationJob?.cancel()
|
||||
messageJob?.cancel()
|
||||
fun configure(
|
||||
dashboard: DashboardApiClient?,
|
||||
ownerKey: String?,
|
||||
scanningEnabled: Boolean,
|
||||
) {
|
||||
clearWorkspaceState()
|
||||
targetGeneration += 1
|
||||
scopeKey = ownerKey
|
||||
_selectedRepoId.value = null
|
||||
_scanningEnabled.value = scanningEnabled
|
||||
_writeGrant.value = false
|
||||
_detail.value = GitRepoDetailState.Idle
|
||||
_content.value = GitContentViewState.Idle
|
||||
_mutation.value = GitMutationState.Idle
|
||||
_messageGeneration.value = GitMessageGenerationState.Idle
|
||||
_stashNotice.value = null
|
||||
api = dashboard?.let(::GitStateApiClient)
|
||||
loadRepos()
|
||||
}
|
||||
|
||||
fun setScanningEnabled(enabled: Boolean) {
|
||||
if (_scanningEnabled.value == enabled) return
|
||||
_scanningEnabled.value = enabled
|
||||
if (!enabled) clearWorkspaceState()
|
||||
}
|
||||
|
||||
/** Grants the plugin.api.write capability for this connection/profile. */
|
||||
@@ -154,6 +158,7 @@ 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
|
||||
@@ -187,7 +192,23 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearWorkspaceState() {
|
||||
reposJob?.cancel()
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
mutationJob?.cancel()
|
||||
messageJob?.cancel()
|
||||
_repos.value = GitStateUiState.Loading
|
||||
_detail.value = GitRepoDetailState.Idle
|
||||
_content.value = GitContentViewState.Idle
|
||||
_mutation.value = GitMutationState.Idle
|
||||
_messageGeneration.value = GitMessageGenerationState.Idle
|
||||
_stashNotice.value = null
|
||||
_selectedRepoId.value = null
|
||||
}
|
||||
|
||||
fun selectRepo(repoId: String) {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: return
|
||||
targetGeneration += 1
|
||||
_selectedRepoId.value = repoId
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.GatewaySubagentEvent
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
internal enum class SubagentActivityPhase {
|
||||
STARTED,
|
||||
THINKING,
|
||||
TOOL,
|
||||
PROGRESS,
|
||||
COMPLETED,
|
||||
FAILED,
|
||||
INTERRUPTED,
|
||||
ENDED_WITH_PARENT,
|
||||
}
|
||||
|
||||
internal enum class SubagentActivityEventKind { STARTED, UPDATE, TOOL, COMPLETED }
|
||||
|
||||
internal data class SubagentActivityEvent(
|
||||
val sequence: Long,
|
||||
val kind: SubagentActivityEventKind,
|
||||
val text: String? = null,
|
||||
val toolName: String? = null,
|
||||
val phase: SubagentActivityPhase,
|
||||
val observedAtMillis: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* A bounded, ephemeral projection of parent-session `subagent.*` events.
|
||||
*
|
||||
* This is intentionally not a child transcript. Upstream currently exposes no
|
||||
* durable child-session key or child-history route, so the projection is owned
|
||||
* by the exact profile-scoped parent session and parent turn that emitted it.
|
||||
*/
|
||||
internal data class SubagentActivity(
|
||||
val laneId: Long,
|
||||
val turnId: String,
|
||||
val taskIndex: Int,
|
||||
val taskCount: Int,
|
||||
val goal: String,
|
||||
val subagentId: String? = null,
|
||||
val childSessionId: String? = null,
|
||||
val parentId: String? = null,
|
||||
val depth: Int? = null,
|
||||
val model: String? = null,
|
||||
val profile: String? = null,
|
||||
val phase: SubagentActivityPhase,
|
||||
val summary: String? = null,
|
||||
val durationSeconds: Double? = null,
|
||||
val events: List<SubagentActivityEvent> = emptyList(),
|
||||
val truncated: Boolean = false,
|
||||
val partialAfterGap: Boolean = false,
|
||||
val revision: Long = 0L,
|
||||
) {
|
||||
val stableKey: String
|
||||
get() = "$turnId:$laneId"
|
||||
|
||||
val isTerminal: Boolean
|
||||
get() = phase in setOf(
|
||||
SubagentActivityPhase.COMPLETED,
|
||||
SubagentActivityPhase.FAILED,
|
||||
SubagentActivityPhase.INTERRUPTED,
|
||||
SubagentActivityPhase.ENDED_WITH_PARENT,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps live child activity isolated from the unrelated `process.list`
|
||||
* registry. All text is control-sanitized and bounded before entering UI state.
|
||||
*/
|
||||
internal class SubagentActivityController(
|
||||
private val clock: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
companion object {
|
||||
internal const val MAX_EVENTS_PER_CHILD = 50
|
||||
internal const val MAX_CHARS_PER_CHILD = 32_000
|
||||
internal const val MAX_GOAL_CHARS = 500
|
||||
internal const val MAX_EVENT_TEXT_CHARS = 2_000
|
||||
internal const val MAX_TOOL_NAME_CHARS = 160
|
||||
}
|
||||
|
||||
private val _activities = MutableStateFlow<List<SubagentActivity>>(emptyList())
|
||||
val activities: StateFlow<List<SubagentActivity>> = _activities.asStateFlow()
|
||||
|
||||
private var storedSessionId: String? = null
|
||||
private var scopeKey: String? = null
|
||||
private var activeTurnId: String? = null
|
||||
private var sequence = 0L
|
||||
private var laneSequence = 0L
|
||||
private var connectionWasReady = false
|
||||
private var pendingGap = false
|
||||
|
||||
fun selectSession(sessionId: String?, newScopeKey: String?) {
|
||||
if (storedSessionId == sessionId && scopeKey == newScopeKey) return
|
||||
storedSessionId = sessionId
|
||||
scopeKey = newScopeKey
|
||||
activeTurnId = null
|
||||
sequence = 0L
|
||||
laneSequence = 0L
|
||||
connectionWasReady = false
|
||||
pendingGap = false
|
||||
_activities.value = emptyList()
|
||||
}
|
||||
|
||||
fun resetConnection() {
|
||||
activeTurnId = null
|
||||
sequence = 0L
|
||||
laneSequence = 0L
|
||||
connectionWasReady = false
|
||||
pendingGap = false
|
||||
_activities.value = emptyList()
|
||||
}
|
||||
|
||||
fun onConnectionReady(ready: Boolean) {
|
||||
if (connectionWasReady && !ready && _activities.value.any { !it.isTerminal }) {
|
||||
pendingGap = true
|
||||
}
|
||||
if (ready && pendingGap) {
|
||||
_activities.value = _activities.value.map { activity ->
|
||||
if (activity.isTerminal) activity else activity.copy(
|
||||
partialAfterGap = true,
|
||||
revision = activity.revision + 1,
|
||||
)
|
||||
}
|
||||
pendingGap = false
|
||||
}
|
||||
connectionWasReady = ready
|
||||
}
|
||||
|
||||
fun beginTurn(sessionId: String?, eventScopeKey: String?, turnId: String) {
|
||||
if (sessionId == null || sessionId != storedSessionId || eventScopeKey != scopeKey) return
|
||||
if (activeTurnId == turnId) return
|
||||
activeTurnId = turnId
|
||||
sequence = 0L
|
||||
laneSequence = 0L
|
||||
_activities.value = emptyList()
|
||||
}
|
||||
|
||||
fun onEvent(
|
||||
sessionId: String?,
|
||||
eventScopeKey: String?,
|
||||
turnId: String,
|
||||
event: GatewaySubagentEvent,
|
||||
profile: String? = null,
|
||||
) {
|
||||
if (sessionId == null || sessionId != storedSessionId || eventScopeKey != scopeKey) return
|
||||
if (activeTurnId != turnId) return
|
||||
|
||||
val taskIndex = event.taskIndex.coerceAtLeast(0)
|
||||
val eventIdentity = event.subagentId?.takeIf(String::isNotBlank)
|
||||
?: event.childSessionId?.takeIf(String::isNotBlank)
|
||||
val identityMatch = eventIdentity?.let { identity ->
|
||||
_activities.value.firstOrNull {
|
||||
it.subagentId == identity || it.childSessionId == identity
|
||||
}
|
||||
}
|
||||
val compatibleIndexMatches = _activities.value.filter { activity ->
|
||||
activity.taskIndex == taskIndex &&
|
||||
(event.subagentId.isNullOrBlank() || activity.subagentId.isNullOrBlank() ||
|
||||
event.subagentId == activity.subagentId) &&
|
||||
(event.childSessionId.isNullOrBlank() || activity.childSessionId.isNullOrBlank() ||
|
||||
event.childSessionId == activity.childSessionId) &&
|
||||
(event.parentId.isNullOrBlank() || activity.parentId.isNullOrBlank() ||
|
||||
event.parentId == activity.parentId) &&
|
||||
(event.depth == null || activity.depth == null || event.depth == activity.depth)
|
||||
}
|
||||
val current = identityMatch ?: compatibleIndexMatches.singleOrNull()
|
||||
if (
|
||||
current?.isTerminal == true &&
|
||||
event.phase != GatewaySubagentEvent.Phase.SPAWN_REQUESTED &&
|
||||
event.phase != GatewaySubagentEvent.Phase.START
|
||||
) return
|
||||
|
||||
val base = if (current?.isTerminal == true) null else current
|
||||
val phase = event.toActivityPhase()
|
||||
val goal = sanitize(event.goal, MAX_GOAL_CHARS)
|
||||
val preview = sanitize(event.preview, MAX_EVENT_TEXT_CHARS).ifBlank { null }
|
||||
val summary = sanitize(event.summary, MAX_EVENT_TEXT_CHARS).ifBlank { null }
|
||||
val toolName = sanitize(event.toolName, MAX_TOOL_NAME_CHARS).ifBlank { null }
|
||||
val eventRow = SubagentActivityEvent(
|
||||
sequence = sequence++,
|
||||
kind = when (event.phase) {
|
||||
GatewaySubagentEvent.Phase.SPAWN_REQUESTED,
|
||||
GatewaySubagentEvent.Phase.START,
|
||||
-> SubagentActivityEventKind.STARTED
|
||||
GatewaySubagentEvent.Phase.THINKING,
|
||||
GatewaySubagentEvent.Phase.PROGRESS,
|
||||
-> SubagentActivityEventKind.UPDATE
|
||||
GatewaySubagentEvent.Phase.TOOL -> SubagentActivityEventKind.TOOL
|
||||
GatewaySubagentEvent.Phase.COMPLETE -> SubagentActivityEventKind.COMPLETED
|
||||
},
|
||||
text = if (event.phase == GatewaySubagentEvent.Phase.COMPLETE) summary else preview,
|
||||
toolName = toolName,
|
||||
phase = phase,
|
||||
observedAtMillis = clock(),
|
||||
)
|
||||
|
||||
val priorEvents = base?.events.orEmpty()
|
||||
val coalesced = eventRow.kind == SubagentActivityEventKind.UPDATE &&
|
||||
priorEvents.lastOrNull()?.let { previous ->
|
||||
previous.kind == eventRow.kind && previous.text == eventRow.text
|
||||
} == true
|
||||
val appended = if (coalesced) priorEvents else priorEvents + eventRow
|
||||
val (boundedEvents, truncated) = boundEvents(appended)
|
||||
val next = SubagentActivity(
|
||||
laneId = base?.laneId ?: laneSequence++,
|
||||
turnId = turnId,
|
||||
taskIndex = taskIndex,
|
||||
taskCount = maxOf(1, event.taskCount, base?.taskCount ?: 1),
|
||||
goal = goal.ifBlank { base?.goal.orEmpty() },
|
||||
subagentId = event.subagentId?.takeIf(String::isNotBlank) ?: base?.subagentId,
|
||||
childSessionId = event.childSessionId?.takeIf(String::isNotBlank) ?: base?.childSessionId,
|
||||
parentId = event.parentId?.takeIf(String::isNotBlank) ?: base?.parentId,
|
||||
depth = event.depth ?: base?.depth,
|
||||
model = event.model?.takeIf(String::isNotBlank) ?: base?.model,
|
||||
profile = profile?.takeIf(String::isNotBlank) ?: base?.profile,
|
||||
phase = phase,
|
||||
summary = summary ?: base?.summary,
|
||||
durationSeconds = event.durationSeconds ?: base?.durationSeconds,
|
||||
events = boundedEvents,
|
||||
truncated = base?.truncated == true || truncated,
|
||||
partialAfterGap = base?.partialAfterGap == true,
|
||||
revision = (base?.revision ?: 0L) + 1,
|
||||
)
|
||||
_activities.value = (_activities.value.filterNot { it.stableKey == next.stableKey } + next)
|
||||
.sortedWith(compareBy<SubagentActivity> { it.isTerminal }.thenBy { it.taskIndex })
|
||||
}
|
||||
|
||||
fun endTurn(turnId: String) {
|
||||
if (activeTurnId != turnId) return
|
||||
_activities.value = _activities.value.map { activity ->
|
||||
if (activity.isTerminal) activity else activity.copy(
|
||||
phase = SubagentActivityPhase.ENDED_WITH_PARENT,
|
||||
partialAfterGap = true,
|
||||
revision = activity.revision + 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun boundEvents(
|
||||
events: List<SubagentActivityEvent>,
|
||||
): Pair<List<SubagentActivityEvent>, Boolean> {
|
||||
val bounded = events.toMutableList()
|
||||
var truncated = false
|
||||
fun charCount(): Int = bounded.sumOf { (it.text?.length ?: 0) + (it.toolName?.length ?: 0) }
|
||||
while (bounded.size > MAX_EVENTS_PER_CHILD || charCount() > MAX_CHARS_PER_CHILD) {
|
||||
if (bounded.size <= 1) break
|
||||
bounded.removeAt(if (bounded.first().kind == SubagentActivityEventKind.STARTED) 1 else 0)
|
||||
truncated = true
|
||||
}
|
||||
return bounded to truncated
|
||||
}
|
||||
}
|
||||
|
||||
private fun GatewaySubagentEvent.toActivityPhase(): SubagentActivityPhase = when (phase) {
|
||||
GatewaySubagentEvent.Phase.SPAWN_REQUESTED,
|
||||
GatewaySubagentEvent.Phase.START -> SubagentActivityPhase.STARTED
|
||||
GatewaySubagentEvent.Phase.THINKING -> SubagentActivityPhase.THINKING
|
||||
GatewaySubagentEvent.Phase.TOOL -> SubagentActivityPhase.TOOL
|
||||
GatewaySubagentEvent.Phase.PROGRESS -> SubagentActivityPhase.PROGRESS
|
||||
GatewaySubagentEvent.Phase.COMPLETE -> when (status?.trim()?.lowercase()) {
|
||||
"failed", "error" -> SubagentActivityPhase.FAILED
|
||||
"interrupted", "cancelled", "canceled" -> SubagentActivityPhase.INTERRUPTED
|
||||
else -> SubagentActivityPhase.COMPLETED
|
||||
}
|
||||
}
|
||||
|
||||
private val ANSI_ESCAPE = Regex("\\u001B(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001B\\\\))")
|
||||
|
||||
private fun sanitize(value: String?, maxChars: Int): String = value.orEmpty()
|
||||
.replace(ANSI_ESCAPE, "")
|
||||
.filter { it == '\n' || it == '\t' || it >= ' ' }
|
||||
.trim()
|
||||
.take(maxChars)
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChildWatch
|
||||
import com.hermesandroid.relay.network.upstream.GatewayTurnCallbacks
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
internal data class SubagentChildPreview(
|
||||
val activityKey: String,
|
||||
val parentSessionId: String,
|
||||
val parentScopeKey: String?,
|
||||
/** null while opening, false for a truthful parent-event fallback. */
|
||||
val childWatchAvailable: Boolean? = null,
|
||||
val messages: List<ChatMessage> = emptyList(),
|
||||
val running: Boolean = false,
|
||||
val status: String? = null,
|
||||
val historyTruncated: Boolean = false,
|
||||
val partialAfterGap: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
internal class SubagentChildPreviewController(
|
||||
private val scope: CoroutineScope,
|
||||
private val openWatch: suspend (
|
||||
GatewayChatClient,
|
||||
String,
|
||||
String?,
|
||||
GatewayTurnCallbacks,
|
||||
) -> Result<GatewayChildWatch> = { client, sessionId, profile, callbacks ->
|
||||
client.openChildWatch(sessionId, profile, callbacks)
|
||||
},
|
||||
private val closeWatch: suspend (GatewayChatClient, GatewayChildWatch) -> Result<Unit> =
|
||||
{ client, watch -> client.closeChildWatch(watch) },
|
||||
) {
|
||||
private class WatchContext(
|
||||
val activity: SubagentActivity,
|
||||
val client: GatewayChatClient,
|
||||
val parentSessionId: String,
|
||||
val parentScopeKey: String?,
|
||||
val generation: Long,
|
||||
val stillOwnsParent: () -> Boolean,
|
||||
) {
|
||||
val handler = ChatHandler()
|
||||
var messageOrdinal = 0
|
||||
var messageId = "child-watch-$generation-0"
|
||||
var contentTruncated = false
|
||||
var initialized = false
|
||||
var pendingOverflow = false
|
||||
val pendingCallbacks = mutableListOf<() -> Unit>()
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow<SubagentChildPreview?>(null)
|
||||
val state: StateFlow<SubagentChildPreview?> = _state.asStateFlow()
|
||||
private val generation = AtomicLong(0)
|
||||
private var watch: GatewayChildWatch? = null
|
||||
private var watchClient: GatewayChatClient? = null
|
||||
|
||||
fun open(
|
||||
activity: SubagentActivity,
|
||||
client: GatewayChatClient?,
|
||||
parentSessionId: String,
|
||||
parentScopeKey: String?,
|
||||
gatewayRouteActive: Boolean,
|
||||
stillOwnsParent: () -> Boolean,
|
||||
) {
|
||||
if (isAlreadyOpen(activity.stableKey, parentSessionId, parentScopeKey)) return
|
||||
close(clearState = false)
|
||||
if (activity.childSessionId.isNullOrBlank() || client == null || !gatewayRouteActive) {
|
||||
_state.value = fallbackState(activity, parentSessionId, parentScopeKey)
|
||||
return
|
||||
}
|
||||
|
||||
val context = WatchContext(
|
||||
activity = activity,
|
||||
client = client,
|
||||
parentSessionId = parentSessionId,
|
||||
parentScopeKey = parentScopeKey,
|
||||
generation = generation.incrementAndGet(),
|
||||
stillOwnsParent = stillOwnsParent,
|
||||
)
|
||||
_state.value = baseState(context)
|
||||
// Once upstream creates a lazy watcher, only the resume acknowledgement
|
||||
// reveals the live id needed to close it. Let a dismissed open finish;
|
||||
// generation invalidation makes [acceptOpenedWatch] close the late handle.
|
||||
scope.launch { openWatch(context) }
|
||||
}
|
||||
|
||||
fun close() = close(clearState = true)
|
||||
|
||||
private suspend fun openWatch(context: WatchContext) {
|
||||
openWatch(
|
||||
context.client,
|
||||
context.activity.childSessionId.orEmpty(),
|
||||
context.activity.profile,
|
||||
callbacks(context),
|
||||
).fold(
|
||||
onSuccess = { opened -> acceptOpenedWatch(context, opened) },
|
||||
onFailure = { error -> publishOpenFailure(context, error.message) },
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun acceptOpenedWatch(context: WatchContext, opened: GatewayChildWatch) {
|
||||
if (!owns(context)) {
|
||||
closeWatch(context.client, opened)
|
||||
return
|
||||
}
|
||||
watch = opened
|
||||
watchClient = context.client
|
||||
context.handler.setSessionId(opened.storedSessionId)
|
||||
context.handler.loadMessageHistory(opened.messages)
|
||||
context.contentTruncated = context.handler.boundReadOnlyPreview()
|
||||
val pending = synchronized(context.pendingCallbacks) {
|
||||
context.initialized = true
|
||||
context.pendingCallbacks.toList().also { context.pendingCallbacks.clear() }
|
||||
}
|
||||
publish(
|
||||
context = context,
|
||||
running = opened.running,
|
||||
status = opened.status,
|
||||
historyTruncated = opened.historyTruncated || context.contentTruncated,
|
||||
partial = context.activity.partialAfterGap || context.pendingOverflow,
|
||||
)
|
||||
pending.forEach { callback -> if (owns(context)) callback() }
|
||||
}
|
||||
|
||||
private fun callbacks(context: WatchContext) = GatewayTurnCallbacks(
|
||||
onSessionId = { },
|
||||
onStart = { runOrQueue(context) { startMessage(context) } },
|
||||
onTextDelta = { delta ->
|
||||
runOrQueue(context) { mutate(context) { onTextDelta(context.messageId, delta) } }
|
||||
},
|
||||
onThinkingDelta = { delta ->
|
||||
runOrQueue(context) { mutate(context) { onThinkingDelta(context.messageId, delta) } }
|
||||
},
|
||||
onToolCallStart = { id, name, preview ->
|
||||
runOrQueue(context) {
|
||||
mutate(context) { onToolCallStart(context.messageId, id, name, preview) }
|
||||
}
|
||||
},
|
||||
onToolCallDone = { id, preview ->
|
||||
runOrQueue(context) {
|
||||
mutate(context, ensureMessage = false) {
|
||||
onToolCallComplete(context.messageId, id, preview)
|
||||
}
|
||||
}
|
||||
},
|
||||
onToolCallFailed = { id, error ->
|
||||
runOrQueue(context) {
|
||||
mutate(context, ensureMessage = false) {
|
||||
onToolCallFailed(context.messageId, id, error)
|
||||
}
|
||||
}
|
||||
},
|
||||
onTurnComplete = {
|
||||
runOrQueue(context) {
|
||||
if (owns(context)) context.handler.onTurnComplete(context.messageId)
|
||||
}
|
||||
},
|
||||
onReconcileRequired = { runOrQueue(context) { publish(context, partial = true) } },
|
||||
onComplete = { runOrQueue(context) { complete(context) } },
|
||||
onUsage = { },
|
||||
onError = { message ->
|
||||
runOrQueue(context) {
|
||||
publish(context, running = false, partial = true, error = message)
|
||||
}
|
||||
},
|
||||
onToolGenerating = { },
|
||||
onSubagentEvent = { event ->
|
||||
runOrQueue(context) { mutate(context) { onSubagentEvent(context.messageId, event) } }
|
||||
},
|
||||
onMoaReference = { },
|
||||
onInteractionRequest = { },
|
||||
onInteractionExpired = { },
|
||||
onResumeFailure = { message ->
|
||||
runOrQueue(context) {
|
||||
publish(context, running = false, partial = true, error = message)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
private fun runOrQueue(context: WatchContext, callback: () -> Unit) {
|
||||
if (!owns(context)) return
|
||||
val runNow = synchronized(context.pendingCallbacks) {
|
||||
if (context.initialized) {
|
||||
true
|
||||
} else {
|
||||
if (context.pendingCallbacks.size >= 256) {
|
||||
context.pendingCallbacks.removeAt(0)
|
||||
context.pendingOverflow = true
|
||||
}
|
||||
context.pendingCallbacks += callback
|
||||
false
|
||||
}
|
||||
}
|
||||
if (runNow) callback()
|
||||
}
|
||||
|
||||
private fun startMessage(context: WatchContext) {
|
||||
if (!owns(context)) return
|
||||
context.messageId = "child-watch-${context.generation}-${context.messageOrdinal++}"
|
||||
ensureLiveMessage(context)
|
||||
publish(context)
|
||||
}
|
||||
|
||||
private inline fun mutate(
|
||||
context: WatchContext,
|
||||
ensureMessage: Boolean = true,
|
||||
mutation: ChatHandler.() -> Unit,
|
||||
) {
|
||||
if (!owns(context)) return
|
||||
if (ensureMessage) ensureLiveMessage(context)
|
||||
context.handler.mutation()
|
||||
context.contentTruncated = context.handler.boundReadOnlyPreview() || context.contentTruncated
|
||||
publish(context)
|
||||
}
|
||||
|
||||
private fun complete(context: WatchContext) {
|
||||
if (!owns(context)) return
|
||||
context.handler.onStreamComplete(context.messageId)
|
||||
// The child mirror's message.complete omits failed/interrupted status.
|
||||
// Keep this neutral; the parent activity lane is authoritative.
|
||||
publish(context, running = false)
|
||||
}
|
||||
|
||||
private fun ensureLiveMessage(context: WatchContext) {
|
||||
if (context.handler.messages.value.any { it.id == context.messageId }) return
|
||||
context.handler.addPlaceholderMessage(
|
||||
ChatMessage(
|
||||
id = context.messageId,
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "",
|
||||
timestamp = System.currentTimeMillis(),
|
||||
isStreaming = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun publish(
|
||||
context: WatchContext,
|
||||
running: Boolean = true,
|
||||
status: String? = _state.value?.status,
|
||||
historyTruncated: Boolean =
|
||||
_state.value?.historyTruncated == true || context.contentTruncated,
|
||||
partial: Boolean = _state.value?.partialAfterGap == true,
|
||||
error: String? = null,
|
||||
) {
|
||||
if (!owns(context)) return
|
||||
_state.value = baseState(context).copy(
|
||||
childWatchAvailable = true,
|
||||
messages = context.handler.messages.value.takeLast(200),
|
||||
running = running,
|
||||
status = status,
|
||||
historyTruncated = historyTruncated,
|
||||
partialAfterGap = partial,
|
||||
error = error,
|
||||
)
|
||||
}
|
||||
|
||||
private fun publishOpenFailure(context: WatchContext, message: String?) {
|
||||
if (!owns(context)) return
|
||||
_state.value = fallbackState(
|
||||
context.activity,
|
||||
context.parentSessionId,
|
||||
context.parentScopeKey,
|
||||
).copy(error = message)
|
||||
}
|
||||
|
||||
private fun owns(context: WatchContext): Boolean =
|
||||
generation.get() == context.generation && context.stillOwnsParent()
|
||||
|
||||
private fun isAlreadyOpen(key: String, sessionId: String, scopeKey: String?): Boolean =
|
||||
_state.value?.let {
|
||||
it.activityKey == key &&
|
||||
it.parentSessionId == sessionId &&
|
||||
it.parentScopeKey == scopeKey &&
|
||||
it.error.isNullOrBlank() &&
|
||||
it.childWatchAvailable != false
|
||||
} == true
|
||||
|
||||
private fun baseState(context: WatchContext) = SubagentChildPreview(
|
||||
activityKey = context.activity.stableKey,
|
||||
parentSessionId = context.parentSessionId,
|
||||
parentScopeKey = context.parentScopeKey,
|
||||
)
|
||||
|
||||
private fun fallbackState(
|
||||
activity: SubagentActivity,
|
||||
parentSessionId: String,
|
||||
parentScopeKey: String?,
|
||||
) = SubagentChildPreview(
|
||||
activityKey = activity.stableKey,
|
||||
parentSessionId = parentSessionId,
|
||||
parentScopeKey = parentScopeKey,
|
||||
childWatchAvailable = false,
|
||||
partialAfterGap = activity.partialAfterGap,
|
||||
)
|
||||
|
||||
private fun close(clearState: Boolean) {
|
||||
generation.incrementAndGet()
|
||||
val closingWatch = watch
|
||||
val closingClient = watchClient
|
||||
watch = null
|
||||
watchClient = null
|
||||
if (closingWatch != null && closingClient != null) {
|
||||
scope.launch { closeWatch(closingClient, closingWatch) }
|
||||
}
|
||||
if (clearState) _state.value = null
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ import com.hermesandroid.relay.voice.VoiceCommandInterpreter
|
||||
import com.hermesandroid.relay.voice.SpokenInterruptionLatch
|
||||
import com.hermesandroid.relay.voice.voiceInterfaceContextPrompt
|
||||
import com.hermesandroid.relay.assistant.assistantContextStore
|
||||
import com.hermesandroid.relay.assistant.AssistantSessionNotice
|
||||
import com.hermesandroid.relay.assistant.buildAssistantVoiceTurnPayload
|
||||
// === PHASE3-voice-intents: voice→bridge intent routing ===
|
||||
import com.hermesandroid.relay.voice.IntentResult
|
||||
@@ -90,6 +91,7 @@ import java.util.Collections
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
|
||||
@@ -126,6 +128,25 @@ internal fun voiceSubmissionRetryState(state: VoiceUiState): VoiceUiState = stat
|
||||
error = null,
|
||||
)
|
||||
|
||||
internal fun voiceNoSpeechState(state: VoiceUiState): VoiceUiState = state.copy(
|
||||
state = VoiceState.Idle,
|
||||
amplitude = 0f,
|
||||
outputAudioActive = false,
|
||||
transcribedText = null,
|
||||
error = null,
|
||||
assistantNotice = AssistantSessionNotice.NoSpeech,
|
||||
)
|
||||
|
||||
internal fun voiceCaptureCancellationState(
|
||||
state: VoiceUiState,
|
||||
notice: AssistantSessionNotice? = null,
|
||||
): VoiceUiState = state.copy(
|
||||
state = VoiceState.Idle,
|
||||
amplitude = 0f,
|
||||
outputAudioActive = false,
|
||||
assistantNotice = notice,
|
||||
)
|
||||
|
||||
internal data class AssistantContextTurnDisposition(
|
||||
val retireForLaterTurns: Boolean,
|
||||
val consumeOnTransportAcceptance: Boolean,
|
||||
@@ -328,6 +349,10 @@ data class VoiceUiState(
|
||||
val responseText: String = "",
|
||||
/** Human-readable error surfaced in the overlay. */
|
||||
val error: String? = null,
|
||||
/** Content-free retry status safe for the system Assistant surface. */
|
||||
val assistantNotice: AssistantSessionNotice? = null,
|
||||
/** Stable owner for cross-process Assistant status; null for ordinary voice. */
|
||||
val assistantActivationId: String? = null,
|
||||
/** Currently-selected interaction mode. */
|
||||
val interactionMode: InteractionMode = InteractionMode.TapToTalk,
|
||||
/**
|
||||
@@ -440,6 +465,7 @@ internal fun voiceSessionExitState(state: VoiceUiState): VoiceUiState =
|
||||
transcribedText = null,
|
||||
responseText = "",
|
||||
error = null,
|
||||
assistantNotice = null,
|
||||
destructiveCountdown = null,
|
||||
hermesConfirmation = null,
|
||||
handoffStatus = null,
|
||||
@@ -1037,6 +1063,14 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private var bargeInListener: BargeInListener? = null
|
||||
private var bargeInListenerJob: Job? = null
|
||||
private var bargeInVadEngine: VadEngine? = null
|
||||
/**
|
||||
* The most recent asynchronous AudioRecord shutdown still releasing the
|
||||
* process-wide BargeIn microphone lease. Teardown is intentionally
|
||||
* idempotent, so completion paths may call [stopBargeInListener] after the
|
||||
* listener reference has already been cleared. Retaining this fence makes
|
||||
* every subsequent VoiceCapture start join the same ownership handoff.
|
||||
*/
|
||||
private val pendingBargeInReaderRelease = AtomicReference<Job?>(null)
|
||||
private val bargeInTurnEpoch = AtomicLong(0L)
|
||||
@Volatile private var activeBargeInTurnEpoch: Long = 0L
|
||||
|
||||
@@ -1373,6 +1407,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return
|
||||
}
|
||||
|
||||
// A mode change supersedes any capture that is still waiting for the
|
||||
// previous microphone owner to release. The selected mode below may
|
||||
// start a fresh Continuous capture with its own generation.
|
||||
cancelPendingListeningStart()
|
||||
|
||||
if (mode != InteractionMode.Continuous) {
|
||||
continuousLoopArmed = false
|
||||
continuousListeningPaused = false
|
||||
@@ -1630,6 +1669,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
state = VoiceState.Idle,
|
||||
outputAudioActive = false,
|
||||
error = null,
|
||||
assistantActivationId = activationId,
|
||||
hermesConfirmation = null,
|
||||
backgroundRun = if (orphanedRun != null) null else it.backgroundRun,
|
||||
)
|
||||
@@ -1844,6 +1884,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
fun exitVoiceMode() {
|
||||
cancelPendingListeningStart()
|
||||
// Idempotence guard — added 2026-04-21 after logcat showed the voice-
|
||||
// exit chime playing on every Add-connection tap.
|
||||
//
|
||||
@@ -1995,6 +2036,10 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
fun startListening() {
|
||||
startListening(requireContinuousLoop = false)
|
||||
}
|
||||
|
||||
private fun startListening(requireContinuousLoop: Boolean) {
|
||||
// A direct mic tap starts a normal capture. Only the recorder opened by
|
||||
// onBargeInDetected may carry response-interruption command context.
|
||||
responseInterruptedForVoiceCommand = false
|
||||
@@ -2003,7 +2048,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
setError("Recorder not initialized")
|
||||
return
|
||||
}
|
||||
if (pendingListeningStartJob?.isActive == true) return
|
||||
if (requireContinuousLoop && !canStartContinuousCapture()) return
|
||||
// A direct/new capture request supersedes a stale handoff waiter. It
|
||||
// will join the same retained microphone-release fence under a fresh
|
||||
// epoch below instead of being silently dropped.
|
||||
cancelPendingListeningStart()
|
||||
if (rec.isRecording()) return
|
||||
if (_uiState.value.state == VoiceState.Listening) {
|
||||
// Listening is reserved for a live AudioRecord. Reconcile a stale
|
||||
@@ -2037,7 +2086,9 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
try { realtimePcmPlayer?.stop() } catch (_: Exception) { /* ignore */ }
|
||||
|
||||
if (microphoneRelease == null || microphoneRelease.isCompleted) {
|
||||
startVoiceCapture(rec)
|
||||
if (!requireContinuousLoop || canStartContinuousCapture()) {
|
||||
startVoiceCapture(rec)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2045,7 +2096,9 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val pendingStart = viewModelScope.launch(start = CoroutineStart.LAZY) {
|
||||
try {
|
||||
microphoneRelease.join()
|
||||
if (listeningStartEpoch == startEpoch) {
|
||||
if (listeningStartEpoch == startEpoch &&
|
||||
(!requireContinuousLoop || canStartContinuousCapture())
|
||||
) {
|
||||
startVoiceCapture(rec)
|
||||
}
|
||||
} finally {
|
||||
@@ -2058,8 +2111,20 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
pendingStart.start()
|
||||
}
|
||||
|
||||
private fun startVoiceCapture(rec: VoiceRecorder) {
|
||||
try {
|
||||
private fun canStartContinuousCapture(): Boolean {
|
||||
val state = _uiState.value
|
||||
return state.voiceMode &&
|
||||
state.interactionMode == InteractionMode.Continuous &&
|
||||
state.state == VoiceState.Idle &&
|
||||
continuousLoopArmed &&
|
||||
!continuousListeningPaused
|
||||
}
|
||||
|
||||
private fun startVoiceCapture(
|
||||
rec: VoiceRecorder,
|
||||
bargeInCapture: Boolean = false,
|
||||
): Boolean {
|
||||
return try {
|
||||
rec.startRecording()
|
||||
listeningStartedAtMs = System.currentTimeMillis()
|
||||
_uiState.update {
|
||||
@@ -2067,6 +2132,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
state = VoiceState.Listening,
|
||||
outputAudioActive = false,
|
||||
error = null,
|
||||
assistantNotice = null,
|
||||
responseText = "",
|
||||
// v0.4.1 — fresh turn, drop any stale JIT permission chip
|
||||
// from the previous dispatch.
|
||||
@@ -2074,16 +2140,20 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
handoffStatus = null,
|
||||
)
|
||||
}
|
||||
// 2026-04-18: arm silence-based auto-stop. HoldToTalk skips
|
||||
// this — the physical release is the authoritative stop.
|
||||
if (_uiState.value.interactionMode != InteractionMode.HoldToTalk) {
|
||||
// A normal Hold-to-talk capture ends on physical release. A
|
||||
// barge-in capture is VAD-owned instead, so it always needs the
|
||||
// silence watchdog even when Hold-to-talk is the saved mode;
|
||||
// otherwise the steering utterance remains open indefinitely.
|
||||
if (shouldArmVoiceSilenceWatchdog(_uiState.value.interactionMode, bargeInCapture)) {
|
||||
startSilenceWatchdog()
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
listeningStartedAtMs = 0L
|
||||
Log.e(TAG, "startListening failed: ${e.message}")
|
||||
// SecurityException path becomes "Permission needed" via the classifier.
|
||||
surfaceError(e, context = "record")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2176,7 +2246,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private fun shouldDiscardVoiceCaptureBeforeStop(durationMs: Long): Boolean =
|
||||
durationMs < MIN_VOICE_CAPTURE_DURATION_MS
|
||||
|
||||
private fun cancelListeningWithoutProcessing(title: String, detail: String? = null) {
|
||||
private fun cancelListeningWithoutProcessing(
|
||||
title: String,
|
||||
detail: String? = null,
|
||||
notice: AssistantSessionNotice? = null,
|
||||
) {
|
||||
responseInterruptedForVoiceCommand = false
|
||||
silenceWatchdogJob?.cancel()
|
||||
silenceWatchdogJob = null
|
||||
@@ -2188,9 +2262,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
title = title,
|
||||
detail = detail,
|
||||
)
|
||||
_uiState.update {
|
||||
it.copy(state = VoiceState.Idle, amplitude = 0f, outputAudioActive = false)
|
||||
}
|
||||
_uiState.update { voiceCaptureCancellationState(it, notice) }
|
||||
}
|
||||
|
||||
/** Reconcile microphone state after the Activity returns to foreground. */
|
||||
@@ -2218,6 +2290,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
* listening turn; until then, idle queue-drain callbacks are ignored.
|
||||
*/
|
||||
fun pauseContinuousMode() {
|
||||
cancelPendingListeningStart()
|
||||
continuousLoopArmed = false
|
||||
continuousListeningPaused = _uiState.value.interactionMode == InteractionMode.Continuous
|
||||
continuousResumeJob?.cancel()
|
||||
@@ -2327,6 +2400,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
cancelListeningWithoutProcessing(
|
||||
title = getApplication<Application>().getString(R.string.voice_status_no_speech),
|
||||
detail = "No speech within ${IDLE_NO_SPEECH_MS / 1000}s",
|
||||
notice = AssistantSessionNotice.NoSpeech,
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
@@ -3547,9 +3621,9 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val message = when {
|
||||
raw.contains("timeout", ignoreCase = true) ||
|
||||
raw.contains("not responding", ignoreCase = true) ->
|
||||
"Relay is not responding. Check Connections."
|
||||
"Relay is not responding. Check Gateways."
|
||||
raw.contains("not configured", ignoreCase = true) ->
|
||||
"Relay is not configured. Check Connections."
|
||||
"Relay is not configured. Check Gateways."
|
||||
else -> raw
|
||||
}
|
||||
DiagnosticsLog.record(
|
||||
@@ -5760,7 +5834,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
continuousLoopArmed &&
|
||||
_uiState.value.state == VoiceState.Idle
|
||||
) {
|
||||
startListening()
|
||||
startListening(requireContinuousLoop = true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5825,6 +5899,29 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!activeResponseOwnsBargeIn()) {
|
||||
Log.i(TAG, "Barge-in listener skipped; no active voice response owns the microphone")
|
||||
return
|
||||
}
|
||||
|
||||
val pendingReaderRelease = pendingBargeInReaderRelease.get()?.takeUnless { it.isCompleted }
|
||||
if (pendingReaderRelease != null) {
|
||||
// A late playback/realtime callback may request the next turn's
|
||||
// listener while the previous AudioRecord is still unwinding.
|
||||
// Join the same ownership fence as VoiceCapture, then re-check the
|
||||
// turn epoch so stale generations cannot reopen the microphone.
|
||||
activeBargeInTurnEpoch = epoch
|
||||
viewModelScope.launch {
|
||||
pendingReaderRelease.join()
|
||||
if (activeBargeInTurnEpoch == epoch &&
|
||||
bargeInListener == null &&
|
||||
activeResponseOwnsBargeIn()
|
||||
) {
|
||||
startBargeInListenerIfEnabled(epoch = epoch)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val vad = try {
|
||||
vadFactory().also { it.setSensitivity(prefs.sensitivity) }
|
||||
@@ -5873,6 +5970,12 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun activeResponseOwnsBargeIn(): Boolean {
|
||||
val state = _uiState.value
|
||||
return state.voiceMode &&
|
||||
(state.state == VoiceState.Thinking || state.state == VoiceState.Speaking)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear down the active [BargeInListener], cancel its event subscribers,
|
||||
* unduck the player (in case a ducking watchdog hadn't yet restored
|
||||
@@ -5906,7 +6009,13 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
try { realtimePcmPlayer?.unduck() } catch (_: Throwable) { /* ignore */ }
|
||||
isDucked = false
|
||||
}
|
||||
return stoppedReaderJob
|
||||
if (stoppedReaderJob != null) {
|
||||
pendingBargeInReaderRelease.set(stoppedReaderJob)
|
||||
stoppedReaderJob.invokeOnCompletion {
|
||||
pendingBargeInReaderRelease.compareAndSet(stoppedReaderJob, null)
|
||||
}
|
||||
}
|
||||
return pendingBargeInReaderRelease.get()?.takeUnless { it.isCompleted }
|
||||
}
|
||||
|
||||
private fun markBargeInPlaybackStarted(graceMs: Long) {
|
||||
@@ -5958,6 +6067,8 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
*/
|
||||
internal fun onBargeInDetected() {
|
||||
if (isBargeInStartupGuardActive()) return
|
||||
val interruptedMode = _uiState.value.interactionMode
|
||||
val interruptedEngine = voiceEngineMode
|
||||
val interruptedSpokenReply = _uiState.value.outputAudioActive
|
||||
if (interruptedSpokenReply) spokenInterruptionLatch.mark()
|
||||
duckingWatchdog?.cancel(); duckingWatchdog = null
|
||||
@@ -5991,18 +6102,68 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
responseText = "",
|
||||
)
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val captureEpoch = ++listeningStartEpoch
|
||||
val pendingStart = viewModelScope.launch(start = CoroutineStart.LAZY) {
|
||||
try {
|
||||
microphoneRelease?.join()
|
||||
val rec = recorder
|
||||
if (rec != null && !rec.isRecording()) {
|
||||
rec.startRecording()
|
||||
if (!canStartBargeInCapture(captureEpoch, interruptedMode, interruptedEngine)) {
|
||||
abandonBargeInCaptureIfCurrent(captureEpoch)
|
||||
return@launch
|
||||
}
|
||||
scheduleResumeWatchdog()
|
||||
val rec = recorder ?: error("Recorder not initialized")
|
||||
val captureStarted = rec.isRecording() ||
|
||||
startVoiceCapture(rec, bargeInCapture = true)
|
||||
if (!captureStarted) {
|
||||
abandonBargeInCaptureIfCurrent(captureEpoch)
|
||||
return@launch
|
||||
}
|
||||
if (canStartBargeInCapture(captureEpoch, interruptedMode, interruptedEngine)) {
|
||||
scheduleResumeWatchdog()
|
||||
} else {
|
||||
silenceWatchdogJob?.cancel()
|
||||
silenceWatchdogJob = null
|
||||
try { rec.cancel() } catch (_: Throwable) { /* ignore */ }
|
||||
abandonBargeInCaptureIfCurrent(captureEpoch)
|
||||
}
|
||||
} catch (t: CancellationException) {
|
||||
abandonBargeInCaptureIfCurrent(captureEpoch)
|
||||
throw t
|
||||
} catch (t: Throwable) {
|
||||
responseInterruptedForVoiceCommand = false
|
||||
Log.w(TAG, "barge-in microphone handoff failed: ${t.message}")
|
||||
surfaceError(t, context = "record")
|
||||
if (listeningStartEpoch == captureEpoch) {
|
||||
responseInterruptedForVoiceCommand = false
|
||||
Log.w(TAG, "barge-in microphone handoff failed: ${t.message}")
|
||||
surfaceError(t, context = "record")
|
||||
}
|
||||
} finally {
|
||||
if (listeningStartEpoch == captureEpoch) {
|
||||
pendingListeningStartJob = null
|
||||
}
|
||||
}
|
||||
}
|
||||
pendingListeningStartJob = pendingStart
|
||||
pendingStart.start()
|
||||
}
|
||||
|
||||
private fun canStartBargeInCapture(
|
||||
captureEpoch: Long,
|
||||
interruptedMode: InteractionMode,
|
||||
interruptedEngine: VoiceEngineMode,
|
||||
): Boolean {
|
||||
val state = _uiState.value
|
||||
return listeningStartEpoch == captureEpoch &&
|
||||
state.voiceMode &&
|
||||
state.state == VoiceState.Listening &&
|
||||
state.interactionMode == interruptedMode &&
|
||||
voiceEngineMode == interruptedEngine &&
|
||||
responseInterruptedForVoiceCommand
|
||||
}
|
||||
|
||||
private fun abandonBargeInCaptureIfCurrent(captureEpoch: Long) {
|
||||
if (listeningStartEpoch != captureEpoch) return
|
||||
responseInterruptedForVoiceCommand = false
|
||||
if (_uiState.value.state == VoiceState.Listening && recorder?.isRecording() != true) {
|
||||
_uiState.update {
|
||||
it.copy(state = VoiceState.Idle, amplitude = 0f, outputAudioActive = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6314,9 +6475,22 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
startBargeInListenerIfEnabled()
|
||||
}
|
||||
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun stopBargeInListenerForTest(): Job? = stopBargeInListener()
|
||||
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun finishAgentAudioOutputForTest() {
|
||||
finishAgentAudioOutput()
|
||||
}
|
||||
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun setVoiceEngineModeForTest(mode: VoiceEngineMode) {
|
||||
voiceEngineMode = mode
|
||||
}
|
||||
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun beginBargeInTurnForTest() {
|
||||
_uiState.update { it.copy(state = VoiceState.Thinking) }
|
||||
_uiState.update { it.copy(voiceMode = true, state = VoiceState.Thinking) }
|
||||
beginBargeInTurnIfEnabled()
|
||||
}
|
||||
|
||||
@@ -6497,13 +6671,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
detail = detail,
|
||||
)
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
state = VoiceState.Idle,
|
||||
amplitude = 0f,
|
||||
outputAudioActive = false,
|
||||
error = null,
|
||||
transcribedText = null,
|
||||
)
|
||||
voiceNoSpeechState(it)
|
||||
}
|
||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -6850,6 +7018,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
}
|
||||
|
||||
internal fun shouldArmVoiceSilenceWatchdog(
|
||||
interactionMode: InteractionMode,
|
||||
bargeInCapture: Boolean,
|
||||
): Boolean = bargeInCapture || interactionMode != InteractionMode.HoldToTalk
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Voice capture guards and sentence-boundary detection (top-level so they're
|
||||
// unit-testable without instantiating an AndroidViewModel + Application).
|
||||
|
||||
+165
-46
@@ -152,9 +152,19 @@ class ProfileController(
|
||||
private val _dashboardProfiles = MutableStateFlow<List<Profile>>(emptyList())
|
||||
private val _gatewayProfiles = MutableStateFlow<List<Profile>>(emptyList())
|
||||
private val _gatewayRosterAuthoritative = MutableStateFlow(false)
|
||||
private val dashboardScopeRefreshGeneration = AtomicLong(0L)
|
||||
private val dashboardRosterRefreshGeneration = AtomicLong(0L)
|
||||
private val avatarRefreshGeneration = AtomicLong(0L)
|
||||
private val petRefreshGeneration = AtomicLong(0L)
|
||||
private val petGalleryGeneration = AtomicLong(0L)
|
||||
private val sessionRestoreGeneration = AtomicLong(0L)
|
||||
private val freshDraftScopes = ConcurrentHashMap.newKeySet<SessionScopeKey>()
|
||||
|
||||
private data class SessionScopeKey(
|
||||
val connectionId: String,
|
||||
val profileName: String?,
|
||||
val transport: SessionTransport,
|
||||
)
|
||||
private val petThumbnailRequests = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
val agentProfiles: StateFlow<List<Profile>> = combine(
|
||||
@@ -185,11 +195,32 @@ class ProfileController(
|
||||
_serverDefaultProfileScope.asStateFlow()
|
||||
private val _serverDefaultProfileSettled = MutableStateFlow(false)
|
||||
|
||||
private fun pendingProfileNameForActiveConnection(): String? {
|
||||
val pendingName = _pendingSelectedProfileName.value ?: return null
|
||||
if (_pendingSelectedProfileConnectionId.value != activeConnectionId.value) return null
|
||||
return pendingName.takeIf { it != AgentDisplay.SERVER_DEFAULT_PROFILE_KEY }
|
||||
}
|
||||
|
||||
private val pendingSessionProfileName: StateFlow<String?> = combine(
|
||||
activeConnectionId,
|
||||
_pendingSelectedProfileConnectionId,
|
||||
_pendingSelectedProfileName,
|
||||
) { connectionId, pendingConnectionId, pendingName ->
|
||||
pendingName?.takeIf {
|
||||
pendingConnectionId == connectionId &&
|
||||
it != AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
}
|
||||
}.stateIn(scope, SharingStarted.Eagerly, null)
|
||||
|
||||
val effectiveSessionProfileName: StateFlow<String?> = combine(
|
||||
selectedProfile,
|
||||
serverDefaultProfileScope,
|
||||
) { selected, serverDefault ->
|
||||
AgentDisplay.effectiveSessionProfileName(selected?.name, serverDefault?.active)
|
||||
pendingSessionProfileName,
|
||||
) { selected, serverDefault, pendingName ->
|
||||
AgentDisplay.effectiveSessionProfileName(
|
||||
selectedProfileName = selected?.name ?: pendingName,
|
||||
serverDefaultProfileName = serverDefault?.active,
|
||||
)
|
||||
}.stateIn(scope, SharingStarted.Eagerly, null)
|
||||
|
||||
/** Display identity resolved through the same sticky server default used by session routing. */
|
||||
@@ -197,12 +228,18 @@ class ProfileController(
|
||||
selectedProfile,
|
||||
agentProfiles,
|
||||
serverDefaultProfileScope,
|
||||
) { selected, profiles, serverDefault ->
|
||||
AgentDisplay.effectiveDisplayProfile(
|
||||
selectedProfile = selected,
|
||||
profiles = profiles,
|
||||
serverDefaultProfileName = serverDefault?.active,
|
||||
)
|
||||
pendingSessionProfileName,
|
||||
) { selected, profiles, serverDefault, pendingName ->
|
||||
if (selected == null && pendingName != null) {
|
||||
profiles.firstOrNull { it.name == pendingName }
|
||||
?: Profile(name = pendingName, model = "")
|
||||
} else {
|
||||
AgentDisplay.effectiveDisplayProfile(
|
||||
selectedProfile = selected,
|
||||
profiles = profiles,
|
||||
serverDefaultProfileName = serverDefault?.active,
|
||||
)
|
||||
}
|
||||
}.stateIn(scope, SharingStarted.Eagerly, null)
|
||||
|
||||
/**
|
||||
@@ -214,27 +251,17 @@ class ProfileController(
|
||||
* - the selection has resolved into [selectedProfile], or
|
||||
* - Server default is selected and `/api/profiles/active` has resolved
|
||||
* (or cleanly degraded to the launch-profile fallback), or
|
||||
* - the agent-profile list has arrived, so resolution has been ATTEMPTED —
|
||||
* a genuinely-missing profile then falls back to server default rather
|
||||
* than gating forever.
|
||||
*
|
||||
* False only in the cold-start window where a non-default profile name is
|
||||
* persisted but the profile list hasn't landed yet to resolve it — exactly
|
||||
* when an unscoped read would load the server-default profile by mistake.
|
||||
* A persisted named profile is already an exact session namespace; roster
|
||||
* metadata may resolve its full [Profile] object later. Server default is
|
||||
* the only cold-start selection that waits for `/api/profiles/active`.
|
||||
*/
|
||||
private val profileResolutionInputs = combine(
|
||||
agentProfiles,
|
||||
_serverDefaultProfileSettled,
|
||||
) { profiles, serverDefaultSettled -> profiles to serverDefaultSettled }
|
||||
|
||||
val selectionSettled: StateFlow<Boolean> = combine(
|
||||
activeConnectionId,
|
||||
selectedProfile,
|
||||
_pendingSelectedProfileConnectionId,
|
||||
_pendingSelectedProfileName,
|
||||
profileResolutionInputs,
|
||||
) { connId, selected, pendingConnId, pendingName, resolution ->
|
||||
val (profiles, serverDefaultSettled) = resolution
|
||||
_serverDefaultProfileSettled,
|
||||
) { connId, selected, pendingConnId, pendingName, serverDefaultSettled ->
|
||||
when {
|
||||
connId == null -> true
|
||||
selected != null -> true
|
||||
@@ -243,9 +270,10 @@ class ProfileController(
|
||||
pendingConnId != connId -> false
|
||||
pendingName == null || pendingName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY ->
|
||||
serverDefaultSettled
|
||||
// Non-default name pending: settled once the profile list is present
|
||||
// (resolution attempted), even if the name turns out to be gone.
|
||||
else -> profiles.isNotEmpty()
|
||||
// A persisted non-default name is already an exact session
|
||||
// namespace. Metadata may arrive later; never block or mis-scope
|
||||
// session REST behind the heavyweight profile inventory.
|
||||
else -> true
|
||||
}
|
||||
}.stateIn(scope, SharingStarted.Eagerly, false)
|
||||
|
||||
@@ -449,7 +477,44 @@ class ProfileController(
|
||||
* the current list untouched on failure (e.g. dashboard not signed in).
|
||||
*/
|
||||
fun refreshDashboardProfiles() {
|
||||
refreshDashboardProfileScope()
|
||||
refreshDeferredProfileMetadata()
|
||||
}
|
||||
|
||||
/** Heavy roster/assets metadata, released only after directory success or explicit UI intent. */
|
||||
fun refreshDeferredProfileMetadata() {
|
||||
val connectionId = activeConnectionId.value ?: return
|
||||
val rosterGeneration = dashboardRosterRefreshGeneration.incrementAndGet()
|
||||
val dashboardUrl = activeDashboardUrlProvider()
|
||||
?: return
|
||||
// Gateway roster/assets and Dashboard metadata have independent
|
||||
// transports. A cold or recovering /api/ws must not hold the REST
|
||||
// default-profile/list path (and its cached avatar identity) hostage.
|
||||
scope.launch {
|
||||
refreshGatewayProfiles(connectionId)
|
||||
refreshHermesPet(connectionId)
|
||||
}
|
||||
scope.launch {
|
||||
val client = dashboardClientFactory(connectionId, dashboardUrl)
|
||||
client.listProfiles().onSuccess { profiles ->
|
||||
if (
|
||||
activeConnectionId.value == connectionId &&
|
||||
dashboardRosterRefreshGeneration.get() == rosterGeneration
|
||||
) {
|
||||
_dashboardProfiles.value = profiles
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight cold-start identity scope. This is the only profile request
|
||||
* allowed ahead of the session directory; `/api/profiles` roster/skills,
|
||||
* Gateway avatars, and pet metadata hydrate after rows publish or on demand.
|
||||
*/
|
||||
fun refreshDashboardProfileScope() {
|
||||
val connectionId = activeConnectionId.value ?: return
|
||||
val scopeGeneration = dashboardScopeRefreshGeneration.incrementAndGet()
|
||||
val dashboardUrl = activeDashboardUrlProvider()
|
||||
if (dashboardUrl == null) {
|
||||
_serverDefaultProfileScope.value = null
|
||||
@@ -457,27 +522,23 @@ class ProfileController(
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
refreshGatewayProfiles(connectionId)
|
||||
refreshHermesPet(connectionId)
|
||||
val client = dashboardClientFactory(connectionId, dashboardUrl)
|
||||
val defaultScope = client.getActiveProfileScope().getOrNull()
|
||||
if (activeConnectionId.value != connectionId) return@launch
|
||||
val defaultScope = dashboardClientFactory(connectionId, dashboardUrl)
|
||||
.getActiveProfileScope()
|
||||
.getOrNull()
|
||||
if (
|
||||
activeConnectionId.value != connectionId ||
|
||||
dashboardScopeRefreshGeneration.get() != scopeGeneration
|
||||
) return@launch
|
||||
|
||||
// Older dashboards may not expose this endpoint. Settle to null so
|
||||
// they retain the historical launch-profile behavior rather than
|
||||
// blocking chat indefinitely.
|
||||
_serverDefaultProfileScope.value = defaultScope
|
||||
_serverDefaultProfileSettled.value = true
|
||||
if (_selectedProfile.value == null) {
|
||||
if (selectionIdentityProfileName() == null) {
|
||||
refreshLastSessionForProfile(connectionId, null)
|
||||
rebuildChatApiClient()
|
||||
}
|
||||
|
||||
client.listProfiles().onSuccess { profiles ->
|
||||
if (activeConnectionId.value == connectionId) {
|
||||
_dashboardProfiles.value = profiles
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -736,7 +797,7 @@ class ProfileController(
|
||||
/** Effective profile namespace for Gateway and profile-scoped session I/O. */
|
||||
fun resolveSessionProfileName(selectedProfileName: String? = _selectedProfile.value?.name): String? =
|
||||
AgentDisplay.effectiveSessionProfileName(
|
||||
selectedProfileName = selectedProfileName,
|
||||
selectedProfileName = selectedProfileName ?: pendingProfileNameForActiveConnection(),
|
||||
serverDefaultProfileName = _serverDefaultProfileScope.value?.active,
|
||||
)
|
||||
|
||||
@@ -753,11 +814,19 @@ class ProfileController(
|
||||
suspend fun listProfileScopedSessions(
|
||||
profileName: String?,
|
||||
limit: Int = 200,
|
||||
offset: Int = 0,
|
||||
excludeSources: Collection<String> = emptyList(),
|
||||
): Result<List<SessionItem>>? {
|
||||
val connectionId = activeConnectionId.value ?: return null
|
||||
val dashboardUrl = activeDashboardUrlProvider() ?: return null
|
||||
return dashboardClientFactory(connectionId, dashboardUrl)
|
||||
.listSessions(profile = profileName, limit = limit, archived = "include")
|
||||
.listSessions(
|
||||
profile = profileName,
|
||||
limit = limit,
|
||||
offset = offset,
|
||||
archived = "include",
|
||||
excludeSources = excludeSources,
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun listAllProfileSessions(limit: Int = 200): Result<List<SessionItem>>? {
|
||||
@@ -1449,24 +1518,66 @@ 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"` the slot
|
||||
* follows the gateway probe, and we deliberately DEFER while it's [Unknown]
|
||||
* rather than guess SSE.
|
||||
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
|
||||
* remains Gateway-owned because the transport resolver also chooses Gateway
|
||||
* until a definitive fallback verdict exists.
|
||||
*/
|
||||
fun activeSessionTransport(): SessionTransport? {
|
||||
val preference = streamingEndpointProvider()
|
||||
if (preference != "auto") return SessionTransport.forEndpoint(preference)
|
||||
return when (gatewayAvailabilityProvider()) {
|
||||
GatewayAvailability.Ready -> SessionTransport.GATEWAY
|
||||
GatewayAvailability.Unknown -> null
|
||||
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
|
||||
else -> SessionTransport.SSE
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a user-requested empty draft for one exact conversation scope.
|
||||
*
|
||||
* The in-memory marker fences any stored-session read that was already in
|
||||
* flight, while clearing the exact transport slot makes the draft survive a
|
||||
* process restart. Other profiles, connections, transports, and the server's
|
||||
* actual session/history rows are untouched.
|
||||
*/
|
||||
fun markFreshDraft(
|
||||
connectionId: String,
|
||||
profileName: String?,
|
||||
transport: SessionTransport,
|
||||
) {
|
||||
val scopeKey = SessionScopeKey(connectionId, profileName, transport)
|
||||
freshDraftScopes += scopeKey
|
||||
sessionRestoreGeneration.incrementAndGet()
|
||||
if (
|
||||
activeConnectionId.value == connectionId &&
|
||||
_selectedProfile.value?.name == profileName
|
||||
) {
|
||||
setLastSessionId(null)
|
||||
}
|
||||
scope.launch {
|
||||
profileSessionStore.setSessionId(connectionId, profileName, transport, null)
|
||||
}
|
||||
}
|
||||
|
||||
/** A real session supersedes the fresh-draft marker for its exact scope. */
|
||||
fun markSessionPersisted(
|
||||
connectionId: String,
|
||||
profileName: String?,
|
||||
transport: SessionTransport,
|
||||
) {
|
||||
freshDraftScopes -= SessionScopeKey(connectionId, profileName, transport)
|
||||
sessionRestoreGeneration.incrementAndGet()
|
||||
}
|
||||
|
||||
/** Persisted UI selection identity, available before roster metadata. */
|
||||
fun selectionIdentityProfileName(): String? =
|
||||
_selectedProfile.value?.name ?: pendingProfileNameForActiveConnection()
|
||||
|
||||
fun refreshLastSessionForProfile(
|
||||
connectionId: String?,
|
||||
profileName: String?,
|
||||
) {
|
||||
val generation = sessionRestoreGeneration.incrementAndGet()
|
||||
setLastSessionId(null)
|
||||
if (connectionId == null) return
|
||||
// Defer until the active transport is known — restoring an id the
|
||||
@@ -1477,7 +1588,9 @@ class ProfileController(
|
||||
// Server default may currently route to a sticky profile named
|
||||
// `default` (or any other name), but its last-session slot must remain
|
||||
// distinct from explicitly selecting that named profile.
|
||||
val sessionProfileName = profileName
|
||||
val sessionProfileName = profileName ?: pendingProfileNameForActiveConnection()
|
||||
val scopeKey = SessionScopeKey(connectionId, sessionProfileName, transport)
|
||||
if (scopeKey in freshDraftScopes) return
|
||||
scope.launch {
|
||||
val profileScoped = profileSessionStore
|
||||
.sessionIdFlow(connectionId, sessionProfileName, transport)
|
||||
@@ -1493,8 +1606,10 @@ class ProfileController(
|
||||
null
|
||||
}
|
||||
if (
|
||||
sessionRestoreGeneration.get() == generation &&
|
||||
scopeKey !in freshDraftScopes &&
|
||||
activeConnectionId.value == connectionId &&
|
||||
_selectedProfile.value?.name == profileName &&
|
||||
selectionIdentityProfileName() == sessionProfileName &&
|
||||
activeSessionTransport() == transport
|
||||
) {
|
||||
setLastSessionId(profileScoped ?: legacyDefault)
|
||||
@@ -1517,6 +1632,8 @@ class ProfileController(
|
||||
_dashboardProfiles.value = emptyList()
|
||||
_gatewayProfiles.value = emptyList()
|
||||
_gatewayRosterAuthoritative.value = false
|
||||
dashboardScopeRefreshGeneration.incrementAndGet()
|
||||
dashboardRosterRefreshGeneration.incrementAndGet()
|
||||
avatarRefreshGeneration.incrementAndGet()
|
||||
petRefreshGeneration.incrementAndGet()
|
||||
petGalleryGeneration.incrementAndGet()
|
||||
@@ -1530,6 +1647,8 @@ class ProfileController(
|
||||
_pendingSelectedProfileName.value = null
|
||||
_serverDefaultProfileScope.value = null
|
||||
_serverDefaultProfileSettled.value = false
|
||||
dashboardScopeRefreshGeneration.incrementAndGet()
|
||||
dashboardRosterRefreshGeneration.incrementAndGet()
|
||||
petRefreshGeneration.incrementAndGet()
|
||||
petGalleryGeneration.incrementAndGet()
|
||||
_hermesPetState.value = HermesPetState()
|
||||
|
||||
+175
-19
@@ -7,9 +7,11 @@ import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardCookieStore
|
||||
import com.hermesandroid.relay.network.upstream.DashboardBearerAuth
|
||||
import com.hermesandroid.relay.network.upstream.EncryptedNativeDashboardTokenStore
|
||||
import com.hermesandroid.relay.network.upstream.NativeDashboardTokenStore
|
||||
import com.hermesandroid.relay.network.upstream.EncryptedDashboardCookieStore
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||
import com.hermesandroid.relay.network.upstream.InMemoryDashboardCookieStore
|
||||
import com.hermesandroid.relay.network.upstream.NativeDashboardAuthClient
|
||||
import com.hermesandroid.relay.network.upstream.clearNativeDashboardTokens
|
||||
@@ -24,6 +26,24 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
internal fun reconcileGatewayAvailability(
|
||||
current: GatewayAvailability,
|
||||
probed: GatewayAvailability,
|
||||
liveState: GatewayConnectionState?,
|
||||
liveRouteMatches: Boolean = true,
|
||||
): GatewayAvailability = when {
|
||||
liveRouteMatches && liveState == GatewayConnectionState.Ready -> GatewayAvailability.Ready
|
||||
current == GatewayAvailability.Unsupported &&
|
||||
(probed == GatewayAvailability.Ready || probed == GatewayAvailability.Unknown) -> current
|
||||
else -> probed
|
||||
}
|
||||
|
||||
internal fun isCurrentGatewayClientCallback(
|
||||
connectionId: String,
|
||||
client: GatewayChatClient,
|
||||
cached: Triple<String, String, GatewayChatClient>?,
|
||||
): Boolean = cached?.first == connectionId && cached.third === client
|
||||
|
||||
/**
|
||||
* Owns the **upstream dashboard/gateway transport clients** and the
|
||||
* capability-driven **transport resolution** for
|
||||
@@ -82,6 +102,8 @@ class UpstreamTransportController(
|
||||
private val tokenStoreKeyProvider: (String) -> String? = { null },
|
||||
/** Exact trusted Dashboard base for any saved connection, active or not. */
|
||||
private val trustedDashboardUrlProvider: (String) -> String? = { null },
|
||||
/** False when the host's advertised auth topology requires cookie compatibility mode. */
|
||||
private val nativeDashboardBearerEligibleProvider: (String) -> Boolean = { true },
|
||||
/** Applies pairing-bound TLS to a standard authenticated client when needed. */
|
||||
private val pinnedClientProvider: (String, okhttp3.OkHttpClient) -> okhttp3.OkHttpClient? =
|
||||
{ _, _ -> null },
|
||||
@@ -89,17 +111,33 @@ class UpstreamTransportController(
|
||||
(DashboardCookieStore, DashboardBearerAuth?) -> okhttp3.OkHttpClient = { cookieStore, bearerAuth ->
|
||||
DashboardApiClient.defaultClient(cookieStore, bearerAuth)
|
||||
},
|
||||
private val dashboardTokenStoreFactory: (String) -> NativeDashboardTokenStore = { tokenStoreKey ->
|
||||
EncryptedNativeDashboardTokenStore(context, tokenStoreKey)
|
||||
},
|
||||
private val dashboardCookieStoreFactory: (String, String?) -> DashboardCookieStore =
|
||||
{ connectionId, tokenStoreKey ->
|
||||
EncryptedDashboardCookieStore(
|
||||
context = context,
|
||||
connectionId = connectionId,
|
||||
tokenStoreKey = tokenStoreKey,
|
||||
)
|
||||
},
|
||||
) {
|
||||
|
||||
// --- Per-connection dashboard cookie stores ----------------------------
|
||||
|
||||
/** Per-connection encrypted cookie stores, cached to avoid Keystore churn. */
|
||||
private val dashboardCookieStores =
|
||||
ConcurrentHashMap<String, EncryptedDashboardCookieStore>()
|
||||
ConcurrentHashMap<String, DashboardCookieStore>()
|
||||
private val dashboardTokenStores =
|
||||
ConcurrentHashMap<String, EncryptedNativeDashboardTokenStore>()
|
||||
ConcurrentHashMap<String, NativeDashboardTokenStore>()
|
||||
/** Shared authenticated transport per exact connection + Dashboard route. */
|
||||
private val dashboardRestHttpClients =
|
||||
mutableMapOf<Pair<String, String>, okhttp3.OkHttpClient>()
|
||||
private var dashboardHttpClientCache:
|
||||
Triple<String, String, okhttp3.OkHttpClient>? = null
|
||||
private var dashboardSessionClientCache:
|
||||
Triple<String, String, DashboardApiClient>? = null
|
||||
private data class RouteGatewayEntry(
|
||||
var dashboardUrl: String,
|
||||
var dashboardClient: DashboardApiClient,
|
||||
@@ -131,11 +169,7 @@ class UpstreamTransportController(
|
||||
*/
|
||||
fun dashboardCookieStoreFor(connectionId: String): DashboardCookieStore =
|
||||
dashboardCookieStores.getOrPut(connectionId) {
|
||||
EncryptedDashboardCookieStore(
|
||||
context = context,
|
||||
connectionId = connectionId,
|
||||
tokenStoreKey = tokenStoreKeyProvider(connectionId),
|
||||
)
|
||||
dashboardCookieStoreFactory(connectionId, tokenStoreKeyProvider(connectionId))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,11 +182,11 @@ class UpstreamTransportController(
|
||||
return dashboardCookieStoreFor(connectionId)
|
||||
}
|
||||
|
||||
private fun dashboardTokenStoreFor(connectionId: String): EncryptedNativeDashboardTokenStore {
|
||||
private fun dashboardTokenStoreFor(connectionId: String): NativeDashboardTokenStore {
|
||||
val key = tokenStoreKeyProvider(connectionId)
|
||||
?: com.hermesandroid.relay.data.Connection.buildTokenStoreKey(connectionId)
|
||||
return dashboardTokenStores.getOrPut(connectionId) {
|
||||
EncryptedNativeDashboardTokenStore(context, key)
|
||||
dashboardTokenStoreFactory(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +194,7 @@ class UpstreamTransportController(
|
||||
connectionId: String,
|
||||
dashboardUrl: String,
|
||||
): DashboardBearerAuth? {
|
||||
if (!nativeDashboardBearerEligibleProvider(connectionId)) return null
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl)) return null
|
||||
val trustedDashboardUrl = trustedDashboardUrlProvider(connectionId)
|
||||
?: (if (activeConnectionIdProvider() == connectionId) dashboardUrlProvider() else null)
|
||||
@@ -179,17 +214,44 @@ class UpstreamTransportController(
|
||||
* factory the dashboard-surface callers (profile lists, session/message
|
||||
* scoping, the gateway client, standard-API setup probe) route through.
|
||||
*/
|
||||
@Synchronized
|
||||
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient {
|
||||
val base = dashboardHttpClientFactory(
|
||||
dashboardCookieStoreFor(connectionId),
|
||||
bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
|
||||
)
|
||||
val normalizedUrl = dashboardUrl.trim().trimEnd('/')
|
||||
val key = connectionId to normalizedUrl
|
||||
val sharedClient = dashboardRestHttpClients.getOrPut(key) {
|
||||
val base = dashboardHttpClientFactory(
|
||||
dashboardCookieStoreFor(connectionId),
|
||||
bearerAuthForTrustedDashboard(connectionId, normalizedUrl),
|
||||
)
|
||||
pinnedClientProvider(normalizedUrl, base) ?: base
|
||||
}
|
||||
return DashboardApiClient(
|
||||
baseUrl = dashboardUrl,
|
||||
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
|
||||
baseUrl = normalizedUrl,
|
||||
okHttpClient = sharedClient,
|
||||
ownsHttpClient = false,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuse one authenticated REST client for profile/session directory work.
|
||||
* Exact connection + route identity owns the warm TLS/HTTP connection and
|
||||
* its retirement, matching Desktop's shared HTTP-stack behavior.
|
||||
*/
|
||||
@Synchronized
|
||||
fun dashboardSessionClientFor(
|
||||
connectionId: String,
|
||||
dashboardUrl: String,
|
||||
): DashboardApiClient {
|
||||
dashboardSessionClientCache?.let { (cachedConnection, cachedUrl, client) ->
|
||||
if (cachedConnection == connectionId && cachedUrl == dashboardUrl) return client
|
||||
client.shutdown()
|
||||
dashboardSessionClientCache = null
|
||||
}
|
||||
return dashboardClientFor(connectionId, dashboardUrl).also { client ->
|
||||
dashboardSessionClientCache = Triple(connectionId, dashboardUrl, client)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a [DashboardApiClient] for the active connection against
|
||||
* [dashboardUrl], falling back to an in-memory cookie store when there is
|
||||
@@ -208,6 +270,21 @@ class UpstreamTransportController(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookie-only client for proving a newly imported WebView session. A saved
|
||||
* native bearer must not override the cookie provider during that proof.
|
||||
*/
|
||||
fun dashboardCookieClientForActive(dashboardUrl: String): DashboardApiClient {
|
||||
val base = dashboardHttpClientFactory(
|
||||
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
|
||||
null,
|
||||
)
|
||||
return DashboardApiClient(
|
||||
baseUrl = dashboardUrl,
|
||||
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Native PKCE client for the active connection's exact trusted dashboard
|
||||
* base. Setup probes and stale routes never receive the encrypted bearer
|
||||
@@ -261,6 +338,16 @@ class UpstreamTransportController(
|
||||
@Synchronized
|
||||
fun clearDashboardAuthentication(connectionId: String) {
|
||||
dashboardCookieStoreFor(connectionId).clear()
|
||||
retireNativeDashboardAuthentication(connectionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfers credential ownership to a verified cookie flow. This retires
|
||||
* only native PKCE tokens and clients that may have captured their bearer;
|
||||
* newly imported Dashboard cookies remain intact.
|
||||
*/
|
||||
@Synchronized
|
||||
fun retireNativeDashboardAuthentication(connectionId: String) {
|
||||
clearNativeDashboardTokens(dashboardTokenStoreFor(connectionId))
|
||||
dashboardHttpClientCache
|
||||
?.takeIf { it.first == connectionId }
|
||||
@@ -306,8 +393,19 @@ class UpstreamTransportController(
|
||||
/** Probe-driven update that respects the sticky [markGatewayUnsupported] verdict. */
|
||||
fun updateGatewayAvailability(probed: GatewayAvailability) {
|
||||
val current = _gatewayAvailability.value
|
||||
if (current == GatewayAvailability.Unsupported && probed == GatewayAvailability.Ready) return
|
||||
_gatewayAvailability.value = probed
|
||||
val live = synchronized(this) { gatewayClientCache }
|
||||
val activeConnectionId = activeConnectionIdProvider()
|
||||
val activeDashboardUrl = dashboardUrlProvider()?.trim()?.trimEnd('/')
|
||||
val liveRouteMatches = live != null && activeConnectionId != null &&
|
||||
live.first == activeConnectionId &&
|
||||
live.second.trim().trimEnd('/') == activeDashboardUrl
|
||||
val liveState = live?.third?.connectionState?.value
|
||||
_gatewayAvailability.value = reconcileGatewayAvailability(
|
||||
current,
|
||||
probed,
|
||||
liveState,
|
||||
liveRouteMatches,
|
||||
)
|
||||
}
|
||||
|
||||
// --- Gateway chat client -----------------------------------------------
|
||||
@@ -315,6 +413,18 @@ class UpstreamTransportController(
|
||||
/** Cached gateway client, keyed by connection + resolved dashboard URL. */
|
||||
private var gatewayClientCache: Triple<String, String, GatewayChatClient>? = null
|
||||
|
||||
@Synchronized
|
||||
private fun updateGatewayAvailabilityIfCurrent(
|
||||
connectionId: String,
|
||||
client: GatewayChatClient,
|
||||
availability: GatewayAvailability,
|
||||
) {
|
||||
val current = gatewayClientCache
|
||||
if (isCurrentGatewayClientCallback(connectionId, client, current)) {
|
||||
updateGatewayAvailability(availability)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway chat client for the active connection — built lazily, rebuilt
|
||||
* when the connection or its resolved dashboard URL changes (LAN ↔
|
||||
@@ -347,9 +457,37 @@ class UpstreamTransportController(
|
||||
}
|
||||
}
|
||||
gatewayClientCache?.third?.shutdown()
|
||||
val client = GatewayChatClient(
|
||||
lateinit var client: GatewayChatClient
|
||||
client = GatewayChatClient(
|
||||
initialDashboardClient = dashboardClientFor(connectionId, dashboardUrl),
|
||||
onGatewayUnsupported = { markGatewayUnsupported() },
|
||||
onGatewayUnsupported = {
|
||||
updateGatewayAvailabilityIfCurrent(
|
||||
connectionId,
|
||||
client,
|
||||
GatewayAvailability.Unsupported,
|
||||
)
|
||||
},
|
||||
onGatewaySignInRequired = {
|
||||
updateGatewayAvailabilityIfCurrent(
|
||||
connectionId,
|
||||
client,
|
||||
GatewayAvailability.SignInRequired,
|
||||
)
|
||||
},
|
||||
onGatewayUnreachable = {
|
||||
updateGatewayAvailabilityIfCurrent(
|
||||
connectionId,
|
||||
client,
|
||||
GatewayAvailability.Unreachable,
|
||||
)
|
||||
},
|
||||
onGatewayReady = {
|
||||
updateGatewayAvailabilityIfCurrent(
|
||||
connectionId,
|
||||
client,
|
||||
GatewayAvailability.Ready,
|
||||
)
|
||||
},
|
||||
)
|
||||
// Carry the current keep-alive preference onto the fresh client so a
|
||||
// connection/route switch doesn't lose the no-background-close flag.
|
||||
@@ -436,6 +574,18 @@ class UpstreamTransportController(
|
||||
|
||||
@Synchronized
|
||||
fun disposeConnectionRouteClients(connectionId: String) {
|
||||
dashboardSessionClientCache
|
||||
?.takeIf { it.first == connectionId }
|
||||
?.third
|
||||
?.shutdown()
|
||||
if (dashboardSessionClientCache?.first == connectionId) {
|
||||
dashboardSessionClientCache = null
|
||||
}
|
||||
dashboardRestHttpClients.keys
|
||||
.filter { it.first == connectionId }
|
||||
.forEach { key ->
|
||||
dashboardRestHttpClients.remove(key)?.let(::disposeDashboardHttpClient)
|
||||
}
|
||||
routeGatewayClients.entries
|
||||
.filter { it.key.connectionId == connectionId }
|
||||
.forEach { (key, entry) ->
|
||||
@@ -447,6 +597,10 @@ class UpstreamTransportController(
|
||||
|
||||
@Synchronized
|
||||
fun disposeAllRouteClients() {
|
||||
dashboardSessionClientCache?.third?.shutdown()
|
||||
dashboardSessionClientCache = null
|
||||
dashboardRestHttpClients.values.forEach(::disposeDashboardHttpClient)
|
||||
dashboardRestHttpClients.clear()
|
||||
routeGatewayClients.values.forEach(::shutdownRouteEntry)
|
||||
routeGatewayClients.clear()
|
||||
}
|
||||
@@ -476,6 +630,8 @@ class UpstreamTransportController(
|
||||
gatewayClientCache = null
|
||||
dashboardHttpClientCache?.third?.let(::disposeDashboardHttpClient)
|
||||
dashboardHttpClientCache = null
|
||||
dashboardSessionClientCache?.third?.shutdown()
|
||||
dashboardSessionClientCache = null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.ViewCompositionStrategy
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -91,6 +92,9 @@ import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.components.distinctVoiceRouteParts
|
||||
import com.hermesandroid.relay.ui.components.dispatchVoiceMicHoldPress
|
||||
import com.hermesandroid.relay.ui.components.dispatchVoiceMicTap
|
||||
import com.hermesandroid.relay.ui.components.voiceHoldGesture
|
||||
import com.hermesandroid.relay.ui.components.voiceRouteDisplayLabel
|
||||
import com.hermesandroid.relay.ui.theme.PersistedHermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.InteractionMode
|
||||
@@ -106,6 +110,8 @@ import kotlin.math.sin
|
||||
|
||||
private const val TWO_PI = 6.2831855f
|
||||
private const val HALF_PI = 1.5707964f
|
||||
internal const val VOICE_FLOATING_OVERLAY_MIC_TEST_TAG = "voiceFloatingOverlayMic"
|
||||
internal const val VOICE_OVERLAY_MIC_CONTROL_TEST_TAG = "voiceOverlayMicControl"
|
||||
|
||||
// Matches the in-app VoiceWaveform palette so minimized overlay mode reads as
|
||||
// the same voice surface, just wrapped around the mic control.
|
||||
@@ -638,7 +644,7 @@ private fun overlayPrimaryText(uiState: VoiceUiState, fallback: String): String
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun VoiceFloatingOverlayBubble(
|
||||
internal fun VoiceFloatingOverlayBubble(
|
||||
uiState: VoiceUiState,
|
||||
stateText: String,
|
||||
onExpand: () -> Unit,
|
||||
@@ -658,6 +664,9 @@ private fun VoiceFloatingOverlayBubble(
|
||||
VoiceState.Transcribing, VoiceState.Thinking ->
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) stringResource(R.string.voice_overlay_tap_action_pause) else stringResource(R.string.voice_overlay_tap_action_interrupt)
|
||||
}
|
||||
val holdStopAction = stringResource(R.string.voice_overlay_tap_action_listening)
|
||||
val inactiveHoldDescription = stringResource(R.string.voice_overlay_a11y, stateText, tapAction)
|
||||
val activeHoldDescription = stringResource(R.string.voice_overlay_a11y, stateText, holdStopAction)
|
||||
val containerColor = when (uiState.state) {
|
||||
VoiceState.Listening, VoiceState.Speaking -> Color(0xFFE53935)
|
||||
VoiceState.Transcribing, VoiceState.Thinking -> Color(0xFFE53935)
|
||||
@@ -669,6 +678,40 @@ private fun VoiceFloatingOverlayBubble(
|
||||
VoiceState.Transcribing, VoiceState.Thinking -> Icons.Filled.Stop
|
||||
VoiceState.Idle, VoiceState.Error -> Icons.Filled.Mic
|
||||
}
|
||||
val bubbleGesture = if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
Modifier.voiceHoldGesture(
|
||||
state = uiState.state,
|
||||
inactiveActionLabel = tapAction,
|
||||
activeActionLabel = holdStopAction,
|
||||
onPress = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onInterruptAndStart = {
|
||||
onInterrupt()
|
||||
onStartListening()
|
||||
},
|
||||
)
|
||||
},
|
||||
onRelease = onStopListening,
|
||||
inactiveContentDescription = inactiveHoldDescription,
|
||||
activeContentDescription = activeHoldDescription,
|
||||
)
|
||||
} else {
|
||||
Modifier.combinedClickable(
|
||||
onClick = {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onStopListening = onStopListening,
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
},
|
||||
onLongClick = onExpand,
|
||||
onDoubleClick = onExpand,
|
||||
)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
@@ -691,19 +734,8 @@ private fun VoiceFloatingOverlayBubble(
|
||||
modifier = Modifier
|
||||
.size(70.dp)
|
||||
.clip(CircleShape)
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
dispatchMicAction(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onStopListening = onStopListening,
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
},
|
||||
onLongClick = onExpand,
|
||||
onDoubleClick = onExpand,
|
||||
),
|
||||
.testTag(VOICE_FLOATING_OVERLAY_MIC_TEST_TAG)
|
||||
.then(bubbleGesture),
|
||||
shape = CircleShape,
|
||||
color = containerColor.copy(alpha = if (isHot) 0.96f else 0.92f),
|
||||
shadowElevation = 8.dp,
|
||||
@@ -716,7 +748,11 @@ private fun VoiceFloatingOverlayBubble(
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = stringResource(R.string.voice_overlay_a11y, stateText, tapAction),
|
||||
contentDescription = if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
null
|
||||
} else {
|
||||
stringResource(R.string.voice_overlay_a11y, stateText, tapAction)
|
||||
},
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(23.dp),
|
||||
)
|
||||
@@ -730,6 +766,22 @@ private fun VoiceFloatingOverlayBubble(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
IconButton(
|
||||
onClick = onExpand,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.size(30.dp)
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant, CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ExpandMore,
|
||||
contentDescription = stringResource(R.string.voice_overlay_expand_cd),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +904,7 @@ private fun overlayBubbleStateLabel(state: VoiceState): String = when (state) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MicControlButton(
|
||||
internal fun MicControlButton(
|
||||
uiState: VoiceUiState,
|
||||
onStartListening: () -> Unit,
|
||||
onStopListening: () -> Unit,
|
||||
@@ -864,19 +916,56 @@ private fun MicControlButton(
|
||||
uiState.state == VoiceState.Speaking ||
|
||||
uiState.state == VoiceState.Transcribing ||
|
||||
uiState.state == VoiceState.Thinking
|
||||
val actionDescription = when (uiState.state) {
|
||||
VoiceState.Idle, VoiceState.Error -> stringResource(R.string.voice_overlay_tap_action_idle)
|
||||
VoiceState.Listening ->
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
stringResource(R.string.voice_overlay_tap_action_pause)
|
||||
} else {
|
||||
stringResource(R.string.voice_overlay_tap_action_listening)
|
||||
}
|
||||
VoiceState.Transcribing, VoiceState.Thinking, VoiceState.Speaking ->
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
stringResource(R.string.voice_overlay_tap_action_pause)
|
||||
} else {
|
||||
stringResource(R.string.voice_overlay_tap_action_interrupt)
|
||||
}
|
||||
}
|
||||
val holdStopDescription = stringResource(R.string.voice_overlay_tap_action_listening)
|
||||
val gestureModifier = if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
Modifier.voiceHoldGesture(
|
||||
state = uiState.state,
|
||||
inactiveActionLabel = actionDescription,
|
||||
activeActionLabel = holdStopDescription,
|
||||
onPress = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onInterruptAndStart = {
|
||||
onInterrupt()
|
||||
onStartListening()
|
||||
},
|
||||
)
|
||||
},
|
||||
onRelease = onStopListening,
|
||||
)
|
||||
} else {
|
||||
Modifier.clickable {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onStopListening = onStopListening,
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.size(size)
|
||||
.clip(CircleShape)
|
||||
.clickable {
|
||||
dispatchMicAction(
|
||||
uiState = uiState,
|
||||
onStartListening = onStartListening,
|
||||
onStopListening = onStopListening,
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
},
|
||||
.testTag(VOICE_OVERLAY_MIC_CONTROL_TEST_TAG)
|
||||
.then(gestureModifier),
|
||||
shape = CircleShape,
|
||||
color = when {
|
||||
isStopAction -> Color(0xFFE53935)
|
||||
@@ -895,7 +984,11 @@ private fun MicControlButton(
|
||||
Icons.Filled.Stop
|
||||
else -> Icons.Filled.Mic
|
||||
},
|
||||
contentDescription = stringResource(R.string.voice_overlay_mic_a11y),
|
||||
contentDescription = if (uiState.interactionMode == InteractionMode.HoldToTalk) {
|
||||
null
|
||||
} else {
|
||||
actionDescription
|
||||
},
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
@@ -903,39 +996,6 @@ private fun MicControlButton(
|
||||
}
|
||||
}
|
||||
|
||||
private fun dispatchMicAction(
|
||||
uiState: VoiceUiState,
|
||||
onStartListening: () -> Unit,
|
||||
onStopListening: () -> Unit,
|
||||
onInterrupt: () -> Unit,
|
||||
onPauseAutoMode: () -> Unit,
|
||||
) {
|
||||
when (uiState.state) {
|
||||
VoiceState.Listening -> {
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
onPauseAutoMode()
|
||||
} else {
|
||||
onStopListening()
|
||||
}
|
||||
}
|
||||
VoiceState.Speaking -> {
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
onPauseAutoMode()
|
||||
} else {
|
||||
onInterrupt()
|
||||
}
|
||||
}
|
||||
VoiceState.Transcribing, VoiceState.Thinking -> {
|
||||
if (uiState.interactionMode == InteractionMode.Continuous) {
|
||||
onPauseAutoMode()
|
||||
} else {
|
||||
onInterrupt()
|
||||
}
|
||||
}
|
||||
VoiceState.Idle, VoiceState.Error -> onStartListening()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusChip(
|
||||
text: String,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<string name="agent_interface">interface do agente</string>
|
||||
<string name="notification_companion_label">assistente de notificações do Hermes-Relay</string>
|
||||
<string name="onboarding_skip_setup_title">Pular a configuração?</string>
|
||||
<string name="onboarding_skip_setup_text">Sem problema — você pode explorar a demonstração para ver como o Hermes-Relay funciona e conectar seu próprio servidor Hermes a qualquer momento em Configurações → Conexões. O pareamento com o Relay para usar ferramentas avançadas também pode ser adicionado depois.</string>
|
||||
<string name="onboarding_skip_setup_text">Sem problema — você pode explorar a demonstração e adicionar seu próprio gateway Hermes a qualquer momento em Configurações → Gateways. O pareamento com o Relay para ferramentas avançadas também pode ser adicionado depois.</string>
|
||||
<string name="onboarding_skip_for_now">Pular por enquanto</string>
|
||||
<string name="onboarding_go_back">Voltar</string>
|
||||
<string name="onboarding_skip">Pular</string>
|
||||
@@ -136,7 +136,7 @@
|
||||
<string name="chat_editing_notice">Editando — a conversa será retrocedida</string>
|
||||
<string name="chat_mic_perm_needed">Permissão do microfone necessária</string>
|
||||
<string name="chat_mic_perm_body">Toque em Abrir Configurações e permita o acesso ao microfone para usar o modo de voz.</string>
|
||||
<string name="chat_manage_connections">Gerenciar conexões</string>
|
||||
<string name="chat_manage_connections">Gerenciar gateways</string>
|
||||
<string name="chat_no_clipboard_image">Nenhuma imagem na área de transferência</string>
|
||||
<string name="chat_copied_to_clipboard">Copiado para a área de transferência</string>
|
||||
<string name="chat_camera_open_failed">Não foi possível abrir a câmera</string>
|
||||
@@ -194,7 +194,7 @@
|
||||
<string name="conn_label_route">Rota</string>
|
||||
<string name="conn_label_status">Status</string>
|
||||
<string name="conn_label_connect">Conectar</string>
|
||||
<string name="conn_label_connections">Conexões</string>
|
||||
<string name="conn_label_connections">Gateways</string>
|
||||
<string name="conn_detail_add_connection">Adicione uma conexão de API/painel do Hermes padrão</string>
|
||||
<string name="conn_detail_waiting_network">Aguardando o Android informar uma rota de internet</string>
|
||||
<string name="conn_detail_chat_unavailable">As chamadas de chat e perfil podem não estar disponíveis</string>
|
||||
@@ -276,19 +276,19 @@
|
||||
<string name="error_classify_retry">Tentar novamente</string>
|
||||
<string name="error_classify_open_settings">Abrir Configurações</string>
|
||||
<!-- Connection wizard — Connect page essentials -->
|
||||
<string name="cw_connect_to_hermes">Conectar ao Hermes</string>
|
||||
<string name="cw_connect_to_hermes">Adicionar gateway</string>
|
||||
<string name="cw_nearby_description">Vamos procurar o Hermes nesta rede. O Painel e o Gateway fornecem a conexão padrão para Chat, Gerenciar e Voz.</string>
|
||||
<string name="cw_connection_chooser_description">Escolha a configuração que você tem. O Hermes Relay é opcional.</string>
|
||||
<string name="cw_connection_chooser_description">Um gateway é uma instalação do Hermes. Escolha como este telefone pode acessá-lo.</string>
|
||||
<string name="cw_scan_setup_qr_title">Ler QR de configuração do Hermes</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">Configure rotas locais, remotas e do Relay disponíveis</string>
|
||||
<string name="cw_recommended">Recomendado</string>
|
||||
<string name="cw_other_ways_to_connect">Outras formas de conectar</string>
|
||||
<string name="cw_other_ways_to_connect">Escolha um gateway</string>
|
||||
<string name="cw_advanced">Avançado</string>
|
||||
<string name="cw_cloud_title">Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
|
||||
<string name="cw_server_vps_title">Servidor ou VPS</string>
|
||||
<string name="cw_server_vps_subtitle">Insira um endereço seguro do Painel</string>
|
||||
<string name="cw_relay_optional_note">Chat, Gerenciar e Voz padrão funcionam sem o Relay. QRs de configuração compatíveis adicionam recursos avançados do Relay quando disponíveis.</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_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>
|
||||
@@ -315,7 +315,7 @@
|
||||
<string name="cw_nearby_search_again">Pesquisar novamente</string>
|
||||
<string name="cw_nearby_enter_address">Informar endereço</string>
|
||||
<string name="cw_other_connection_methods">Outros métodos de conexão</string>
|
||||
<string name="cw_manual_hermes_title">Informe o endereço do Hermes</string>
|
||||
<string name="cw_manual_hermes_title">Informe o endereço do gateway</string>
|
||||
<string name="cw_manual_hermes_description">Informe o endereço do Painel usado no navegador. Se ele não abrir neste celular, inicie hermes dashboard e verifique o Wi-Fi ou o Tailscale.</string>
|
||||
<string name="cw_hermes_address">Endereço do Hermes</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 ou hermes.example.com</string>
|
||||
@@ -401,6 +401,13 @@
|
||||
<string name="cw_pairing_code_label">Código de pareamento</string>
|
||||
<string name="cw_pairing_code_placeholder">ex.: ABC123</string>
|
||||
<string name="cw_pair_button">Parear</string>
|
||||
<string name="cw_mixed_route_plain">%1$s usa HTTP/WS sem criptografia. Use somente em uma rede privada confiável ou por uma VPN sob seu controle.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s usa HTTPS/WSS com criptografia de transporte.</string>
|
||||
<string name="cw_mixed_safe">O app verifica estas rotas e seleciona uma disponível. Você pode alterar a rota preferida depois.</string>
|
||||
<string name="cw_pair_in_progress">Processando…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">Preparando o gateway…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">Abrindo o login seguro…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Pareando o Relay…</string>
|
||||
<string name="cw_show_code_subtitle">Use isto quando não puder ler um QR de pareamento do Relay. Defina suas URLs e registre o código abaixo no host que executa o Hermes-Relay.</string>
|
||||
<string name="cw_step_copy_code">1. Copie este código</string>
|
||||
<string name="cw_copy_pairing_code">Copiar código de pareamento</string>
|
||||
@@ -419,9 +426,6 @@
|
||||
<string name="cw_insecure_relay_warning">Este relay usa ws:// sem criptografia — o tráfego não é criptografado.</string>
|
||||
<string name="cw_insecure_relay_trust">Continue somente se confiar na rede em qualquer conexão (LAN, Tailscale, VPN).</string>
|
||||
<string name="cw_insecure_ack">Entendo que este pareamento envia o tráfego como texto simples — visível para qualquer pessoa na rede.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s usa ws:// sem criptografia — adequado em casa ou no escritório, mas não em Wi-Fi público.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s é criptografada (wss://), e o app a usa automaticamente quando %2$s está inacessível.</string>
|
||||
<string name="cw_mixed_safe">Você está protegido em qualquer rede.</string>
|
||||
<string name="cw_connecting_to_hermes">Conectando ao Hermes</string>
|
||||
<string name="cw_connecting_detail">Verificando o servidor API, a chave salva e o painel.</string>
|
||||
<string name="cw_pairing_title">Pareando…</string>
|
||||
@@ -447,7 +451,7 @@
|
||||
<string name="cw_voice_after_connect">Verificada após a conexão</string>
|
||||
<string name="cw_remote">Remoto</string>
|
||||
<string name="cw_remote_fallback_ready">Rota alternativa pronta para uso fora de casa</string>
|
||||
<string name="cw_remote_lan_only">Somente LAN — adicione uma rota do Tailscale ou pública em Configurações → Conexões → Rotas</string>
|
||||
<string name="cw_remote_lan_only">Somente LAN — adicione uma rota do Tailscale ou pública em Configurações → Gateways → Rotas</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">Ferramentas avançadas pareadas</string>
|
||||
<string name="cw_relay_optional">Opcional para Terminal e Bridge</string>
|
||||
@@ -466,6 +470,17 @@
|
||||
<string name="endpoints_preferred">Preferencial</string>
|
||||
<string name="endpoints_automatic">Automática</string>
|
||||
<string name="endpoints_current_route">Rota atual: %1$s (%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">Nenhuma rota alternativa está selecionada no momento.</string>
|
||||
<string name="endpoints_selection_reason">Prioridade %1$d (0 é a mais alta) · %2$s</string>
|
||||
<string name="endpoints_reachable_now">Acessível agora</string>
|
||||
<string name="endpoints_last_check_failed">A última verificação falhou</string>
|
||||
<string name="endpoints_reachability_not_checked">A acessibilidade não foi verificada</string>
|
||||
<string name="endpoints_security_application_tls">TLS da aplicação</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Criptografado pelo Tailscale · sem TLS da aplicação</string>
|
||||
<string name="endpoints_security_wireguard_overlay">Criptografado pelo WireGuard · sem TLS da aplicação</string>
|
||||
<string name="endpoints_security_secure_link">Criptografado pelo Hermes Secure Link</string>
|
||||
<string name="endpoints_security_private_plain">Rede privada · sem TLS da aplicação</string>
|
||||
<string name="endpoints_security_public_plain">A rota pública não está criptografada</string>
|
||||
<string name="endpoints_cancel_manual_switch">Cancelar troca manual — voltar para %1$s</string>
|
||||
<string name="endpoints_stop_preferring">Parar de preferir — voltar ao modo automático</string>
|
||||
<string name="endpoints_checking">Verificando…</string>
|
||||
@@ -635,7 +650,7 @@
|
||||
<string name="relay_state_needs_repair">Precisa parear novamente</string>
|
||||
<string name="settings_no_connection">Sem conexão</string>
|
||||
<string name="settings_server_default">Padrão do servidor</string>
|
||||
<string name="settings_connections">Conexões</string>
|
||||
<string name="settings_connections">Gateways</string>
|
||||
<string name="settings_connections_desc">API, painel, pareamento com o relay e rotas</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
|
||||
@@ -774,15 +789,32 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">O Gateway exige login em Gerenciar</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Entre uma vez pela aba Gerenciar para liberar o pensamento ao vivo por /api/ws.</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Entre uma vez para liberar Chat, sessões, Gerenciar e voz padrão nesta conexão Hermes.</string>
|
||||
<string name="chat_settings_completions">Completions</string>
|
||||
<string name="chat_settings_offline">offline</string>
|
||||
<!-- P0: ConnectionsSettingsScreen -->
|
||||
<string name="conn_back">Voltar</string>
|
||||
<string name="conn_title">Conexões</string>
|
||||
<string name="conn_add_connection">Adicionar conexão</string>
|
||||
<string name="conn_no_connections">Ainda não há conexões</string>
|
||||
<string name="conn_no_connections_desc">Toque em Adicionar conexão para se conectar ao Hermes.</string>
|
||||
<string name="conn_title">Gateways</string>
|
||||
<string name="conn_add_connection">Adicionar gateway</string>
|
||||
<string name="conn_no_connections">Ainda não há gateways</string>
|
||||
<string name="conn_no_connections_desc">Toque em Adicionar gateway para se conectar ao Hermes.</string>
|
||||
<string name="gateways_title">Gateways</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d gateway</item><item quantity="other">%d gateways</item></plurals>
|
||||
<string name="gateway_add">Adicionar gateway</string>
|
||||
<string name="gateways_empty_title">Ainda não há gateways</string>
|
||||
<string name="gateways_empty_body">Adicione um gateway para conectar este telefone ao Hermes.</string>
|
||||
<string name="gateway_route_not_configured">Nenhuma rota configurada</string>
|
||||
<string name="gateway_status_online">Gateway online</string>
|
||||
<string name="gateway_status_sign_in_required">Login necessário</string>
|
||||
<string name="gateway_status_offline">Gateway offline</string>
|
||||
<string name="gateway_status_checking">Verificando gateway…</string>
|
||||
<string name="gateway_status_not_checked">Gateway não verificado</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">Última verificação: login necessário</string>
|
||||
<string name="gateway_status_last_check_succeeded">Última verificação concluída</string>
|
||||
<string name="gateway_status_last_check_failed">Falha na última verificação</string>
|
||||
<string name="gateway_status_no_route">Sem rota de gateway</string>
|
||||
<string name="gateway_status_unavailable">Gateway indisponível</string>
|
||||
<string name="conn_add_requires_parent_access">Desbloqueie o acesso dos responsáveis antes de adicionar um gateway.</string>
|
||||
<string name="conn_active">Ativa</string>
|
||||
<string name="conn_connected">Conectado</string>
|
||||
<string name="conn_standard_not_paired">Padrão · Relay não pareado</string>
|
||||
@@ -858,6 +890,8 @@
|
||||
<string name="detail_tab_routes">Rotas</string>
|
||||
<string name="detail_tab_advanced">Avançado</string>
|
||||
<string name="detail_tab_security">Segurança</string>
|
||||
<string name="detail_tab_access">Acesso</string>
|
||||
<string name="detail_current_route">Rota atual</string>
|
||||
<!-- P0: SessionDrawer -->
|
||||
<string name="bot_mode_title">Modo Bot</string>
|
||||
<string name="bot_mode_drawer_summary">Bots e salas em grupo</string>
|
||||
@@ -916,6 +950,8 @@
|
||||
<string name="drawer_delete_session_title">Excluir sessão?</string>
|
||||
<string name="drawer_delete_session_prefix">Isso excluirá permanentemente \"</string>
|
||||
<string name="drawer_delete_session_suffix">\" e o histórico de mensagens.</string>
|
||||
<string name="drawer_remove_provisional_thread_title">Remover Thread?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">Isso remove \"%1$s\" deste dispositivo. O histórico promovido ou armazenado no servidor não será excluído.</string>
|
||||
<string name="drawer_untitled">Sem título</string>
|
||||
<string name="drawer_delete">Excluir</string>
|
||||
<string name="drawer_thread">Thread</string>
|
||||
@@ -945,7 +981,7 @@
|
||||
<string name="bridge_relay_label">relay</string>
|
||||
<string name="bridge_safety_label">segurança</string>
|
||||
<string name="bridge_not_connected_title">Relay desconectado</string>
|
||||
<string name="bridge_not_connected_body">Os comandos do Bridge trafegam pelo relay. Pareie um relay em Configurações → Conexões para que o Bridge realmente funcione.</string>
|
||||
<string name="bridge_not_connected_body">Os comandos do Bridge trafegam pelo Relay. Pareie o Relay em Configurações → Gateways para usar o Bridge.</string>
|
||||
<string name="bridge_accessibility_needed">O Serviço de acessibilidade precisa ser ativado primeiro.</string>
|
||||
<string name="bridge_open_settings">Abrir Configurações</string>
|
||||
<string name="bridge_allow_agent_control">Permitir Controle do agente</string>
|
||||
@@ -981,8 +1017,8 @@
|
||||
<string name="bridge_core_relay_body">O Núcleo do Bridge usa a mesma sessão pareada do relay que os recursos de terminal, notificações, mídia e voz.</string>
|
||||
<string name="bridge_core_surface_title">Superfície do Bridge</string>
|
||||
<string name="bridge_core_surface_meta">não oculta nas configurações</string>
|
||||
<string name="bridge_core_connections">Conexões</string>
|
||||
<string name="bridge_core_connections_sub">Pareie, alterne e verifique as rotas do relay</string>
|
||||
<string name="bridge_core_connections">Gateways</string>
|
||||
<string name="bridge_core_connections_sub">Pareie o Relay, alterne gateways e verifique rotas</string>
|
||||
<string name="bridge_core_terminal_tile">Terminal</string>
|
||||
<string name="bridge_core_terminal_sub">Conecte-se ao terminal do relay do Hermes</string>
|
||||
<string name="bridge_core_voice">Voz</string>
|
||||
@@ -1331,7 +1367,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Permitir que o Hermes me envie mensagens</string>
|
||||
<string name="proactive_allow_proactive_messages">Permitir mensagens proativas</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">Seu agente pode entrar em contato por conta própria — lembretes, tarefas concluídas e alertas. As mensagens aparecem como Threads no Chat, onde você pode responder.</string>
|
||||
<string name="proactive_not_paired_warning">Ainda não pareado — faça o pareamento com seu servidor Hermes em Configurações → Conexões para começar a receber mensagens.</string>
|
||||
<string name="proactive_not_paired_warning">Ainda não pareado — pareie o Relay em Configurações → Gateways para começar a receber mensagens.</string>
|
||||
<string name="proactive_your_threads">Suas Threads</string>
|
||||
<string name="proactive_your_threads_desc">Cada conversa iniciada pelo agente aparece como uma Thread no Chat — abra a lista de sessões, filtre por Threads e responda ali mesmo.</string>
|
||||
<string name="proactive_open_chat">Abrir Chat</string>
|
||||
@@ -1513,7 +1549,7 @@
|
||||
<string name="voice_settings_engine_realtime">Agente em tempo real</string>
|
||||
<string name="voice_settings_engine_realtime_desc">Fala em tempo real nativa do provedor com ferramentas intermediadas pelo Hermes. Exige um Relay pareado.</string>
|
||||
<string name="voice_settings_experimental">Experimental</string>
|
||||
<string name="voice_settings_realtime_no_relay">Nenhum Relay está configurado para esta conexão, então o Agente em tempo real não pode iniciar. Pareie o Relay em Configurações → Conexões ou volte para Chat do Hermes + saída de voz.</string>
|
||||
<string name="voice_settings_realtime_no_relay">Nenhum Relay está configurado para este gateway, então o Agente em tempo real não pode iniciar. Pareie o Relay em Configurações → Gateways ou volte para Chat do Hermes + saída de voz.</string>
|
||||
<string name="voice_settings_route_label">Rota STT/TTS</string>
|
||||
<string name="voice_settings_status_ready">Pronta</string>
|
||||
<string name="voice_settings_status_sign_in_required">É necessário entrar no painel</string>
|
||||
@@ -1731,8 +1767,8 @@
|
||||
<string name="dashboard_tile_config_title">Configuração</string>
|
||||
<string name="dashboard_tile_config_sub">Esquema e opções de runtime</string>
|
||||
<!-- Nav tiles -->
|
||||
<string name="dashboard_nav_connections_title">Conexões</string>
|
||||
<string name="dashboard_nav_connections_sub">Pareie, alterne e verifique as rotas</string>
|
||||
<string name="dashboard_nav_connections_title">Gateways</string>
|
||||
<string name="dashboard_nav_connections_sub">Entre, pareie o Relay, alterne e verifique rotas</string>
|
||||
<!-- Hub header -->
|
||||
<string name="dashboard_hub_title">Central do Relay</string>
|
||||
<string name="dashboard_hub_meta">visão geral</string>
|
||||
@@ -1762,7 +1798,7 @@
|
||||
<string name="dashboard_hours_ago">há %1$d h</string>
|
||||
<!-- Sign-in card -->
|
||||
<string name="dashboard_signin_required_title">É necessário entrar no painel</string>
|
||||
<string name="dashboard_signin_required_body">O Gerenciar usa a sessão do painel do Hermes em %1$s.</string>
|
||||
<string name="dashboard_signin_required_body">Entre no Hermes em %1$s para usar Chat, sessões, Gerenciar e voz padrão.</string>
|
||||
<string name="dashboard_signin_route_hint">Não foi possível reutilizar a sessão salva do painel pela rota %1$s. Entre novamente para atualizá-la nas rotas confiáveis desta conexão.</string>
|
||||
<string name="dashboard_signin_with_provider">Entrar com %1$s</string>
|
||||
<string name="dashboard_username_password">Nome de usuário e senha</string>
|
||||
@@ -1771,6 +1807,7 @@
|
||||
<string name="dashboard_sign_in">Entrar</string>
|
||||
<string name="dashboard_signing_in">Entrando…</string>
|
||||
<string name="dashboard_no_supported_provider">Este painel não anunciou um provedor de login compatível com o Android.</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">O provedor de login salvo não está disponível. Escolha outro provedor configurado ou tente novamente mais tarde.</string>
|
||||
<!-- OAuth sign-in dialog -->
|
||||
<string name="dashboard_oauth_initial_status">Conclua o login na página segura do painel.</string>
|
||||
<string name="dashboard_oauth_verifying">Verificando a sessão do painel…</string>
|
||||
@@ -2199,6 +2236,8 @@
|
||||
<string name="active_section_no_response_from_relay">Sem resposta do relay</string>
|
||||
<string name="active_section_no_route_reachable">Nenhuma rota acessível</string>
|
||||
<string name="active_section_no_routes_answered_probe">Nenhuma rota respondeu ao teste</string>
|
||||
<string name="active_section_no_reachable_route_title">Nenhuma rota do Gateway está acessível</string>
|
||||
<string name="active_section_no_reachable_route_body">Nenhuma das rotas configuradas do Gateway respondeu. Ative o Tailscale, o Wi-Fi ou os dados móveis e verifique novamente. Expanda uma rota abaixo para ver os resultados do Dashboard, da API e do Relay.</string>
|
||||
<string name="active_section_not_advertised">Não anunciado</string>
|
||||
<string name="active_section_not_checked">Não verificado</string>
|
||||
<string name="active_section_not_configured">Não configurado</string>
|
||||
@@ -2331,7 +2370,7 @@
|
||||
<string name="conn_info_loading_profiles">Carregando perfis…</string>
|
||||
<string name="conn_info_local_display_name">Nome de exibição local</string>
|
||||
<string name="conn_info_locked_to">Bloqueado em %1$s</string>
|
||||
<string name="conn_info_manage_connections">Gerenciar conexões</string>
|
||||
<string name="conn_info_manage_connections">Gerenciar gateways</string>
|
||||
<string name="conn_info_manage_profiles">Gerenciar exibição de perfis</string>
|
||||
<string name="conn_info_manage_profiles_hint">Reordene os perfis ou oculte os que você não usa. O perfil ativo permanece visível.</string>
|
||||
<string name="conn_info_move_profile_up">Mover %1$s para cima</string>
|
||||
@@ -2593,8 +2632,8 @@
|
||||
<string name="conn_security_learn_more">Saiba mais sobre a segurança da conexão →</string>
|
||||
<!-- ConnectionSwitcherSheet -->
|
||||
<string name="conn_switcher_title">Alternar conexão</string>
|
||||
<string name="conn_switcher_empty">Ainda não há conexões</string>
|
||||
<string name="conn_switcher_manage">Gerenciar conexões…</string>
|
||||
<string name="conn_switcher_empty">Ainda não há gateways</string>
|
||||
<string name="conn_switcher_manage">Gerenciar gateways…</string>
|
||||
<!-- DiagnosticsLogPanel -->
|
||||
<string name="diagnostics_title">Atividade recente</string>
|
||||
<string name="diagnostics_clear">Limpar</string>
|
||||
@@ -2935,7 +2974,7 @@
|
||||
<string name="screen_bridge_label">Bridge</string>
|
||||
<string name="screen_manage_label">Gerenciar</string>
|
||||
<string name="screen_settings_label">Configurações</string>
|
||||
<string name="screen_connections_label">Conexões</string>
|
||||
<string name="screen_connections_label">Gateways</string>
|
||||
<string name="screen_connection_label">Conexão</string>
|
||||
<string name="screen_voice_label">Voz</string>
|
||||
<string name="screen_notification_companion_label">Assistente de notificações</string>
|
||||
@@ -3017,7 +3056,7 @@
|
||||
<string name="cw_hint_chat">Chat</string>
|
||||
<string name="cw_hint_manage">Gerenciar</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s espera http:// ou https:// (hosts sem esquema recebem http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s espera http:// ou https:// (hosts privados usam http://; hosts públicos usam https://)</string>
|
||||
<string name="cw_label_api_key">Chave da API</string>
|
||||
<string name="cw_label_api_server">Servidor API</string>
|
||||
<string name="cw_label_dashboard">Painel</string>
|
||||
@@ -3070,7 +3109,7 @@
|
||||
<string name="cw_step_3_3">Etapa 3 de 3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Rede Tailscale detectada</string>
|
||||
<string name="cw_tailscale_supporting_other">Quando estiver fora da rede do servidor, você poderá alterar manualmente o tempo limite, o endereço, a porta da API (8642) e os padrões de http:// em Configurações → Conexões → Rotas.</string>
|
||||
<string name="cw_tailscale_supporting_other">Quando estiver fora da rede do servidor, você poderá alterar o tempo limite, o endereço, a porta da API (8642) e os padrões de http:// em Configurações → Gateways → Rotas.</string>
|
||||
<string name="cw_value_derived">Detectado automaticamente</string>
|
||||
<string name="cw_value_included">Incluído</string>
|
||||
<string name="cw_value_not_included">Não incluído</string>
|
||||
@@ -3263,6 +3302,7 @@
|
||||
<string name="card_send_answer_a11y">Enviar resposta</string>
|
||||
<string name="card_submit">Enviar</string>
|
||||
<string name="card_answer_placeholder">Digite uma resposta…</string>
|
||||
<string name="card_other_answer_placeholder">Outra (digite sua resposta)…</string>
|
||||
<string name="session_ttl_title">Manter este pareamento por…</string>
|
||||
<string name="session_ttl_intro">Seu celular se reconectará automaticamente durante este período. Você pode revogar o pareamento a qualquer momento.</string>
|
||||
<string name="session_ttl_stays_paired">Este dispositivo permanecerá pareado até você revogá-lo.</string>
|
||||
@@ -3320,7 +3360,7 @@
|
||||
<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>
|
||||
<string name="active_section_scan_relay_qr">Escanear QR do Relay</string>
|
||||
<string name="active_section_other_relay_methods">Outros métodos de pareamento</string>
|
||||
<string name="active_section_direct_relay_endpoint">Endpoint direto do Relay</string>
|
||||
<string name="cw_pair_relay_for">Emparelhar Relay com %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Adicione a extensão opcional Relay a esta conexão Hermes salva. Isso não adiciona nem substitui um servidor.</string>
|
||||
<string name="cw_current_connection">Conexão atual</string>
|
||||
@@ -3408,7 +3448,8 @@
|
||||
<string name="dev_settings_image_generation_lab">Laboratório de geração de imagens</string>
|
||||
<string name="dev_settings_image_generation_lab_desc">Visualize os ciclos de geração e a revelação final da imagem</string>
|
||||
<string name="dev_settings_open_image_generation_lab_cd">Abrir o laboratório de geração de imagens</string>
|
||||
<string name="dashboard_native_signin_opening">Conclua o login no navegador e volte aqui.</string>
|
||||
<string name="dashboard_native_signin_opening">Conclua o login no navegador. Se o provedor fizer login sem retornar, volte e toque em Continuar login.</string>
|
||||
<string name="dashboard_native_signin_continue">Continuar login</string>
|
||||
<string name="dashboard_native_signin_cancelled">Login pelo navegador cancelado.</string>
|
||||
<string name="dashboard_native_signin_requires_https">O login seguro pelo navegador exige um endereço HTTPS do painel.</string>
|
||||
<string name="dashboard_native_signin_unavailable">O login seguro pelo navegador não está disponível para esta conexão. Atualize a conexão e tente novamente.</string>
|
||||
@@ -3865,6 +3906,9 @@
|
||||
<string name="plugins_remove">Remover</string>
|
||||
<string name="plugins_remove_confirm">Remover “%1$s”? Esta página do plugin não aparecerá mais nos dispositivos Android conectados.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">Verificação de repositórios no host</string>
|
||||
<string name="git_state_host_scanning_on_desc">Ativado para este gateway · As gravações do Git continuam exigindo permissão separada.</string>
|
||||
<string name="git_state_host_scanning_off_desc">Permite que este telefone solicite ao gateway a verificação das raízes Git configuradas em busca de repositórios, branches e alterações. As gravações do Git exigem permissão separada.</string>
|
||||
<string name="git_state_back">Voltar</string>
|
||||
<string name="git_state_staged">Preparados</string>
|
||||
<string name="git_state_modified">Modificados</string>
|
||||
@@ -3908,7 +3952,7 @@
|
||||
<string name="git_state_switch_stash">Alternar (guardar se houver alterações)</string>
|
||||
<string name="support_bundle_review">Revisar informações de suporte</string>
|
||||
<string name="support_bundle_title">Informações de suporte</string>
|
||||
<string name="support_bundle_privacy">Nada é enviado automaticamente. Revise a exportação local com até %1$d relatórios.</string>
|
||||
<string name="support_bundle_privacy">Nada é enviado automaticamente. Revise a exportação local com %1$d relatórios e diagnósticos recentes.</string>
|
||||
<string name="support_bundle_copied">Informações de suporte copiadas</string>
|
||||
<string name="support_bundle_no_share">Informações de suporte copiadas — nenhum app encontrado para compartilhar</string>
|
||||
<string name="support_bundle_share_title">Compartilhar informações de suporte do Hermes-Relay</string>
|
||||
@@ -4272,7 +4316,7 @@
|
||||
<string name="custom_theme_modified">Alterações não salvas</string>
|
||||
<string name="custom_theme_saved_count">%1$d temas salvos</string>
|
||||
<string name="chat_settings_show_git_workspace">Mostrar o espaço de trabalho Git no chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Mostra a branch e as alterações acima do campo de mensagem</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Mostra o status do Git e as alterações no Chat quando a verificação de repositórios no host está ativada. O espaço de trabalho Git completo continua disponível quando isto está desativado.</string>
|
||||
<string name="chat_git_open_workspace">Abrir o espaço de trabalho Git</string>
|
||||
<string name="chat_git_branch">Branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d adições</string>
|
||||
@@ -4280,4 +4324,86 @@
|
||||
<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="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>
|
||||
<string name="current_chat_activity_summary">%1$d agentes · %2$d processos</string>
|
||||
<string name="current_chat_activity_close">Fechar prévia da atividade</string>
|
||||
<string name="current_chat_activity_empty">Nenhuma atividade atual neste chat</string>
|
||||
<string name="current_chat_activity_latest">Mais recente</string>
|
||||
<string name="agent_activity_section">Atividade ao vivo dos agentes</string>
|
||||
<string name="agent_activity_disclosure">Atualizações recebidas por este chat. O histórico completo do agente filho pode não estar disponível.</string>
|
||||
<string name="agent_activity_fallback">Agente %d</string>
|
||||
<string name="agent_activity_task_position">%1$d de %2$d · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s, %2$s, agente %3$d de %4$d</string>
|
||||
<string name="agent_activity_duration">%1$.1fs</string>
|
||||
<string name="agent_activity_older_omitted">Atividade anterior omitida</string>
|
||||
<string name="agent_activity_partial">Atualizações ao vivo retomadas. Pode faltar atividade do período offline.</string>
|
||||
<string name="agent_activity_event_started">Iniciado</string>
|
||||
<string name="agent_activity_event_update">Atualização</string>
|
||||
<string name="agent_activity_event_tool">Prévia da ferramenta</string>
|
||||
<string name="agent_activity_status_started">Iniciando</string>
|
||||
<string name="agent_activity_status_thinking">Pensando</string>
|
||||
<string name="agent_activity_status_tool">Usando uma ferramenta</string>
|
||||
<string name="agent_activity_status_progress">Trabalhando</string>
|
||||
<string name="agent_activity_status_completed">Concluído</string>
|
||||
<string name="agent_activity_status_failed">Falhou</string>
|
||||
<string name="agent_activity_status_interrupted">Interrompido</string>
|
||||
<string name="agent_activity_status_unavailable">Estado final indisponível</string>
|
||||
<string name="agent_activity_child_loading">Abrindo histórico filho somente leitura…</string>
|
||||
<string name="agent_activity_child_unavailable">O histórico filho não está disponível nesta versão ou rota do Hermes. A atividade da sessão principal é mostrada acima.</string>
|
||||
<string name="agent_activity_child_live">Histórico filho · atualizações ao vivo</string>
|
||||
<string name="agent_activity_child_history">Histórico filho · somente leitura</string>
|
||||
<string name="agent_activity_child_truncated">Atividade filha recente exibida · detalhes antigos ou muito grandes foram omitidos</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Informe o endereço do Gateway Hermes</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">Endereço autenticado do Dashboard</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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_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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">Usar rota selecionada</string>
|
||||
<string name="active_section_use_selected_route_failed">Não foi possível voltar o login do Dashboard para a rota selecionada.</string>
|
||||
<string name="active_section_forget_sign_in_origin">Esquecer origem de login</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<string name="notification_companion_label">Hermes-Relay 通知助手</string>
|
||||
|
||||
<string name="onboarding_skip_setup_title">跳过设置?</string>
|
||||
<string name="onboarding_skip_setup_text">没问题,你可以先体验演示,看看 Hermes-Relay 的工作方式;以后也可以随时到“设置 → 连接”里接入自己的 Hermes 服务器。高级工具所需的 Relay 配对也可以稍后再添加。</string>
|
||||
<string name="onboarding_skip_setup_text">没问题,你可以先体验演示;以后也可以随时在“设置 → 网关”中添加自己的 Hermes 网关。高级工具所需的 Relay 配对也可以稍后添加。</string>
|
||||
<string name="onboarding_skip_for_now">暂时跳过</string>
|
||||
<string name="onboarding_go_back">返回</string>
|
||||
<string name="onboarding_skip">跳过</string>
|
||||
@@ -150,7 +150,7 @@
|
||||
<string name="chat_editing_notice">编辑中——将回退对话</string>
|
||||
<string name="chat_mic_perm_needed">需要麦克风权限</string>
|
||||
<string name="chat_mic_perm_body">点击“打开设置”并授予麦克风权限以使用语音模式。</string>
|
||||
<string name="chat_manage_connections">管理连接</string>
|
||||
<string name="chat_manage_connections">管理网关</string>
|
||||
<string name="chat_no_clipboard_image">剪贴板中没有图片</string>
|
||||
<string name="chat_copied_to_clipboard">已复制到剪贴板</string>
|
||||
<string name="chat_camera_open_failed">无法打开相机</string>
|
||||
@@ -211,7 +211,7 @@
|
||||
<string name="conn_label_route">路由</string>
|
||||
<string name="conn_label_status">状态</string>
|
||||
<string name="conn_label_connect">连接</string>
|
||||
<string name="conn_label_connections">连接管理</string>
|
||||
<string name="conn_label_connections">网关</string>
|
||||
<string name="conn_detail_add_connection">添加 Vanilla Hermes API/仪表盘连接</string>
|
||||
<string name="conn_detail_waiting_network">等待 Android 报告网络路由</string>
|
||||
<string name="conn_detail_chat_unavailable">聊天和个人资料调用可能不可用</string>
|
||||
@@ -297,19 +297,19 @@
|
||||
<string name="error_classify_open_settings">打开设置</string>
|
||||
|
||||
<!-- 连接向导 —— Connect 页核心文案 -->
|
||||
<string name="cw_connect_to_hermes">连接 Hermes</string>
|
||||
<string name="cw_connect_to_hermes">添加网关</string>
|
||||
<string name="cw_nearby_description">我们将在此网络中查找 Hermes。仪表板和网关提供聊天、管理和语音的标准连接。</string>
|
||||
<string name="cw_connection_chooser_description">请选择你现有的设置方式。Hermes Relay 为可选功能。</string>
|
||||
<string name="cw_connection_chooser_description">一个网关代表一套 Hermes 安装。请选择此手机访问它的方式。</string>
|
||||
<string name="cw_scan_setup_qr_title">扫描 Hermes 设置二维码</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">配置本地、远程及可用的 Relay 路由</string>
|
||||
<string name="cw_recommended">推荐</string>
|
||||
<string name="cw_other_ways_to_connect">其他连接方式</string>
|
||||
<string name="cw_other_ways_to_connect">选择网关</string>
|
||||
<string name="cw_advanced">高级</string>
|
||||
<string name="cw_cloud_title">Nous 托管的 Hermes</string>
|
||||
<string name="cw_cloud_subtitle">连接到你的托管智能体</string>
|
||||
<string name="cw_server_vps_title">服务器或 VPS</string>
|
||||
<string name="cw_server_vps_subtitle">输入安全的 Dashboard 地址</string>
|
||||
<string name="cw_relay_optional_note">标准聊天、管理和语音功能无需 Relay 即可使用。兼容的设置二维码会在可用时添加 Relay 高级功能。</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_cloud_entry_title">连接到 Nous 托管的 Hermes</string>
|
||||
<string name="cw_cloud_entry_description">输入 Nous Portal 中显示的智能体地址。找到 Hermes 后,你将安全登录。</string>
|
||||
<string name="cw_cloud_agent_name">智能体地址</string>
|
||||
@@ -336,7 +336,7 @@
|
||||
<string name="cw_nearby_search_again">重新搜索</string>
|
||||
<string name="cw_nearby_enter_address">改为输入地址</string>
|
||||
<string name="cw_other_connection_methods">其他连接方式</string>
|
||||
<string name="cw_manual_hermes_title">输入 Hermes 地址</string>
|
||||
<string name="cw_manual_hermes_title">输入网关地址</string>
|
||||
<string name="cw_manual_hermes_description">请输入你在浏览器中打开的仪表板地址。如果此手机无法打开,请启动 hermes dashboard 并检查 Wi-Fi 或 Tailscale。</string>
|
||||
<string name="cw_hermes_address">Hermes 地址</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 或 hermes.example.com</string>
|
||||
@@ -429,6 +429,13 @@
|
||||
<string name="cw_pairing_code_label">配对码</string>
|
||||
<string name="cw_pairing_code_placeholder">例如 ABC123</string>
|
||||
<string name="cw_pair_button">配对</string>
|
||||
<string name="cw_mixed_route_plain">%1$s 使用未加密的 HTTP/WS。请仅在受信任的专用网络或您控制的 VPN 中使用。</string>
|
||||
<string name="cw_mixed_route_secure">%1$s 使用带传输加密的 HTTPS/WSS。</string>
|
||||
<string name="cw_mixed_safe">应用会探测这些路由并选择可用路由。您可以稍后更改首选路由。</string>
|
||||
<string name="cw_pair_in_progress">正在处理…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">正在准备网关…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">正在打开安全登录…</string>
|
||||
<string name="cw_pair_status_pairing_relay">正在配对 Relay…</string>
|
||||
<string name="cw_show_code_subtitle">无法扫描 Relay 配对二维码时使用。设置您的地址,然后在运行 Hermes-Relay 的主机上注册下面的配对码。</string>
|
||||
<string name="cw_step_copy_code">1. 复制此配对码</string>
|
||||
<string name="cw_copy_pairing_code">复制配对码</string>
|
||||
@@ -447,9 +454,6 @@
|
||||
<string name="cw_insecure_relay_warning">此 Relay 使用明文 ws://——流量未加密。</string>
|
||||
<string name="cw_insecure_relay_trust">仅当您信任所有连接(LAN、Tailscale、VPN)的网络时才继续。</string>
|
||||
<string name="cw_insecure_ack">我了解此配对以明文形式发送流量——网络上的任何人都可以看到。</string>
|
||||
<string name="cw_mixed_route_plain">%1$s 使用明文 ws://——在家或办公室没问题,但不要在公共 Wi-Fi 上使用。</string>
|
||||
<string name="cw_mixed_route_secure">%1$s 已加密(wss://),当 %2$s 不可达时,应用会自动使用它。</string>
|
||||
<string name="cw_mixed_safe">在任何网络上您都是安全的。</string>
|
||||
<string name="cw_connecting_to_hermes">正在连接到 Hermes</string>
|
||||
<string name="cw_connecting_detail">正在检查 API 服务器、已保存的密钥和仪表盘。</string>
|
||||
<string name="cw_pairing_title">正在配对…</string>
|
||||
@@ -475,7 +479,7 @@
|
||||
<string name="cw_voice_after_connect">连接后检查</string>
|
||||
<string name="cw_remote">远程</string>
|
||||
<string name="cw_remote_fallback_ready">备用路由已准备好,可在远离家时使用</string>
|
||||
<string name="cw_remote_lan_only">仅 LAN——在 设置 → 连接 → 路由 中添加 Tailscale 或公共路由</string>
|
||||
<string name="cw_remote_lan_only">仅 LAN——在“设置 → 网关 → 路由”中添加 Tailscale 或公共路由</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">高级工具已配对</string>
|
||||
<string name="cw_relay_optional">终端和 Bridge 可选</string>
|
||||
@@ -495,6 +499,17 @@
|
||||
<string name="endpoints_preferred">首选</string>
|
||||
<string name="endpoints_automatic">自动</string>
|
||||
<string name="endpoints_current_route">当前路由:%1$s(%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">当前未选择备用路由。</string>
|
||||
<string name="endpoints_selection_reason">优先级 %1$d(0 最高)· %2$s</string>
|
||||
<string name="endpoints_reachable_now">当前可达</string>
|
||||
<string name="endpoints_last_check_failed">上次检查失败</string>
|
||||
<string name="endpoints_reachability_not_checked">尚未检查可达性</string>
|
||||
<string name="endpoints_security_application_tls">应用层 TLS</string>
|
||||
<string name="endpoints_security_tailscale_overlay">由 Tailscale 加密 · 无应用层 TLS</string>
|
||||
<string name="endpoints_security_wireguard_overlay">由 WireGuard 加密 · 无应用层 TLS</string>
|
||||
<string name="endpoints_security_secure_link">由 Hermes Secure Link 加密</string>
|
||||
<string name="endpoints_security_private_plain">专用网络 · 无应用层 TLS</string>
|
||||
<string name="endpoints_security_public_plain">公共路由未加密</string>
|
||||
<string name="endpoints_cancel_manual_switch">取消手动切换——恢复到 %1$s</string>
|
||||
<string name="endpoints_stop_preferring">取消首选——恢复到自动</string>
|
||||
<string name="endpoints_checking">检测中…</string>
|
||||
@@ -674,7 +689,7 @@
|
||||
<string name="relay_state_needs_repair">需要重新配对</string>
|
||||
<string name="settings_no_connection">无连接</string>
|
||||
<string name="settings_server_default">服务器默认</string>
|
||||
<string name="settings_connections">连接</string>
|
||||
<string name="settings_connections">网关</string>
|
||||
<string name="settings_connections_desc">API、仪表盘、Relay 配对和路由</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
@@ -814,16 +829,33 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">网关需要管理登录</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">从管理标签页登录一次以解锁 /api/ws 上的实时思考。</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">登录一次即可为此 Hermes 连接启用 Chat、会话、管理和标准语音。</string>
|
||||
<string name="chat_settings_completions">Completions</string>
|
||||
<string name="chat_settings_offline">离线</string>
|
||||
|
||||
<!-- P0: ConnectionsSettingsScreen -->
|
||||
<string name="conn_back">返回</string>
|
||||
<string name="conn_title">连接</string>
|
||||
<string name="conn_add_connection">添加连接</string>
|
||||
<string name="conn_no_connections">暂无连接</string>
|
||||
<string name="conn_no_connections_desc">点击添加连接以连接到 Hermes。</string>
|
||||
<string name="conn_title">网关</string>
|
||||
<string name="conn_add_connection">添加网关</string>
|
||||
<string name="conn_no_connections">暂无网关</string>
|
||||
<string name="conn_no_connections_desc">点击添加网关以连接到 Hermes。</string>
|
||||
<string name="gateways_title">网关</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d 个网关</item><item quantity="other">%d 个网关</item></plurals>
|
||||
<string name="gateway_add">添加网关</string>
|
||||
<string name="gateways_empty_title">暂无网关</string>
|
||||
<string name="gateways_empty_body">添加网关,将此手机连接到 Hermes。</string>
|
||||
<string name="gateway_route_not_configured">未配置路由</string>
|
||||
<string name="gateway_status_online">网关在线</string>
|
||||
<string name="gateway_status_sign_in_required">需要登录</string>
|
||||
<string name="gateway_status_offline">网关离线</string>
|
||||
<string name="gateway_status_checking">正在检查网关…</string>
|
||||
<string name="gateway_status_not_checked">尚未检查网关</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">上次检查:需要登录</string>
|
||||
<string name="gateway_status_last_check_succeeded">上次检查成功</string>
|
||||
<string name="gateway_status_last_check_failed">上次检查失败</string>
|
||||
<string name="gateway_status_no_route">无网关路由</string>
|
||||
<string name="gateway_status_unavailable">网关不可用</string>
|
||||
<string name="conn_add_requires_parent_access">添加网关前,请先解锁家长访问权限。</string>
|
||||
<string name="conn_active">活跃</string>
|
||||
<string name="conn_connected">已连接</string>
|
||||
<string name="conn_standard_not_paired">标准 · Relay 未配对</string>
|
||||
@@ -901,6 +933,8 @@
|
||||
<string name="detail_tab_routes">路由</string>
|
||||
<string name="detail_tab_advanced">高级</string>
|
||||
<string name="detail_tab_security">安全</string>
|
||||
<string name="detail_tab_access">访问</string>
|
||||
<string name="detail_current_route">当前路由</string>
|
||||
|
||||
<!-- P0: SessionDrawer -->
|
||||
<string name="bot_mode_title">Bot 模式</string>
|
||||
@@ -960,6 +994,8 @@
|
||||
<string name="drawer_delete_session_title">删除会话?</string>
|
||||
<string name="drawer_delete_session_prefix">这将永久删除\"</string>
|
||||
<string name="drawer_delete_session_suffix">\"及其消息历史。</string>
|
||||
<string name="drawer_remove_provisional_thread_title">移除话题?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">这会从此设备移除“%1$s”,不会删除已提升或服务器端的历史记录。</string>
|
||||
<string name="drawer_untitled">未命名</string>
|
||||
<string name="drawer_delete">删除</string>
|
||||
<string name="drawer_thread">话题</string>
|
||||
@@ -990,7 +1026,7 @@
|
||||
<string name="bridge_relay_label">relay</string>
|
||||
<string name="bridge_safety_label">安全</string>
|
||||
<string name="bridge_not_connected_title">Relay 未连接</string>
|
||||
<string name="bridge_not_connected_body">Bridge 命令通过 Relay 传输。在设置 → 连接中配对 Relay 才能让 Bridge 实际工作。</string>
|
||||
<string name="bridge_not_connected_body">Bridge 命令通过 Relay 传输。请在“设置 → 网关”中配对 Relay 以使用 Bridge。</string>
|
||||
<string name="bridge_accessibility_needed">必须先启用无障碍服务。</string>
|
||||
<string name="bridge_open_settings">打开设置</string>
|
||||
<string name="bridge_allow_agent_control">允许代理控制</string>
|
||||
@@ -1027,8 +1063,8 @@
|
||||
<string name="bridge_core_relay_body">Bridge 核心使用与终端、通知、媒体和语音功能相同的已配对 Relay 会话。</string>
|
||||
<string name="bridge_core_surface_title">Bridge 界面</string>
|
||||
<string name="bridge_core_surface_meta">未在设置中隐藏</string>
|
||||
<string name="bridge_core_connections">连接</string>
|
||||
<string name="bridge_core_connections_sub">配对、切换和验证 Relay 路由</string>
|
||||
<string name="bridge_core_connections">网关</string>
|
||||
<string name="bridge_core_connections_sub">配对 Relay、切换网关并验证路由</string>
|
||||
<string name="bridge_core_terminal_tile">终端</string>
|
||||
<string name="bridge_core_terminal_sub">连接到你的 Hermes Relay 终端</string>
|
||||
<string name="bridge_core_voice">语音</string>
|
||||
@@ -1386,7 +1422,7 @@
|
||||
<string name="proactive_let_hermes_message_me">让 Hermes 主动联系我</string>
|
||||
<string name="proactive_allow_proactive_messages">允许主动消息</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">您的代理可自行联系您——提醒、已完成的任务、警报。其消息会以 Threads 形式出现在聊天中,您可在其中回复。</string>
|
||||
<string name="proactive_not_paired_warning">尚未配对——请在 设置 → 连接 中与您的 Hermes 服务器配对以开始接收消息。</string>
|
||||
<string name="proactive_not_paired_warning">尚未配对——请在“设置 → 网关”中配对 Relay 以开始接收消息。</string>
|
||||
<string name="proactive_your_threads">您的 Threads</string>
|
||||
<string name="proactive_your_threads_desc">您的代理发起的每段对话都会以 Thread 形式出现在聊天中——打开会话列表,筛选 Threads,即可直接回复。</string>
|
||||
<string name="proactive_open_chat">打开聊天</string>
|
||||
@@ -1572,7 +1608,7 @@
|
||||
<string name="voice_settings_engine_realtime">实时 Agent</string>
|
||||
<string name="voice_settings_engine_realtime_desc">由提供商原生实时语音配合 Hermes 中介的工具。需要已配对的 Relay。</string>
|
||||
<string name="voice_settings_experimental">实验性</string>
|
||||
<string name="voice_settings_realtime_no_relay">此连接未配置 Relay,因此实时 Agent 无法启动。请在 设置 → 连接 中配对 Relay,或切回 Hermes 聊天 + 语音输出。</string>
|
||||
<string name="voice_settings_realtime_no_relay">此网关未配置 Relay,因此实时 Agent 无法启动。请在“设置 → 网关”中配对 Relay,或切回 Hermes 聊天 + 语音输出。</string>
|
||||
<string name="voice_settings_route_label">STT/TTS 路由</string>
|
||||
<string name="voice_settings_status_ready">就绪</string>
|
||||
<string name="voice_settings_status_sign_in_required">需要仪表板登录</string>
|
||||
@@ -1793,8 +1829,8 @@
|
||||
<string name="dashboard_tile_config_sub">Schema 与运行时选项</string>
|
||||
|
||||
<!-- Nav tiles -->
|
||||
<string name="dashboard_nav_connections_title">连接</string>
|
||||
<string name="dashboard_nav_connections_sub">配对、切换、校验路由</string>
|
||||
<string name="dashboard_nav_connections_title">网关</string>
|
||||
<string name="dashboard_nav_connections_sub">登录、配对 Relay、切换并验证路由</string>
|
||||
|
||||
<!-- Hub header -->
|
||||
<string name="dashboard_hub_title">Relay 中心</string>
|
||||
@@ -1830,7 +1866,7 @@
|
||||
|
||||
<!-- Sign-in card -->
|
||||
<string name="dashboard_signin_required_title">需要登录仪表盘</string>
|
||||
<string name="dashboard_signin_required_body">管理功能使用位于 %1$s 的 Hermes 仪表盘会话。</string>
|
||||
<string name="dashboard_signin_required_body">登录 %1$s 的 Hermes 以使用聊天、会话、管理和标准语音。</string>
|
||||
<string name="dashboard_signin_route_hint">无法在 %1$s 路由上复用已保存的仪表板会话。请重新登录,以便在此连接的可信路由之间刷新会话。</string>
|
||||
<string name="dashboard_signin_with_provider">使用 %1$s 登录</string>
|
||||
<string name="dashboard_username_password">用户名与密码</string>
|
||||
@@ -1839,6 +1875,7 @@
|
||||
<string name="dashboard_sign_in">登录</string>
|
||||
<string name="dashboard_signing_in">正在登录……</string>
|
||||
<string name="dashboard_no_supported_provider">该仪表盘未提供受 Android 支持的登录方式。</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">已保存的登录提供商当前不可用。请选择其他已配置的提供商,或稍后重试。</string>
|
||||
|
||||
<!-- OAuth sign-in dialog -->
|
||||
<string name="dashboard_oauth_initial_status">请在安全的仪表盘页面完成登录。</string>
|
||||
@@ -2290,6 +2327,8 @@
|
||||
<string name="active_section_no_response_from_relay">Relay 无响应</string>
|
||||
<string name="active_section_no_route_reachable">无可用路由</string>
|
||||
<string name="active_section_no_routes_answered_probe">没有路由响应探测</string>
|
||||
<string name="active_section_no_reachable_route_title">没有可达的 Gateway 路由</string>
|
||||
<string name="active_section_no_reachable_route_body">配置的 Gateway 路由均未响应。请开启 Tailscale、Wi-Fi 或移动数据,然后重新检查。展开下方路由可查看 Dashboard、API 和 Relay 的结果。</string>
|
||||
<string name="active_section_not_advertised">未公布</string>
|
||||
<string name="active_section_not_checked">未检查</string>
|
||||
<string name="active_section_not_configured">未配置</string>
|
||||
@@ -2423,7 +2462,7 @@
|
||||
<string name="conn_info_loading_profiles">正在加载个人资料…</string>
|
||||
<string name="conn_info_local_display_name">本地显示名称</string>
|
||||
<string name="conn_info_locked_to">锁定为 %1$s</string>
|
||||
<string name="conn_info_manage_connections">管理连接</string>
|
||||
<string name="conn_info_manage_connections">管理网关</string>
|
||||
<string name="conn_info_manage_profiles">管理个人资料显示</string>
|
||||
<string name="conn_info_manage_profiles_hint">重新排序个人资料,或隐藏不常用的个人资料。当前个人资料会保持可见。</string>
|
||||
<string name="conn_info_move_profile_up">上移 %1$s</string>
|
||||
@@ -2702,8 +2741,8 @@
|
||||
|
||||
<!-- ConnectionSwitcherSheet -->
|
||||
<string name="conn_switcher_title">切换连接</string>
|
||||
<string name="conn_switcher_empty">尚无连接</string>
|
||||
<string name="conn_switcher_manage">管理连接…</string>
|
||||
<string name="conn_switcher_empty">尚无网关</string>
|
||||
<string name="conn_switcher_manage">管理网关…</string>
|
||||
|
||||
<!-- DiagnosticsLogPanel -->
|
||||
<string name="diagnostics_title">最近活动</string>
|
||||
@@ -3034,7 +3073,7 @@
|
||||
<string name="screen_bridge_label">桥接</string>
|
||||
<string name="screen_manage_label">管理</string>
|
||||
<string name="screen_settings_label">设置</string>
|
||||
<string name="screen_connections_label">连接</string>
|
||||
<string name="screen_connections_label">网关</string>
|
||||
<string name="screen_connection_label">连接</string>
|
||||
<string name="screen_voice_label">语音</string>
|
||||
<string name="screen_notification_companion_label">通知伴侣</string>
|
||||
@@ -3121,7 +3160,7 @@
|
||||
<string name="cw_hint_chat">聊天</string>
|
||||
<string name="cw_hint_manage">管理</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s 应使用 http:// 或 https://(未写协议的主机默认使用 http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s 应使用 http:// 或 https://(私有主机使用 http://;公共主机使用 https://)</string>
|
||||
<string name="cw_label_api_key">API Key</string>
|
||||
<string name="cw_label_api_server">API 服务器</string>
|
||||
<string name="cw_label_dashboard">仪表盘</string>
|
||||
@@ -3170,7 +3209,7 @@
|
||||
<string name="cw_step_3_3">第 3 步(共 3 步)</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">检测到 Tailscale 网络</string>
|
||||
<string name="cw_tailscale_supporting_other">离开服务器网络时,可手动切换超时设置、地址、API 端口(8642)和 http:// 默认值,这些可以在设置 → 连接 → 路由中更改。</string>
|
||||
<string name="cw_tailscale_supporting_other">离开服务器网络时,可在“设置 → 网关 → 路由”中更改超时、地址、API 端口(8642)和 http:// 默认值。</string>
|
||||
<string name="cw_value_derived">自动检测</string>
|
||||
<string name="cw_value_included">包含</string>
|
||||
<string name="cw_value_not_included">不包含</string>
|
||||
@@ -3363,6 +3402,7 @@
|
||||
<string name="card_send_answer_a11y">发送回答</string>
|
||||
<string name="card_submit">提交</string>
|
||||
<string name="card_answer_placeholder">输入回答…</string>
|
||||
<string name="card_other_answer_placeholder">其他(输入自定义回答)…</string>
|
||||
<string name="session_ttl_title">保持配对的时长…</string>
|
||||
<string name="session_ttl_intro">在此时间内,手机会自动重新连接。您可以随时撤销配对。</string>
|
||||
<string name="session_ttl_stays_paired">此设备会保持配对,直到您主动撤销。</string>
|
||||
@@ -3473,7 +3513,7 @@
|
||||
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
|
||||
<string name="active_section_scan_relay_qr">扫描 Relay 二维码</string>
|
||||
<string name="active_section_other_relay_methods">其他配对方式</string>
|
||||
<string name="active_section_direct_relay_endpoint">直接 Relay 端点</string>
|
||||
<string name="endpoints_tailscale_setup_hint">两台设备都必须连接 Tailscale,并且 Hermes Dashboard 必须可通过端口 9119 访问。</string>
|
||||
<string name="endpoints_setup_help">Tailscale 设置帮助</string>
|
||||
<string name="voice_settings_provider_desc">语音生成的位置。可用选项来自此 Hermes 主机及其已安装的提供商。</string>
|
||||
@@ -3498,7 +3538,8 @@
|
||||
<string name="dev_settings_image_generation_lab">图像生成实验室</string>
|
||||
<string name="dev_settings_image_generation_lab_desc">预览生成循环和最终图像显现效果</string>
|
||||
<string name="dev_settings_open_image_generation_lab_cd">打开图像生成实验室</string>
|
||||
<string name="dashboard_native_signin_opening">请在浏览器中完成登录,然后返回此处。</string>
|
||||
<string name="dashboard_native_signin_opening">请在浏览器中完成登录。如果提供商登录后没有返回,请回到此处并点按“继续登录”。</string>
|
||||
<string name="dashboard_native_signin_continue">继续登录</string>
|
||||
<string name="dashboard_native_signin_cancelled">已取消浏览器登录。</string>
|
||||
<string name="dashboard_native_signin_requires_https">安全浏览器登录需要 HTTPS 控制面板地址。</string>
|
||||
<string name="dashboard_native_signin_unavailable">此连接无法使用安全浏览器登录。请刷新连接后重试。</string>
|
||||
@@ -3950,6 +3991,9 @@
|
||||
<string name="plugins_remove">移除</string>
|
||||
<string name="plugins_remove_confirm">要移除“%1$s”吗?此插件页面将不再显示在已连接的 Android 设备上。</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">主机仓库扫描</string>
|
||||
<string name="git_state_host_scanning_on_desc">已为此网关启用 · Git 写入仍需单独授权。</string>
|
||||
<string name="git_state_host_scanning_off_desc">允许此手机请求网关扫描已配置的 Git 根目录,以查找仓库、分支和更改状态。Git 写入需要单独授权。</string>
|
||||
<string name="git_state_back">返回</string>
|
||||
<string name="git_state_staged">已暂存</string>
|
||||
<string name="git_state_modified">已修改</string>
|
||||
@@ -3993,7 +4037,7 @@
|
||||
<string name="git_state_switch_stash">切换(有更改时暂存)</string>
|
||||
<string name="support_bundle_review">查看支持信息</string>
|
||||
<string name="support_bundle_title">支持信息</string>
|
||||
<string name="support_bundle_privacy">不会自动上传任何内容。请查看最多包含 %1$d 个报告的本地导出。</string>
|
||||
<string name="support_bundle_privacy">不会自动上传任何内容。请检查包含 %1$d 条近期报告和诊断的本地导出。</string>
|
||||
<string name="support_bundle_copied">支持信息已复制</string>
|
||||
<string name="support_bundle_no_share">支持信息已复制 — 未找到可分享的应用</string>
|
||||
<string name="support_bundle_share_title">分享 Hermes-Relay 支持信息</string>
|
||||
@@ -4354,7 +4398,7 @@
|
||||
<string name="custom_theme_modified">未保存的更改</string>
|
||||
<string name="custom_theme_saved_count">已保存 %1$d 个预设</string>
|
||||
<string name="chat_settings_show_git_workspace">在聊天中显示 Git 工作区</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">在输入框上方显示分支和更改</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">启用主机仓库扫描后,在 Chat 中显示 Git 状态和更改。关闭此项时仍可使用完整的 Git 工作区。</string>
|
||||
<string name="chat_git_open_workspace">打开 Git 工作区</string>
|
||||
<string name="chat_git_branch">分支 %1$s</string>
|
||||
<string name="chat_git_additions">新增 %1$d 行</string>
|
||||
@@ -4362,4 +4406,86 @@
|
||||
<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="current_chat_activity_title">当前聊天活动</string>
|
||||
<string name="current_chat_activity_subtitle">此聊天中的只读实时详情</string>
|
||||
<string name="current_chat_activity_open">预览当前聊天活动</string>
|
||||
<string name="current_chat_activity_summary">%1$d 个代理 · %2$d 个进程</string>
|
||||
<string name="current_chat_activity_close">关闭活动预览</string>
|
||||
<string name="current_chat_activity_empty">此聊天当前没有活动</string>
|
||||
<string name="current_chat_activity_latest">最新</string>
|
||||
<string name="agent_activity_section">实时代理活动</string>
|
||||
<string name="agent_activity_disclosure">此聊天接收到的更新。可能无法获取子代理的完整历史记录。</string>
|
||||
<string name="agent_activity_fallback">代理 %d</string>
|
||||
<string name="agent_activity_task_position">第 %1$d 个,共 %2$d 个 · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s,%2$s,第 %3$d 个代理,共 %4$d 个</string>
|
||||
<string name="agent_activity_duration">%1$.1f 秒</string>
|
||||
<string name="agent_activity_older_omitted">已省略较早的活动</string>
|
||||
<string name="agent_activity_partial">实时更新已恢复。离线期间的活动可能缺失。</string>
|
||||
<string name="agent_activity_event_started">已开始</string>
|
||||
<string name="agent_activity_event_update">更新</string>
|
||||
<string name="agent_activity_event_tool">工具预览</string>
|
||||
<string name="agent_activity_status_started">正在启动</string>
|
||||
<string name="agent_activity_status_thinking">正在思考</string>
|
||||
<string name="agent_activity_status_tool">正在使用工具</string>
|
||||
<string name="agent_activity_status_progress">正在工作</string>
|
||||
<string name="agent_activity_status_completed">已完成</string>
|
||||
<string name="agent_activity_status_failed">失败</string>
|
||||
<string name="agent_activity_status_interrupted">已中断</string>
|
||||
<string name="agent_activity_status_unavailable">最终状态不可用</string>
|
||||
<string name="agent_activity_child_loading">正在打开只读子历史记录…</string>
|
||||
<string name="agent_activity_child_unavailable">此 Hermes 版本或路由不提供子历史记录。上方显示父会话活动。</string>
|
||||
<string name="agent_activity_child_live">子历史记录 · 实时更新</string>
|
||||
<string name="agent_activity_child_history">子历史记录 · 只读</string>
|
||||
<string name="agent_activity_child_truncated">显示近期子活动 · 已省略较早或过大的详情</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">输入 Hermes Gateway 地址</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">已认证的仪表盘地址</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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_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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">使用所选路由</string>
|
||||
<string name="active_section_use_selected_route_failed">无法将 Dashboard 登录切换回所选路由。</string>
|
||||
<string name="active_section_forget_sign_in_origin">忘记登录来源</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<string name="notification_companion_label">Hermes-Relay-Benachrichtigungsassistent</string>
|
||||
|
||||
<string name="onboarding_skip_setup_title">Einrichtung überspringen?</string>
|
||||
<string name="onboarding_skip_setup_text">Kein Problem — erkunde die Demo und sieh dir an, wie Hermes-Relay funktioniert. Deinen eigenen Hermes-Server kannst du jederzeit unter Einstellungen → Verbindungen hinzufügen. Die Relay-Kopplung für Profiwerkzeuge ist auch später möglich.</string>
|
||||
<string name="onboarding_skip_setup_text">Kein Problem — erkunde die Demo und sieh dir an, wie Hermes-Relay funktioniert. Dein eigenes Hermes-Gateway kannst du jederzeit unter Einstellungen → Gateways hinzufügen. Die Relay-Kopplung für Profiwerkzeuge ist auch später möglich.</string>
|
||||
<string name="onboarding_skip_for_now">Vorerst überspringen</string>
|
||||
<string name="onboarding_go_back">Zurück</string>
|
||||
<string name="onboarding_skip">Überspringen</string>
|
||||
@@ -150,7 +150,7 @@
|
||||
<string name="chat_editing_notice">Bearbeitung — setzt die Unterhaltung zurück</string>
|
||||
<string name="chat_mic_perm_needed">Mikrofonberechtigung erforderlich</string>
|
||||
<string name="chat_mic_perm_body">Tippe auf Einstellungen öffnen und erteile Mikrofonzugriff, um den Sprachmodus zu nutzen.</string>
|
||||
<string name="chat_manage_connections">Verbindungen verwalten</string>
|
||||
<string name="chat_manage_connections">Gateways verwalten</string>
|
||||
<string name="chat_no_clipboard_image">Kein Bild in der Zwischenablage</string>
|
||||
<string name="chat_copied_to_clipboard">In die Zwischenablage kopiert</string>
|
||||
<string name="chat_camera_open_failed">Kamera konnte nicht geöffnet werden</string>
|
||||
@@ -211,7 +211,7 @@
|
||||
<string name="conn_label_route">Route</string>
|
||||
<string name="conn_label_status">Status</string>
|
||||
<string name="conn_label_connect">Verbinden</string>
|
||||
<string name="conn_label_connections">Verbindungen</string>
|
||||
<string name="conn_label_connections">Gateways</string>
|
||||
<string name="conn_detail_add_connection">Standard-Hermes-API-/Dashboard-Verbindung hinzufügen</string>
|
||||
<string name="conn_detail_waiting_network">Warten, bis Android eine Internetroute meldet</string>
|
||||
<string name="conn_detail_chat_unavailable">Chat- und Profilaufrufe sind möglicherweise nicht verfügbar</string>
|
||||
@@ -297,19 +297,19 @@
|
||||
<string name="error_classify_open_settings">Einstellungen öffnen</string>
|
||||
|
||||
<!-- Connection wizard — Connect page essentials -->
|
||||
<string name="cw_connect_to_hermes">Mit Hermes verbinden</string>
|
||||
<string name="cw_connect_to_hermes">Gateway hinzufügen</string>
|
||||
<string name="cw_nearby_description">Wir suchen in diesem Netzwerk nach Hermes. Dashboard und Gateway stellen die Standardverbindung für Chat, Verwaltung und Sprache bereit.</string>
|
||||
<string name="cw_connection_chooser_description">Wähle deine vorhandene Einrichtung. Hermes Relay ist optional.</string>
|
||||
<string name="cw_connection_chooser_description">Ein Gateway ist eine Hermes-Installation. Wähle, wie dieses Telefon sie erreicht.</string>
|
||||
<string name="cw_scan_setup_qr_title">Hermes-Einrichtungs-QR-Code scannen</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">Lokale, entfernte und verfügbare Relay-Routen konfigurieren</string>
|
||||
<string name="cw_recommended">Empfohlen</string>
|
||||
<string name="cw_other_ways_to_connect">Weitere Verbindungsmöglichkeiten</string>
|
||||
<string name="cw_other_ways_to_connect">Gateway auswählen</string>
|
||||
<string name="cw_advanced">Erweitert</string>
|
||||
<string name="cw_cloud_title">Von Nous gehostetes Hermes</string>
|
||||
<string name="cw_cloud_subtitle">Mit deinem gehosteten Agenten verbinden</string>
|
||||
<string name="cw_server_vps_title">Server oder VPS</string>
|
||||
<string name="cw_server_vps_subtitle">Sichere Dashboard-Adresse eingeben</string>
|
||||
<string name="cw_relay_optional_note">Standard-Chat, Verwaltung und Sprache funktionieren ohne Relay. Kompatible Einrichtungs-QR-Codes fügen verfügbare Relay-Power-Funktionen hinzu.</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_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>
|
||||
@@ -336,7 +336,7 @@
|
||||
<string name="cw_nearby_search_again">Erneut suchen</string>
|
||||
<string name="cw_nearby_enter_address">Stattdessen Adresse eingeben</string>
|
||||
<string name="cw_other_connection_methods">Andere Verbindungsmethoden</string>
|
||||
<string name="cw_manual_hermes_title">Hermes-Adresse eingeben</string>
|
||||
<string name="cw_manual_hermes_title">Gateway-Adresse eingeben</string>
|
||||
<string name="cw_manual_hermes_description">Gib die Dashboard-Adresse ein, die du im Browser öffnest. Wenn sie auf diesem Smartphone nicht geöffnet wird, starte hermes dashboard und prüfe WLAN oder Tailscale.</string>
|
||||
<string name="cw_hermes_address">Hermes-Adresse</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 oder hermes.example.com</string>
|
||||
@@ -429,6 +429,13 @@
|
||||
<string name="cw_pairing_code_label">Kopplungscode</string>
|
||||
<string name="cw_pairing_code_placeholder">z. B. ABC123</string>
|
||||
<string name="cw_pair_button">Koppeln</string>
|
||||
<string name="cw_mixed_route_plain">%1$s verwendet unverschlüsseltes HTTP/WS. Nur in einem vertrauenswürdigen privaten Netzwerk oder über ein selbst verwaltetes VPN verwenden.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s verwendet HTTPS/WSS mit Transportverschlüsselung.</string>
|
||||
<string name="cw_mixed_safe">Die App prüft diese Routen und wählt eine verfügbare aus. Die bevorzugte Route kann später geändert werden.</string>
|
||||
<string name="cw_pair_in_progress">Wird ausgeführt…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">Gateway wird vorbereitet…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">Sichere Anmeldung wird geöffnet…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Relay wird gekoppelt…</string>
|
||||
<string name="cw_show_code_subtitle">Verwende dies, wenn du keinen Relay-Kopplungs-QR-Code scannen kannst. Lege deine URLs fest und registriere dann den folgenden Code auf dem Host, auf dem Hermes-Relay läuft.</string>
|
||||
<string name="cw_step_copy_code">1. Diesen Code kopieren</string>
|
||||
<string name="cw_copy_pairing_code">Kopplungscode kopieren</string>
|
||||
@@ -447,9 +454,6 @@
|
||||
<string name="cw_insecure_relay_warning">Dieses Relay verwendet unverschlüsseltes ws:// — der Datenverkehr ist nicht verschlüsselt.</string>
|
||||
<string name="cw_insecure_relay_trust">Fahre nur fort, wenn du das Netzwerk bei jeder Verbindung (LAN, Tailscale, VPN) als vertrauenswürdig einstufst.</string>
|
||||
<string name="cw_insecure_ack">Ich verstehe, dass diese Kopplung Daten im Klartext sendet — sichtbar für alle im Netzwerk.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s nutzt unverschlüsseltes ws:// — zu Hause oder im Büro in Ordnung, nicht aber in öffentlichen WLANs.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s ist verschlüsselt (wss://) und wird von der App automatisch verwendet, wenn %2$s nicht erreichbar ist.</string>
|
||||
<string name="cw_mixed_safe">Du bist in jedem Netzwerk geschützt.</string>
|
||||
<string name="cw_connecting_to_hermes">Verbindung mit Hermes wird hergestellt</string>
|
||||
<string name="cw_connecting_detail">API-Server, gespeicherter Schlüssel und Dashboard werden geprüft.</string>
|
||||
<string name="cw_pairing_title">Kopplung läuft…</string>
|
||||
@@ -475,7 +479,7 @@
|
||||
<string name="cw_voice_after_connect">Wird nach dem Verbinden geprüft</string>
|
||||
<string name="cw_remote">Fernzugriff</string>
|
||||
<string name="cw_remote_fallback_ready">Ausweichroute für die Nutzung unterwegs bereit</string>
|
||||
<string name="cw_remote_lan_only">Nur LAN — füge unter Einstellungen → Verbindungen → Routen eine Tailscale- oder öffentliche Route hinzu</string>
|
||||
<string name="cw_remote_lan_only">Nur LAN — füge unter Einstellungen → Gateways → Routen eine Tailscale- oder öffentliche Route hinzu</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">Profiwerkzeuge gekoppelt</string>
|
||||
<string name="cw_relay_optional">Optional für Terminal und Bridge</string>
|
||||
@@ -495,6 +499,17 @@
|
||||
<string name="endpoints_preferred">Bevorzugt</string>
|
||||
<string name="endpoints_automatic">Automatisch</string>
|
||||
<string name="endpoints_current_route">Aktuelle Route: %1$s (%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">Derzeit ist keine Ausweichroute ausgewählt.</string>
|
||||
<string name="endpoints_selection_reason">Priorität %1$d (0 ist am höchsten) · %2$s</string>
|
||||
<string name="endpoints_reachable_now">Jetzt erreichbar</string>
|
||||
<string name="endpoints_last_check_failed">Letzte Prüfung fehlgeschlagen</string>
|
||||
<string name="endpoints_reachability_not_checked">Erreichbarkeit nicht geprüft</string>
|
||||
<string name="endpoints_security_application_tls">TLS auf Anwendungsebene</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Durch Tailscale verschlüsselt · kein TLS auf Anwendungsebene</string>
|
||||
<string name="endpoints_security_wireguard_overlay">Durch WireGuard verschlüsselt · kein TLS auf Anwendungsebene</string>
|
||||
<string name="endpoints_security_secure_link">Durch Hermes Secure Link verschlüsselt</string>
|
||||
<string name="endpoints_security_private_plain">Privates Netzwerk · kein TLS auf Anwendungsebene</string>
|
||||
<string name="endpoints_security_public_plain">Öffentliche Route ist nicht verschlüsselt</string>
|
||||
<string name="endpoints_cancel_manual_switch">Manuelle Umschaltung abbrechen — zurück zu %1$s</string>
|
||||
<string name="endpoints_stop_preferring">Nicht mehr bevorzugen — zurück zu Automatisch</string>
|
||||
<string name="endpoints_checking">Prüfung läuft…</string>
|
||||
@@ -676,7 +691,7 @@
|
||||
<string name="relay_state_needs_repair">Erneut koppeln</string>
|
||||
<string name="settings_no_connection">Keine Verbindung</string>
|
||||
<string name="settings_server_default">Serverstandard</string>
|
||||
<string name="settings_connections">Verbindungen</string>
|
||||
<string name="settings_connections">Gateways</string>
|
||||
<string name="settings_connections_desc">API, Dashboard, Relay-Kopplung und Routen</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Hermes-Verwaltung</string>
|
||||
@@ -816,16 +831,33 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">Gateway erfordert Anmeldung unter Verwalten</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Melde dich einmal im Tab Verwalten an, um Live-Denken über /api/ws freizuschalten.</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Melde dich einmal an, um Chat, Sitzungen, Verwaltung und Standard-Sprache für diese Hermes-Verbindung freizuschalten.</string>
|
||||
<string name="chat_settings_completions">Vervollständigungen</string>
|
||||
<string name="chat_settings_offline">offline</string>
|
||||
|
||||
<!-- P0: ConnectionsSettingsScreen -->
|
||||
<string name="conn_back">Zurück</string>
|
||||
<string name="conn_title">Verbindungen</string>
|
||||
<string name="conn_add_connection">Verbindung hinzufügen</string>
|
||||
<string name="conn_no_connections">Noch keine Verbindungen</string>
|
||||
<string name="conn_no_connections_desc">Tippe auf Verbindung hinzufügen, um dich mit Hermes zu verbinden.</string>
|
||||
<string name="conn_title">Gateways</string>
|
||||
<string name="conn_add_connection">Gateway hinzufügen</string>
|
||||
<string name="conn_no_connections">Noch keine Gateways</string>
|
||||
<string name="conn_no_connections_desc">Tippe auf Gateway hinzufügen, um dich mit Hermes zu verbinden.</string>
|
||||
<string name="gateways_title">Gateways</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d Gateway</item><item quantity="other">%d Gateways</item></plurals>
|
||||
<string name="gateway_add">Gateway hinzufügen</string>
|
||||
<string name="gateways_empty_title">Noch keine Gateways</string>
|
||||
<string name="gateways_empty_body">Füge ein Gateway hinzu, um dieses Telefon mit Hermes zu verbinden.</string>
|
||||
<string name="gateway_route_not_configured">Keine Route konfiguriert</string>
|
||||
<string name="gateway_status_online">Gateway online</string>
|
||||
<string name="gateway_status_sign_in_required">Anmeldung erforderlich</string>
|
||||
<string name="gateway_status_offline">Gateway offline</string>
|
||||
<string name="gateway_status_checking">Gateway wird geprüft…</string>
|
||||
<string name="gateway_status_not_checked">Gateway nicht geprüft</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">Letzte Prüfung: Anmeldung erforderlich</string>
|
||||
<string name="gateway_status_last_check_succeeded">Letzte Prüfung erfolgreich</string>
|
||||
<string name="gateway_status_last_check_failed">Letzte Prüfung fehlgeschlagen</string>
|
||||
<string name="gateway_status_no_route">Keine Gateway-Route</string>
|
||||
<string name="gateway_status_unavailable">Gateway nicht verfügbar</string>
|
||||
<string name="conn_add_requires_parent_access">Entsperre den Elternzugriff, bevor du ein Gateway hinzufügst.</string>
|
||||
<string name="conn_active">Aktiv</string>
|
||||
<string name="conn_connected">Verbunden</string>
|
||||
<string name="conn_standard_not_paired">Standard · Relay nicht gekoppelt</string>
|
||||
@@ -906,6 +938,8 @@
|
||||
<string name="detail_tab_routes">Routen</string>
|
||||
<string name="detail_tab_advanced">Erweitert</string>
|
||||
<string name="detail_tab_security">Sicherheit</string>
|
||||
<string name="detail_tab_access">Zugriff</string>
|
||||
<string name="detail_current_route">Aktuelle Route</string>
|
||||
|
||||
<!-- P0: SessionDrawer -->
|
||||
<string name="bot_mode_title">Bot-Modus</string>
|
||||
@@ -965,6 +999,8 @@
|
||||
<string name="drawer_delete_session_title">Sitzung löschen?</string>
|
||||
<string name="drawer_delete_session_prefix">Dadurch werden \"</string>
|
||||
<string name="drawer_delete_session_suffix">\" und der Nachrichtenverlauf dauerhaft gelöscht.</string>
|
||||
<string name="drawer_remove_provisional_thread_title">Thread entfernen?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">Dadurch wird „%1$s“ von diesem Gerät entfernt. Hochgestufte oder serverseitige Verläufe werden nicht gelöscht.</string>
|
||||
<string name="drawer_untitled">Ohne Titel</string>
|
||||
<string name="drawer_delete">Löschen</string>
|
||||
<string name="drawer_thread">Thread</string>
|
||||
@@ -995,7 +1031,7 @@
|
||||
<string name="bridge_relay_label">Relay</string>
|
||||
<string name="bridge_safety_label">Sicherheit</string>
|
||||
<string name="bridge_not_connected_title">Relay nicht verbunden</string>
|
||||
<string name="bridge_not_connected_body">Bridge-Befehle werden über das Relay übertragen. Kopple unter Einstellungen → Verbindungen ein Relay, damit die Bridge tatsächlich funktioniert.</string>
|
||||
<string name="bridge_not_connected_body">Bridge-Befehle werden über Relay übertragen. Kopple Relay unter Einstellungen → Gateways, damit die Bridge funktioniert.</string>
|
||||
<string name="bridge_accessibility_needed">Der Bedienungshilfendienst muss zuerst aktiviert werden.</string>
|
||||
<string name="bridge_open_settings">Einstellungen öffnen</string>
|
||||
<string name="bridge_allow_agent_control">Agentensteuerung erlauben</string>
|
||||
@@ -1032,8 +1068,8 @@
|
||||
<string name="bridge_core_relay_body">Bridge-Kern verwendet dieselbe gekoppelte Relay-Sitzung wie Terminal-, Benachrichtigungs-, Medien- und Sprachfunktionen.</string>
|
||||
<string name="bridge_core_surface_title">Bridge-Oberfläche</string>
|
||||
<string name="bridge_core_surface_meta">in den Einstellungen sichtbar</string>
|
||||
<string name="bridge_core_connections">Verbindungen</string>
|
||||
<string name="bridge_core_connections_sub">Relay-Routen koppeln, wechseln und prüfen</string>
|
||||
<string name="bridge_core_connections">Gateways</string>
|
||||
<string name="bridge_core_connections_sub">Relay koppeln, Gateways wechseln und Routen prüfen</string>
|
||||
<string name="bridge_core_terminal_tile">Terminal</string>
|
||||
<string name="bridge_core_terminal_sub">Mit deinem Hermes-Relay-Terminal verbinden</string>
|
||||
<string name="bridge_core_voice">Sprache</string>
|
||||
@@ -1391,7 +1427,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Hermes darf mir schreiben</string>
|
||||
<string name="proactive_allow_proactive_messages">Proaktive Nachrichten erlauben</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">Dein Agent kann selbstständig Kontakt aufnehmen — mit Erinnerungen, abgeschlossenen Aufträgen oder Warnungen. Seine Nachrichten erscheinen als Threads im Chat, wo du antworten kannst.</string>
|
||||
<string name="proactive_not_paired_warning">Noch nicht gekoppelt — kopple dich unter Einstellungen → Verbindungen mit deinem Hermes-Server, um Nachrichten zu empfangen.</string>
|
||||
<string name="proactive_not_paired_warning">Noch nicht gekoppelt — kopple Relay unter Einstellungen → Gateways, um Nachrichten zu empfangen.</string>
|
||||
<string name="proactive_your_threads">Deine Threads</string>
|
||||
<string name="proactive_your_threads_desc">Jede vom Agenten gestartete Unterhaltung erscheint als Thread im Chat — öffne die Sitzungsliste, filtere nach Threads und antworte direkt dort.</string>
|
||||
<string name="proactive_open_chat">Chat öffnen</string>
|
||||
@@ -1577,7 +1613,7 @@
|
||||
<string name="voice_settings_engine_realtime">Echtzeit-Agent</string>
|
||||
<string name="voice_settings_engine_realtime_desc">Anbietereigene Echtzeitsprache mit von Hermes vermittelten Werkzeugen. Erfordert ein gekoppeltes Relay.</string>
|
||||
<string name="voice_settings_experimental">Experimentell</string>
|
||||
<string name="voice_settings_realtime_no_relay">Für diese Verbindung ist kein Relay konfiguriert, daher kann der Echtzeit-Agent nicht starten. Kopple Relay unter Einstellungen → Verbindungen oder wechsle zurück zu Hermes-Chat + Sprachausgabe.</string>
|
||||
<string name="voice_settings_realtime_no_relay">Für dieses Gateway ist kein Relay konfiguriert, daher kann der Echtzeit-Agent nicht starten. Kopple Relay unter Einstellungen → Gateways oder wechsle zurück zu Hermes-Chat + Sprachausgabe.</string>
|
||||
<string name="voice_settings_route_label">STT-/TTS-Route</string>
|
||||
<string name="voice_settings_status_ready">Bereit</string>
|
||||
<string name="voice_settings_status_sign_in_required">Dashboard-Anmeldung erforderlich</string>
|
||||
@@ -1798,8 +1834,8 @@
|
||||
<string name="dashboard_tile_config_sub">Schema und Laufzeitoptionen</string>
|
||||
|
||||
<!-- Nav tiles -->
|
||||
<string name="dashboard_nav_connections_title">Verbindungen</string>
|
||||
<string name="dashboard_nav_connections_sub">Routen koppeln, wechseln, prüfen</string>
|
||||
<string name="dashboard_nav_connections_title">Gateways</string>
|
||||
<string name="dashboard_nav_connections_sub">Anmelden, Relay koppeln, wechseln und Routen prüfen</string>
|
||||
|
||||
<!-- Hub header -->
|
||||
<string name="dashboard_hub_title">Relay-Zentrale</string>
|
||||
@@ -1835,7 +1871,7 @@
|
||||
|
||||
<!-- Sign-in card -->
|
||||
<string name="dashboard_signin_required_title">Dashboard-Anmeldung erforderlich</string>
|
||||
<string name="dashboard_signin_required_body">Verwalten verwendet die Hermes-Dashboard-Sitzung unter %1$s.</string>
|
||||
<string name="dashboard_signin_required_body">Melde dich bei Hermes unter %1$s für Chat, Sitzungen, Verwalten und Standard-Voice an.</string>
|
||||
<string name="dashboard_signin_route_hint">Die gespeicherte Dashboard-Sitzung konnte über die Route %1$s nicht wiederverwendet werden. Melde dich erneut an, um sie für die vertrauenswürdigen Routen dieser Verbindung zu aktualisieren.</string>
|
||||
<string name="dashboard_signin_with_provider">Mit %1$s anmelden</string>
|
||||
<string name="dashboard_username_password">Benutzername & Passwort</string>
|
||||
@@ -1844,6 +1880,7 @@
|
||||
<string name="dashboard_sign_in">Anmelden</string>
|
||||
<string name="dashboard_signing_in">Anmeldung läuft…</string>
|
||||
<string name="dashboard_no_supported_provider">Dieses Dashboard hat keinen unterstützten Android-Anmeldeanbieter angekündigt.</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">Der gespeicherte Anmeldeanbieter ist nicht verfügbar. Wähle einen anderen konfigurierten Anbieter oder versuche es später erneut.</string>
|
||||
|
||||
<!-- OAuth sign-in dialog -->
|
||||
<string name="dashboard_oauth_initial_status">Schließe die Anmeldung auf der sicheren Dashboard-Seite ab.</string>
|
||||
@@ -2297,6 +2334,8 @@
|
||||
<string name="active_section_no_response_from_relay">Keine Antwort vom Relay</string>
|
||||
<string name="active_section_no_route_reachable">Keine Route erreichbar</string>
|
||||
<string name="active_section_no_routes_answered_probe">Keine Route hat auf die Prüfung geantwortet</string>
|
||||
<string name="active_section_no_reachable_route_title">Keine erreichbare Gateway-Route</string>
|
||||
<string name="active_section_no_reachable_route_body">Keine der konfigurierten Gateway-Routen hat geantwortet. Aktiviere Tailscale, WLAN oder mobile Daten und prüfe erneut. Klappe unten eine Route auf, um die Ergebnisse für Dashboard, API und Relay anzuzeigen.</string>
|
||||
<string name="active_section_not_advertised">Nicht angekündigt</string>
|
||||
<string name="active_section_not_checked">Nicht geprüft</string>
|
||||
<string name="active_section_not_configured">Nicht konfiguriert</string>
|
||||
@@ -2430,7 +2469,7 @@
|
||||
<string name="conn_info_loading_profiles">Profile werden geladen…</string>
|
||||
<string name="conn_info_local_display_name">Lokaler Anzeigename</string>
|
||||
<string name="conn_info_locked_to">Gesperrt auf %1$s</string>
|
||||
<string name="conn_info_manage_connections">Verbindungen verwalten</string>
|
||||
<string name="conn_info_manage_connections">Gateways verwalten</string>
|
||||
<string name="conn_info_manage_profiles">Profilanzeige verwalten</string>
|
||||
<string name="conn_info_manage_profiles_hint">Profile neu anordnen oder nicht verwendete Profile ausblenden. Das aktive Profil bleibt sichtbar.</string>
|
||||
<string name="conn_info_move_profile_up">%1$s nach oben verschieben</string>
|
||||
@@ -2707,8 +2746,8 @@
|
||||
|
||||
<!-- ConnectionSwitcherSheet -->
|
||||
<string name="conn_switcher_title">Verbindung wechseln</string>
|
||||
<string name="conn_switcher_empty">Noch keine Verbindungen</string>
|
||||
<string name="conn_switcher_manage">Verbindungen verwalten…</string>
|
||||
<string name="conn_switcher_empty">Noch keine Gateways</string>
|
||||
<string name="conn_switcher_manage">Gateways verwalten…</string>
|
||||
|
||||
<!-- DiagnosticsLogPanel -->
|
||||
<string name="diagnostics_title">Letzte Aktivität</string>
|
||||
@@ -3099,7 +3138,7 @@
|
||||
<string name="screen_bridge_label">Bridge</string>
|
||||
<string name="screen_manage_label">Verwalten</string>
|
||||
<string name="screen_settings_label">Einstellungen</string>
|
||||
<string name="screen_connections_label">Verbindungen</string>
|
||||
<string name="screen_connections_label">Gateways</string>
|
||||
<string name="screen_connection_label">Verbindung</string>
|
||||
<string name="screen_voice_label">Sprache</string>
|
||||
<string name="screen_notification_companion_label">Benachrichtigungsassistent</string>
|
||||
@@ -3185,7 +3224,7 @@
|
||||
<string name="cw_hint_chat">Chat</string>
|
||||
<string name="cw_hint_manage">Verwalten</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s erwartet http:// oder https:// (reine Hosts erhalten http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s erwartet http:// oder https:// (private Hosts verwenden http://, öffentliche Hosts https://)</string>
|
||||
<string name="cw_label_api_key">API-Schlüssel</string>
|
||||
<string name="cw_label_api_server">API-Server</string>
|
||||
<string name="cw_label_dashboard">Dashboard</string>
|
||||
@@ -3238,7 +3277,7 @@
|
||||
<string name="cw_step_3_3">Schritt 3 von 3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Tailscale-Netzwerk erkannt</string>
|
||||
<string name="cw_tailscale_supporting_other">Wenn du nicht im Servernetzwerk bist, können Zeitlimit, Adresse, API-Port (8642) und http://-Vorgaben unter Einstellungen → Verbindungen → Routen manuell geändert werden.</string>
|
||||
<string name="cw_tailscale_supporting_other">Wenn du nicht im Servernetzwerk bist, können Zeitlimit, Adresse, API-Port (8642) und http://-Vorgaben unter Einstellungen → Gateways → Routen manuell geändert werden.</string>
|
||||
<string name="cw_value_derived">Automatisch erkannt</string>
|
||||
<string name="cw_value_included">Enthalten</string>
|
||||
<string name="cw_value_not_included">Nicht enthalten</string>
|
||||
@@ -3431,6 +3470,7 @@
|
||||
<string name="card_send_answer_a11y">Antwort senden</string>
|
||||
<string name="card_submit">Absenden</string>
|
||||
<string name="card_answer_placeholder">Antwort eingeben…</string>
|
||||
<string name="card_other_answer_placeholder">Andere (eigene Antwort eingeben)…</string>
|
||||
<string name="session_ttl_title">Diese Kopplung behalten für…</string>
|
||||
<string name="session_ttl_intro">Dein Smartphone verbindet sich in diesem Zeitraum automatisch erneut. Du kannst die Kopplung jederzeit widerrufen.</string>
|
||||
<string name="session_ttl_stays_paired">Dieses Gerät bleibt gekoppelt, bis du es widerrufst.</string>
|
||||
@@ -3540,7 +3580,7 @@
|
||||
<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>
|
||||
<string name="active_section_scan_relay_qr">Relay-QR scannen</string>
|
||||
<string name="active_section_other_relay_methods">Andere Kopplungsmethoden</string>
|
||||
<string name="active_section_direct_relay_endpoint">Direkter Relay-Endpunkt</string>
|
||||
<string name="endpoints_tailscale_setup_hint">Tailscale muss auf beiden Geräten verbunden und Hermes Dashboard auf Port 9119 erreichbar sein.</string>
|
||||
<string name="endpoints_setup_help">Tailscale-Einrichtungshilfe</string>
|
||||
<string name="voice_settings_provider_desc">Wo Sprache erzeugt wird. Verfuegbare Optionen kommen von diesem Hermes-Host und seinen installierten Anbietern.</string>
|
||||
@@ -3565,7 +3605,8 @@
|
||||
<string name="dev_settings_image_generation_lab">Bildgenerierungs-Labor</string>
|
||||
<string name="dev_settings_image_generation_lab_desc">Generierungsschleifen und die abschließende Bildenthüllung als Vorschau anzeigen</string>
|
||||
<string name="dev_settings_open_image_generation_lab_cd">Bildgenerierungs-Labor öffnen</string>
|
||||
<string name="dashboard_native_signin_opening">Schließe die Anmeldung im Browser ab und kehre dann hierher zurück.</string>
|
||||
<string name="dashboard_native_signin_opening">Schließe die Anmeldung im Browser ab. Falls der Anbieter dich anmeldet, ohne zurückzukehren, tippe hier auf Anmeldung fortsetzen.</string>
|
||||
<string name="dashboard_native_signin_continue">Anmeldung fortsetzen</string>
|
||||
<string name="dashboard_native_signin_cancelled">Browser-Anmeldung abgebrochen.</string>
|
||||
<string name="dashboard_native_signin_requires_https">Die sichere Browser-Anmeldung erfordert eine HTTPS-Dashboard-Adresse.</string>
|
||||
<string name="dashboard_native_signin_unavailable">Die sichere Browser-Anmeldung ist für diese Verbindung nicht verfügbar. Aktualisiere die Verbindung und versuche es erneut.</string>
|
||||
@@ -4022,6 +4063,9 @@
|
||||
<string name="plugins_remove">Entfernen</string>
|
||||
<string name="plugins_remove_confirm">„%1$s“ entfernen? Diese Plugin-Seite wird auf verbundenen Android-Geräten nicht mehr angezeigt.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">Repository-Scan auf dem Host</string>
|
||||
<string name="git_state_host_scanning_on_desc">Für dieses Gateway aktiviert · Git-Schreibzugriffe benötigen weiterhin eine separate Berechtigung.</string>
|
||||
<string name="git_state_host_scanning_off_desc">Erlaubt diesem Smartphone, die konfigurierten Git-Stammordner dieses Gateways nach Repositorys, Branches und Änderungen zu durchsuchen. Git-Schreibzugriffe benötigen eine separate Berechtigung.</string>
|
||||
<string name="git_state_back">Zurück</string>
|
||||
<string name="git_state_staged">Gestaged</string>
|
||||
<string name="git_state_modified">Geändert</string>
|
||||
@@ -4065,7 +4109,7 @@
|
||||
<string name="git_state_switch_stash">Wechseln (bei Änderungen stashen)</string>
|
||||
<string name="support_bundle_review">Supportinformationen prüfen</string>
|
||||
<string name="support_bundle_title">Supportinformationen</string>
|
||||
<string name="support_bundle_privacy">Nichts wird automatisch hochgeladen. Prüfen Sie den lokalen Export mit bis zu %1$d Berichten.</string>
|
||||
<string name="support_bundle_privacy">Nichts wird automatisch hochgeladen. Prüfe den lokalen Export mit %1$d aktuellen Berichten und Diagnosen.</string>
|
||||
<string name="support_bundle_copied">Supportinformationen kopiert</string>
|
||||
<string name="support_bundle_no_share">Supportinformationen kopiert — keine App zum Teilen gefunden</string>
|
||||
<string name="support_bundle_share_title">Hermes-Relay-Supportinformationen teilen</string>
|
||||
@@ -4429,7 +4473,7 @@
|
||||
<string name="custom_theme_modified">Nicht gespeicherte Änderungen</string>
|
||||
<string name="custom_theme_saved_count">%1$d gespeicherte Presets</string>
|
||||
<string name="chat_settings_show_git_workspace">Git-Arbeitsbereich im Chat anzeigen</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Zeigt Branch und Änderungen über dem Eingabefeld an</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Zeigt Git-Status und Änderungen im Chat, wenn der Repository-Scan auf dem Host aktiviert ist. Der vollständige Git-Arbeitsbereich bleibt verfügbar, wenn dies aus ist.</string>
|
||||
<string name="chat_git_open_workspace">Git-Arbeitsbereich öffnen</string>
|
||||
<string name="chat_git_branch">Branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d Hinzufügungen</string>
|
||||
@@ -4437,4 +4481,86 @@
|
||||
<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="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>
|
||||
<string name="current_chat_activity_summary">%1$d Agenten · %2$d Prozesse</string>
|
||||
<string name="current_chat_activity_close">Aktivitätsvorschau schließen</string>
|
||||
<string name="current_chat_activity_empty">Keine aktuelle Aktivität in diesem Chat</string>
|
||||
<string name="current_chat_activity_latest">Neueste</string>
|
||||
<string name="agent_activity_section">Live-Agentenaktivität</string>
|
||||
<string name="agent_activity_disclosure">Von diesem Chat empfangene Updates. Der vollständige Verlauf des untergeordneten Agenten ist möglicherweise nicht verfügbar.</string>
|
||||
<string name="agent_activity_fallback">Agent %d</string>
|
||||
<string name="agent_activity_task_position">%1$d von %2$d · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s, %2$s, Agent %3$d von %4$d</string>
|
||||
<string name="agent_activity_duration">%1$.1fs</string>
|
||||
<string name="agent_activity_older_omitted">Ältere Aktivität ausgelassen</string>
|
||||
<string name="agent_activity_partial">Live-Updates fortgesetzt. Aktivität während der Offlinezeit kann fehlen.</string>
|
||||
<string name="agent_activity_event_started">Gestartet</string>
|
||||
<string name="agent_activity_event_update">Update</string>
|
||||
<string name="agent_activity_event_tool">Werkzeugvorschau</string>
|
||||
<string name="agent_activity_status_started">Wird gestartet</string>
|
||||
<string name="agent_activity_status_thinking">Denkt nach</string>
|
||||
<string name="agent_activity_status_tool">Verwendet ein Werkzeug</string>
|
||||
<string name="agent_activity_status_progress">Arbeitet</string>
|
||||
<string name="agent_activity_status_completed">Abgeschlossen</string>
|
||||
<string name="agent_activity_status_failed">Fehlgeschlagen</string>
|
||||
<string name="agent_activity_status_interrupted">Unterbrochen</string>
|
||||
<string name="agent_activity_status_unavailable">Endstatus nicht verfügbar</string>
|
||||
<string name="agent_activity_child_loading">Schreibgeschützter untergeordneter Verlauf wird geöffnet…</string>
|
||||
<string name="agent_activity_child_unavailable">Der untergeordnete Verlauf ist in dieser Hermes-Version oder Route nicht verfügbar. Die Aktivität der übergeordneten Sitzung wird oben angezeigt.</string>
|
||||
<string name="agent_activity_child_live">Untergeordneter Verlauf · Live-Updates</string>
|
||||
<string name="agent_activity_child_history">Untergeordneter Verlauf · schreibgeschützt</string>
|
||||
<string name="agent_activity_child_truncated">Neueste untergeordnete Aktivität angezeigt · ältere oder zu große Details ausgelassen</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Gib die Hermes-Gateway-Adresse ein</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">Authentifizierte Dashboard-Adresse</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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_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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">Ausgewählte Route verwenden</string>
|
||||
<string name="active_section_use_selected_route_failed">Die Dashboard-Anmeldung konnte nicht auf die ausgewählte Route zurückgesetzt werden.</string>
|
||||
<string name="active_section_forget_sign_in_origin">Anmeldeursprung vergessen</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<string name="agent_interface">interfaz del agente</string>
|
||||
<string name="notification_companion_label">Compañero de notificación Hermes-Relay</string>
|
||||
<string name="onboarding_skip_setup_title">¿Saltar configuración?</string>
|
||||
<string name="onboarding_skip_setup_text">No hay problema: puede explorar la demostración para ver cómo funciona Hermes-Relay y conectar su propio servidor Hermes en cualquier momento desde Configuración → Conexiones. El emparejamiento Relay para herramientas eléctricas también se puede agregar más adelante.</string>
|
||||
<string name="onboarding_skip_setup_text">No hay problema: puede explorar la demostración y agregar su propio gateway de Hermes en cualquier momento desde Configuración → Gateways. El emparejamiento de Relay para herramientas avanzadas también se puede agregar más adelante.</string>
|
||||
<string name="onboarding_skip_for_now">Saltar por ahora</string>
|
||||
<string name="onboarding_go_back">Volver</string>
|
||||
<string name="onboarding_skip">Saltar</string>
|
||||
@@ -127,7 +127,7 @@
|
||||
<string name="chat_editing_notice">Editando: rebobinará la conversación</string>
|
||||
<string name="chat_mic_perm_needed">Se necesita permiso para el micrófono</string>
|
||||
<string name="chat_mic_perm_body">Toque Abrir configuración y otorgue acceso al micrófono para usar el modo de voz.</string>
|
||||
<string name="chat_manage_connections">Administrar conexiones</string>
|
||||
<string name="chat_manage_connections">Administrar gateways</string>
|
||||
<string name="chat_no_clipboard_image">No hay ninguna imagen en el portapapeles</string>
|
||||
<string name="chat_copied_to_clipboard">Copiado al portapapeles</string>
|
||||
<string name="chat_camera_open_failed">No se ha podido abrir la cámara</string>
|
||||
@@ -182,7 +182,7 @@
|
||||
<string name="conn_label_route">Ruta</string>
|
||||
<string name="conn_label_status">Estado</string>
|
||||
<string name="conn_label_connect">Conectar</string>
|
||||
<string name="conn_label_connections">Conexiones</string>
|
||||
<string name="conn_label_connections">Gateways</string>
|
||||
<string name="conn_detail_add_connection">Agregar una conexión Vanilla Hermes API/dashboard</string>
|
||||
<string name="conn_detail_waiting_network">Esperando a que Android informe una ruta de Internet</string>
|
||||
<string name="conn_detail_chat_unavailable">Es posible que el chat y las llamadas de perfil no estén disponibles</string>
|
||||
@@ -259,19 +259,19 @@
|
||||
<string name="error_classify_repair">Volver a emparejar</string>
|
||||
<string name="error_classify_retry">Reintentar</string>
|
||||
<string name="error_classify_open_settings">Abrir configuración</string>
|
||||
<string name="cw_connect_to_hermes">Conéctese a Hermes</string>
|
||||
<string name="cw_connect_to_hermes">Agregar gateway</string>
|
||||
<string name="cw_nearby_description">Buscaremos Hermes en esta red. El panel y la puerta de enlace proporcionan la conexión estándar para Chat, Administrar y Voz.</string>
|
||||
<string name="cw_connection_chooser_description">Elige la configuración que tengas. Hermes Relay es opcional.</string>
|
||||
<string name="cw_connection_chooser_description">Un gateway es una instalación de Hermes. Elige cómo puede acceder este teléfono.</string>
|
||||
<string name="cw_scan_setup_qr_title">Escanear QR de configuración de Hermes</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">Configura rutas locales, remotas y de Relay disponibles</string>
|
||||
<string name="cw_recommended">Recomendado</string>
|
||||
<string name="cw_other_ways_to_connect">Otras formas de conectarse</string>
|
||||
<string name="cw_other_ways_to_connect">Elige un gateway</string>
|
||||
<string name="cw_advanced">Avanzado</string>
|
||||
<string name="cw_cloud_title">Hermes alojado por Nous</string>
|
||||
<string name="cw_cloud_subtitle">Conéctate a tu agente alojado</string>
|
||||
<string name="cw_server_vps_title">Servidor o VPS</string>
|
||||
<string name="cw_server_vps_subtitle">Introduce una dirección segura del panel</string>
|
||||
<string name="cw_relay_optional_note">Chat, Administrar y Voz estándar funcionan sin Relay. Los QR de configuración compatibles añaden funciones avanzadas de Relay cuando están disponibles.</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Introduce la dirección del Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Las direcciones privadas LAN y Tailscale pueden usar HTTP o HTTPS. Las direcciones públicas requieren HTTPS. Relay y la alternativa API son opcionales.</string>
|
||||
<string name="cw_cloud_entry_title">Conectarse a Hermes alojado por Nous</string>
|
||||
<string name="cw_cloud_entry_description">Introduce la dirección del agente que aparece en Nous Portal. Iniciarás sesión de forma segura después de encontrar Hermes.</string>
|
||||
<string name="cw_cloud_agent_name">Dirección del agente</string>
|
||||
@@ -298,7 +298,7 @@
|
||||
<string name="cw_nearby_search_again">Buscar de nuevo</string>
|
||||
<string name="cw_nearby_enter_address">Introducir la dirección</string>
|
||||
<string name="cw_other_connection_methods">Otros métodos de conexión</string>
|
||||
<string name="cw_manual_hermes_title">Introduzca la dirección de Hermes</string>
|
||||
<string name="cw_manual_hermes_title">Introduce la dirección del gateway</string>
|
||||
<string name="cw_manual_hermes_description">Introduce la dirección del panel que abres en el navegador. Si no abre en este teléfono, inicia hermes dashboard y comprueba Wi-Fi o Tailscale.</string>
|
||||
<string name="cw_hermes_address">Dirección de Hermes</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 o hermes.example.com</string>
|
||||
@@ -382,6 +382,13 @@
|
||||
<string name="cw_pairing_code_label">código de emparejamiento</string>
|
||||
<string name="cw_pairing_code_placeholder">p.ej. ABC123</string>
|
||||
<string name="cw_pair_button">Emparejar</string>
|
||||
<string name="cw_mixed_route_plain">%1$s usa HTTP/WS sin cifrar. Úsalo solo en una red privada de confianza o mediante una VPN que controles.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s usa HTTPS/WSS con cifrado de transporte.</string>
|
||||
<string name="cw_mixed_safe">La aplicación comprueba estas rutas y selecciona una disponible. Puedes cambiar la ruta preferida más tarde.</string>
|
||||
<string name="cw_pair_in_progress">Procesando…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">Preparando la puerta de enlace…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">Abriendo el inicio de sesión seguro…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Emparejando Relay…</string>
|
||||
<string name="cw_show_code_subtitle">Use esto cuando no pueda escanear un emparejamiento Relay QR. Establece tus URL y, a continuación, registra el código que aparece a continuación en el host que ejecuta Hermes-Relay.</string>
|
||||
<string name="cw_step_copy_code">1. Copia este código</string>
|
||||
<string name="cw_copy_pairing_code">Copiar código de emparejamiento</string>
|
||||
@@ -400,9 +407,6 @@
|
||||
<string name="cw_insecure_relay_warning">Este relay utiliza ws:// simple: el tráfico no está cifrado.</string>
|
||||
<string name="cw_insecure_relay_trust">Continúe solo si confía en la red en cualquier conexión (LAN, Tailscale, VPN).</string>
|
||||
<string name="cw_insecure_ack">Entiendo que este emparejamiento envía tráfico en texto sin formato, visible para cualquier persona en la red.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s es simple ws://: está bien en casa o en la oficina, no en público Wi-Fi.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s está encriptado (wss://) y la aplicación lo usa automáticamente cuando no se puede acceder a %2$s.</string>
|
||||
<string name="cw_mixed_safe">Estás a salvo en cualquier red.</string>
|
||||
<string name="cw_connecting_to_hermes">Conexión a Hermes</string>
|
||||
<string name="cw_connecting_detail">Comprobación del servidor API, la clave guardada y el panel.</string>
|
||||
<string name="cw_pairing_title">Emparejamiento…</string>
|
||||
@@ -428,7 +432,7 @@
|
||||
<string name="cw_voice_after_connect">Comprobado después de conectar</string>
|
||||
<string name="cw_remote">Remoto</string>
|
||||
<string name="cw_remote_fallback_ready">Ruta alternativa lista para usar fuera de casa</string>
|
||||
<string name="cw_remote_lan_only">Solo LAN: agregue un Tailscale o una ruta pública en Configuración → Conexiones → Rutas</string>
|
||||
<string name="cw_remote_lan_only">Solo LAN: agregue una ruta Tailscale o pública en Configuración → Gateways → Rutas</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">Herramientas eléctricas emparejadas</string>
|
||||
<string name="cw_relay_optional">Opcional para Terminal y Bridge</string>
|
||||
@@ -446,6 +450,17 @@
|
||||
<string name="endpoints_preferred">Privilegiado</string>
|
||||
<string name="endpoints_automatic">Automático</string>
|
||||
<string name="endpoints_current_route">Ruta actual: %1$s (%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">Actualmente no hay ninguna ruta alternativa seleccionada.</string>
|
||||
<string name="endpoints_selection_reason">Prioridad %1$d (0 es la más alta) · %2$s</string>
|
||||
<string name="endpoints_reachable_now">Accesible ahora</string>
|
||||
<string name="endpoints_last_check_failed">La última comprobación falló</string>
|
||||
<string name="endpoints_reachability_not_checked">Accesibilidad no comprobada</string>
|
||||
<string name="endpoints_security_application_tls">TLS de aplicación</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Cifrado por Tailscale · sin TLS de aplicación</string>
|
||||
<string name="endpoints_security_wireguard_overlay">Cifrado por WireGuard · sin TLS de aplicación</string>
|
||||
<string name="endpoints_security_secure_link">Cifrado por Hermes Secure Link</string>
|
||||
<string name="endpoints_security_private_plain">Red privada · sin TLS de aplicación</string>
|
||||
<string name="endpoints_security_public_plain">La ruta pública no está cifrada</string>
|
||||
<string name="endpoints_cancel_manual_switch">Cancelar el cambio manual: volver a %1$s</string>
|
||||
<string name="endpoints_stop_preferring">Dejar de preferir: volver a automático</string>
|
||||
<string name="endpoints_checking">De cheques…</string>
|
||||
@@ -603,7 +618,7 @@
|
||||
<string name="relay_state_needs_repair">Requiere volver a emparejar</string>
|
||||
<string name="settings_no_connection">Sin conexión</string>
|
||||
<string name="settings_server_default">Valor predeterminado del servidor</string>
|
||||
<string name="settings_connections">Conexiones</string>
|
||||
<string name="settings_connections">Gateways</string>
|
||||
<string name="settings_connections_desc">API, tablero, emparejamiento de relay y rutas</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Gestión Hermes</string>
|
||||
@@ -741,14 +756,31 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">Gateway necesita Administrar el inicio de sesión</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Inicie sesión una vez desde la pestaña Administrar para desbloquear el pensamiento en vivo sobre /api/ws.</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Inicia sesión una vez para desbloquear Chat, sesiones, Administrar y la voz estándar en esta conexión de Hermes.</string>
|
||||
<string name="chat_settings_completions">Terminaciones</string>
|
||||
<string name="chat_settings_offline">desconectado</string>
|
||||
<string name="conn_back">Atrás</string>
|
||||
<string name="conn_title">Conexiones</string>
|
||||
<string name="conn_add_connection">Agregar conexión</string>
|
||||
<string name="conn_no_connections">Aún no hay conexiones</string>
|
||||
<string name="conn_no_connections_desc">Toque Agregar conexión para conectarse a Hermes.</string>
|
||||
<string name="conn_title">Gateways</string>
|
||||
<string name="conn_add_connection">Agregar gateway</string>
|
||||
<string name="conn_no_connections">Aún no hay gateways</string>
|
||||
<string name="conn_no_connections_desc">Toca Agregar gateway para conectarte a Hermes.</string>
|
||||
<string name="gateways_title">Gateways</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d gateway</item><item quantity="other">%d gateways</item></plurals>
|
||||
<string name="gateway_add">Agregar gateway</string>
|
||||
<string name="gateways_empty_title">Aún no hay gateways</string>
|
||||
<string name="gateways_empty_body">Agrega un gateway para conectar este teléfono a Hermes.</string>
|
||||
<string name="gateway_route_not_configured">No hay ruta configurada</string>
|
||||
<string name="gateway_status_online">Gateway en línea</string>
|
||||
<string name="gateway_status_sign_in_required">Inicio de sesión requerido</string>
|
||||
<string name="gateway_status_offline">Gateway sin conexión</string>
|
||||
<string name="gateway_status_checking">Comprobando gateway…</string>
|
||||
<string name="gateway_status_not_checked">Gateway sin comprobar</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">Última comprobación: requiere inicio de sesión</string>
|
||||
<string name="gateway_status_last_check_succeeded">Última comprobación correcta</string>
|
||||
<string name="gateway_status_last_check_failed">Falló la última comprobación</string>
|
||||
<string name="gateway_status_no_route">Sin ruta de gateway</string>
|
||||
<string name="gateway_status_unavailable">Gateway no disponible</string>
|
||||
<string name="conn_add_requires_parent_access">Desbloquea el acceso parental antes de agregar un gateway.</string>
|
||||
<string name="conn_active">Activo</string>
|
||||
<string name="conn_connected">Conectado</string>
|
||||
<string name="conn_standard_not_paired">Estándar · Relay no emparejado</string>
|
||||
@@ -823,6 +855,8 @@
|
||||
<string name="detail_tab_routes">Rutas</string>
|
||||
<string name="detail_tab_advanced">Avanzado</string>
|
||||
<string name="detail_tab_security">Seguridad</string>
|
||||
<string name="detail_tab_access">Acceso</string>
|
||||
<string name="detail_current_route">Ruta actual</string>
|
||||
<string name="bot_mode_title">Modo Bot</string>
|
||||
<string name="bot_mode_drawer_summary">Bots y salas de grupo</string>
|
||||
<string name="bot_mode_search">Buscar en Modo Bot</string>
|
||||
@@ -880,6 +914,8 @@
|
||||
<string name="drawer_delete_session_title">¿Eliminar sesión?</string>
|
||||
<string name="drawer_delete_session_prefix">Esto eliminará permanentemente \"</string>
|
||||
<string name="drawer_delete_session_suffix">\" y su historial de mensajes.</string>
|
||||
<string name="drawer_remove_provisional_thread_title">¿Quitar hilo?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">Esto quita «%1$s» de este dispositivo. No elimina el historial promocionado ni el del servidor.</string>
|
||||
<string name="drawer_untitled">Intitulado</string>
|
||||
<string name="drawer_delete">Borrar</string>
|
||||
<string name="drawer_thread">Hilo</string>
|
||||
@@ -908,7 +944,7 @@
|
||||
<string name="bridge_relay_label">relay</string>
|
||||
<string name="bridge_safety_label">seguridad</string>
|
||||
<string name="bridge_not_connected_title">Relay no conectado</string>
|
||||
<string name="bridge_not_connected_body">Los comandos Bridge viajan a través del relay. Empareje un relay en Configuración → Conexiones para que el bridge realmente haga cualquier cosa.</string>
|
||||
<string name="bridge_not_connected_body">Los comandos de Bridge viajan mediante Relay. Empareje Relay en Configuración → Gateways para usar Bridge.</string>
|
||||
<string name="bridge_accessibility_needed">El servicio de accesibilidad debe estar habilitado primero.</string>
|
||||
<string name="bridge_open_settings">Abrir configuración</string>
|
||||
<string name="bridge_allow_agent_control">Permitir el control del agente</string>
|
||||
@@ -943,8 +979,8 @@
|
||||
<string name="bridge_core_relay_body">Bridge Core utiliza la misma sesión relay emparejada como terminal, notificación, medios y funciones de voz.</string>
|
||||
<string name="bridge_core_surface_title">Superficie Bridge</string>
|
||||
<string name="bridge_core_surface_meta">no oculto en la configuración</string>
|
||||
<string name="bridge_core_connections">Conexiones</string>
|
||||
<string name="bridge_core_connections_sub">Emparejar, cambiar y verificar rutas relay</string>
|
||||
<string name="bridge_core_connections">Gateways</string>
|
||||
<string name="bridge_core_connections_sub">Emparejar Relay, cambiar gateways y verificar rutas</string>
|
||||
<string name="bridge_core_terminal_tile">Terminal</string>
|
||||
<string name="bridge_core_terminal_sub">Conéctelo a su terminal Hermes relay</string>
|
||||
<string name="bridge_core_voice">Voz</string>
|
||||
@@ -1274,7 +1310,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Deja que Hermes me envíe un mensaje</string>
|
||||
<string name="proactive_allow_proactive_messages">Permitir mensajes proactivos</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">Su agente puede comunicarse por sí solo: recordatorios, trabajos terminados, alertas. Sus mensajes aparecen como Threads en el Chat, donde puedes responder.</string>
|
||||
<string name="proactive_not_paired_warning">Aún no emparejado: emparéjelo con su servidor Hermes en Configuración → Conexiones para comenzar a recibir mensajes.</string>
|
||||
<string name="proactive_not_paired_warning">Aún no está emparejado: empareje Relay en Configuración → Gateways para comenzar a recibir mensajes.</string>
|
||||
<string name="proactive_your_threads">Tu Threads</string>
|
||||
<string name="proactive_your_threads_desc">Cada conversación que inicia su agente se muestra como un hilo en el chat: abra la lista de sesiones, filtre a Threads y responda allí mismo.</string>
|
||||
<string name="proactive_open_chat">Abrir chat</string>
|
||||
@@ -1452,7 +1488,7 @@
|
||||
<string name="voice_settings_engine_realtime">Agente en tiempo real</string>
|
||||
<string name="voice_settings_engine_realtime_desc">Voz en tiempo real nativa del proveedor con herramientas gestionadas por Hermes. Requiere un Relay emparejado.</string>
|
||||
<string name="voice_settings_experimental">Experimental</string>
|
||||
<string name="voice_settings_realtime_no_relay">No hay Relay configurado para esta conexión, por lo que el agente en tiempo real no puede iniciarse. Empareje Relay en Configuración → Conexiones, o vuelva a Hermes Chat + Salida de voz.</string>
|
||||
<string name="voice_settings_realtime_no_relay">No hay Relay configurado para este gateway, por lo que el agente en tiempo real no puede iniciarse. Empareje Relay en Configuración → Gateways, o vuelva a Hermes Chat + Salida de voz.</string>
|
||||
<string name="voice_settings_route_label">Ruta STT/TTS</string>
|
||||
<string name="voice_settings_status_ready">Listo</string>
|
||||
<string name="voice_settings_status_sign_in_required">Es necesario iniciar sesión en el panel</string>
|
||||
@@ -1665,8 +1701,8 @@
|
||||
<string name="dashboard_tile_keys_sub">Claves de proveedor + secretos de entorno</string>
|
||||
<string name="dashboard_tile_config_title">configuración</string>
|
||||
<string name="dashboard_tile_config_sub">Opciones de esquema y tiempo de ejecución</string>
|
||||
<string name="dashboard_nav_connections_title">Conexiones</string>
|
||||
<string name="dashboard_nav_connections_sub">Emparejar, cambiar, verificar rutas</string>
|
||||
<string name="dashboard_nav_connections_title">Gateways</string>
|
||||
<string name="dashboard_nav_connections_sub">Iniciar sesión, emparejar Relay, cambiar y verificar rutas</string>
|
||||
<string name="dashboard_hub_title">Cubo Relay</string>
|
||||
<string name="dashboard_hub_meta">descripción general</string>
|
||||
<string name="dashboard_health_loading">…</string>
|
||||
@@ -1690,7 +1726,7 @@
|
||||
<string name="dashboard_minutes_ago">Hace %1$dm</string>
|
||||
<string name="dashboard_hours_ago">Hace %1$dh</string>
|
||||
<string name="dashboard_signin_required_title">Es necesario iniciar sesión en el panel</string>
|
||||
<string name="dashboard_signin_required_body">Administrar utiliza la sesión del panel Hermes en %1$s.</string>
|
||||
<string name="dashboard_signin_required_body">Inicia sesión en Hermes en %1$s para Chat, sesiones, Administrar y voz estándar.</string>
|
||||
<string name="dashboard_signin_route_hint">No se pudo reutilizar la sesión guardada del panel en la ruta %1$s. Vuelve a iniciar sesión para actualizarla en las rutas de confianza de esta conexión.</string>
|
||||
<string name="dashboard_signin_with_provider">Iniciar sesión con %1$s</string>
|
||||
<string name="dashboard_username_password">Nombre de usuario y contraseña</string>
|
||||
@@ -1699,6 +1735,7 @@
|
||||
<string name="dashboard_sign_in">Iniciar sesión</string>
|
||||
<string name="dashboard_signing_in">Iniciando sesión…</string>
|
||||
<string name="dashboard_no_supported_provider">Este panel no anunciaba un proveedor de inicio de sesión Android compatible.</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">El proveedor de inicio de sesión guardado no está disponible. Elige otro proveedor configurado o vuelve a intentarlo más tarde.</string>
|
||||
<string name="dashboard_oauth_initial_status">Complete el inicio de sesión en la página del panel seguro.</string>
|
||||
<string name="dashboard_oauth_verifying">Verificando la sesión del panel...</string>
|
||||
<string name="dashboard_oauth_not_accepted">El inicio de sesión aún no fue aceptado. Finalice el flujo del panel para continuar.</string>
|
||||
@@ -2104,6 +2141,8 @@
|
||||
<string name="active_section_no_response_from_relay">No hay respuesta de relay</string>
|
||||
<string name="active_section_no_route_reachable">No hay ruta accesible</string>
|
||||
<string name="active_section_no_routes_answered_probe">Ninguna ruta respondió a la sonda.</string>
|
||||
<string name="active_section_no_reachable_route_title">No hay ninguna ruta de Gateway accesible</string>
|
||||
<string name="active_section_no_reachable_route_body">Ninguna de las rutas de Gateway configuradas respondió. Activa Tailscale, Wi-Fi o los datos móviles y vuelve a comprobar. Despliega una ruta abajo para ver los resultados de Dashboard, API y Relay.</string>
|
||||
<string name="active_section_not_advertised">No anunciado</string>
|
||||
<string name="active_section_not_checked">No comprobado</string>
|
||||
<string name="active_section_not_configured">No configurado</string>
|
||||
@@ -2229,7 +2268,7 @@
|
||||
<string name="conn_info_loading_profiles">Cargando perfiles…</string>
|
||||
<string name="conn_info_local_display_name">Nombre para mostrar local</string>
|
||||
<string name="conn_info_locked_to">Bloqueado en %1$s</string>
|
||||
<string name="conn_info_manage_connections">Administrar conexiones</string>
|
||||
<string name="conn_info_manage_connections">Administrar gateways</string>
|
||||
<string name="conn_info_manage_profiles">Administrar visualización de perfiles</string>
|
||||
<string name="conn_info_manage_profiles_hint">Reordena los perfiles u oculta los que no uses. El perfil activo permanece visible.</string>
|
||||
<string name="conn_info_move_profile_up">Mover %1$s hacia arriba</string>
|
||||
@@ -2476,8 +2515,8 @@
|
||||
<string name="conn_security_empty">Aún no hay ruta activa. Conéctese a un servidor para ver cómo está protegida cada parte de la conexión.</string>
|
||||
<string name="conn_security_learn_more">Más información sobre la seguridad de la conexión →</string>
|
||||
<string name="conn_switcher_title">Conexión del interruptor</string>
|
||||
<string name="conn_switcher_empty">Aún no hay conexiones</string>
|
||||
<string name="conn_switcher_manage">Administrar conexiones…</string>
|
||||
<string name="conn_switcher_empty">Aún no hay gateways</string>
|
||||
<string name="conn_switcher_manage">Administrar gateways…</string>
|
||||
<string name="diagnostics_title">Actividad reciente</string>
|
||||
<string name="diagnostics_clear">Claro</string>
|
||||
<string name="diagnostics_all">Todo</string>
|
||||
@@ -2768,7 +2807,7 @@
|
||||
<string name="screen_bridge_label">Bridge</string>
|
||||
<string name="screen_manage_label">Administrar</string>
|
||||
<string name="screen_settings_label">Ajustes</string>
|
||||
<string name="screen_connections_label">Conexiones</string>
|
||||
<string name="screen_connections_label">Gateways</string>
|
||||
<string name="screen_connection_label">Conexión</string>
|
||||
<string name="screen_voice_label">Voz</string>
|
||||
<string name="screen_notification_companion_label">Compañero de notificación</string>
|
||||
@@ -2849,7 +2888,7 @@
|
||||
<string name="cw_hint_chat">Charlar</string>
|
||||
<string name="cw_hint_manage">Administrar</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s espera http:// o https:// (los hosts básicos obtienen http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s espera http:// o https:// (los hosts privados usan http:// y los públicos https://)</string>
|
||||
<string name="cw_label_api_key">Clave API</string>
|
||||
<string name="cw_label_api_server">Servidor API</string>
|
||||
<string name="cw_label_dashboard">Panel</string>
|
||||
@@ -2902,7 +2941,7 @@
|
||||
<string name="cw_step_3_3">Paso 3 de 3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Red Tailscale detectada</string>
|
||||
<string name="cw_tailscale_supporting_other">Cuando esté lejos de la red del servidor, cambie manualmente el tiempo de espera, la dirección, el puerto API (8642) y los valores predeterminados de http:// se pueden cambiar en Configuración → Conexiones → Rutas.</string>
|
||||
<string name="cw_tailscale_supporting_other">Cuando esté fuera de la red del servidor, puede cambiar el tiempo de espera, la dirección, el puerto API (8642) y los valores de http:// en Configuración → Gateways → Rutas.</string>
|
||||
<string name="cw_value_derived">Detectado automáticamente</string>
|
||||
<string name="cw_value_included">Incluido</string>
|
||||
<string name="cw_value_not_included">No incluido</string>
|
||||
@@ -3094,6 +3133,7 @@
|
||||
<string name="card_send_answer_a11y">Enviar respuesta</string>
|
||||
<string name="card_submit">Entregar</string>
|
||||
<string name="card_answer_placeholder">Escribe una respuesta...</string>
|
||||
<string name="card_other_answer_placeholder">Otra (escribe tu respuesta)…</string>
|
||||
<string name="session_ttl_title">Mantenga este emparejamiento para...</string>
|
||||
<string name="session_ttl_intro">Su teléfono se volverá a conectar automáticamente durante esta ventana. Puedes revocar el emparejamiento en cualquier momento.</string>
|
||||
<string name="session_ttl_stays_paired">Este dispositivo permanecerá emparejado hasta que lo revoques.</string>
|
||||
@@ -3231,7 +3271,7 @@
|
||||
<string name="active_section_choose_how_phone_reaches_named">Cómo accede este teléfono a %1$s</string>
|
||||
<string name="active_section_dashboard_home_lan">Dashboard · Red LAN doméstica</string>
|
||||
<string name="active_section_scan_relay_qr">Escanear QR de Relay</string>
|
||||
<string name="active_section_other_relay_methods">Otros métodos de vinculación</string>
|
||||
<string name="active_section_direct_relay_endpoint">Endpoint directo de Relay</string>
|
||||
<string name="endpoints_tailscale_setup_hint">Tailscale debe estar conectado en ambos dispositivos y Hermes Dashboard debe ser accesible por el puerto 9119.</string>
|
||||
<string name="endpoints_setup_help">Ayuda para configurar Tailscale</string>
|
||||
<string name="voice_settings_provider_desc">Dónde se genera la voz. Las opciones disponibles vienen de este host Hermes y sus proveedores instalados.</string>
|
||||
@@ -3256,7 +3296,8 @@
|
||||
<string name="dev_settings_image_generation_lab">Laboratorio de generación de imágenes</string>
|
||||
<string name="dev_settings_image_generation_lab_desc">Previsualiza los ciclos de generación y la revelación final de la imagen</string>
|
||||
<string name="dev_settings_open_image_generation_lab_cd">Abrir el laboratorio de generación de imágenes</string>
|
||||
<string name="dashboard_native_signin_opening">Completa el inicio de sesión en el navegador y vuelve aquí.</string>
|
||||
<string name="dashboard_native_signin_opening">Completa el inicio de sesión en el navegador. Si el proveedor inicia sesión sin volver, regresa y toca Continuar inicio de sesión.</string>
|
||||
<string name="dashboard_native_signin_continue">Continuar inicio de sesión</string>
|
||||
<string name="dashboard_native_signin_cancelled">Inicio de sesión en el navegador cancelado.</string>
|
||||
<string name="dashboard_native_signin_requires_https">El inicio de sesión seguro en el navegador requiere una dirección HTTPS del panel.</string>
|
||||
<string name="dashboard_native_signin_unavailable">El inicio de sesión seguro en el navegador no está disponible para esta conexión. Actualiza la conexión e inténtalo de nuevo.</string>
|
||||
@@ -3713,6 +3754,9 @@
|
||||
<string name="plugins_remove">Eliminar</string>
|
||||
<string name="plugins_remove_confirm">¿Eliminar «%1$s»? Esta página del plugin dejará de aparecer en los dispositivos Android conectados.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">Análisis de repositorios del host</string>
|
||||
<string name="git_state_host_scanning_on_desc">Activado para esta puerta de enlace · Las escrituras de Git requieren un permiso aparte.</string>
|
||||
<string name="git_state_host_scanning_off_desc">Permite que este teléfono solicite a esta puerta de enlace analizar sus raíces de Git configuradas para encontrar repositorios, ramas y cambios. Las escrituras de Git requieren un permiso aparte.</string>
|
||||
<string name="git_state_back">Atrás</string>
|
||||
<string name="git_state_staged">Preparados</string>
|
||||
<string name="git_state_modified">Modificados</string>
|
||||
@@ -3756,7 +3800,7 @@
|
||||
<string name="git_state_switch_stash">Cambiar (guardar en stash si hay cambios)</string>
|
||||
<string name="support_bundle_review">Revisar información de soporte</string>
|
||||
<string name="support_bundle_title">Información de soporte</string>
|
||||
<string name="support_bundle_privacy">Nada se sube automáticamente. Revisa la exportación local con hasta %1$d informes.</string>
|
||||
<string name="support_bundle_privacy">Nada se sube automáticamente. Revisa la exportación local con %1$d informes y diagnósticos recientes.</string>
|
||||
<string name="support_bundle_copied">Información de soporte copiada</string>
|
||||
<string name="support_bundle_no_share">Información de soporte copiada — no se encontró una aplicación para compartir</string>
|
||||
<string name="support_bundle_share_title">Compartir información de soporte de Hermes-Relay</string>
|
||||
@@ -4120,7 +4164,7 @@
|
||||
<string name="custom_theme_modified">Cambios sin guardar</string>
|
||||
<string name="custom_theme_saved_count">%1$d preajustes guardados</string>
|
||||
<string name="chat_settings_show_git_workspace">Mostrar el espacio de Git en el chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Muestra la rama y los cambios encima del cuadro de texto</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Muestra el estado de Git y los cambios en Chat cuando el análisis de repositorios del host está activado. El espacio de Git completo sigue disponible cuando esto está desactivado.</string>
|
||||
<string name="chat_git_open_workspace">Abrir el espacio de Git</string>
|
||||
<string name="chat_git_branch">Rama %1$s</string>
|
||||
<string name="chat_git_additions">%1$d adiciones</string>
|
||||
@@ -4128,4 +4172,86 @@
|
||||
<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="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>
|
||||
<string name="current_chat_activity_summary">%1$d agentes · %2$d procesos</string>
|
||||
<string name="current_chat_activity_close">Cerrar vista previa de actividad</string>
|
||||
<string name="current_chat_activity_empty">No hay actividad actual en este chat</string>
|
||||
<string name="current_chat_activity_latest">Más reciente</string>
|
||||
<string name="agent_activity_section">Actividad de agentes en vivo</string>
|
||||
<string name="agent_activity_disclosure">Actualizaciones recibidas por este chat. Es posible que el historial completo del agente secundario no esté disponible.</string>
|
||||
<string name="agent_activity_fallback">Agente %d</string>
|
||||
<string name="agent_activity_task_position">%1$d de %2$d · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s, %2$s, agente %3$d de %4$d</string>
|
||||
<string name="agent_activity_duration">%1$.1fs</string>
|
||||
<string name="agent_activity_older_omitted">Se omitió la actividad anterior</string>
|
||||
<string name="agent_activity_partial">Se reanudaron las actualizaciones en vivo. Puede faltar actividad mientras estaba sin conexión.</string>
|
||||
<string name="agent_activity_event_started">Iniciado</string>
|
||||
<string name="agent_activity_event_update">Actualización</string>
|
||||
<string name="agent_activity_event_tool">Vista previa de herramienta</string>
|
||||
<string name="agent_activity_status_started">Iniciando</string>
|
||||
<string name="agent_activity_status_thinking">Pensando</string>
|
||||
<string name="agent_activity_status_tool">Usando una herramienta</string>
|
||||
<string name="agent_activity_status_progress">Trabajando</string>
|
||||
<string name="agent_activity_status_completed">Completado</string>
|
||||
<string name="agent_activity_status_failed">Falló</string>
|
||||
<string name="agent_activity_status_interrupted">Interrumpido</string>
|
||||
<string name="agent_activity_status_unavailable">Estado final no disponible</string>
|
||||
<string name="agent_activity_child_loading">Abriendo el historial secundario de solo lectura…</string>
|
||||
<string name="agent_activity_child_unavailable">El historial secundario no está disponible en esta versión o ruta de Hermes. La actividad de la sesión principal se muestra arriba.</string>
|
||||
<string name="agent_activity_child_live">Historial secundario · actualizaciones en vivo</string>
|
||||
<string name="agent_activity_child_history">Historial secundario · solo lectura</string>
|
||||
<string name="agent_activity_child_truncated">Se muestra la actividad secundaria reciente · se omitieron detalles anteriores o demasiado grandes</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Introduce la dirección del Gateway Hermes</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">Dirección autenticada del Dashboard</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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">Las rutas LAN, Tailscale y públicas permiten llegar a este Gateway. La alternativa API y las extensiones Relay son opcionales.</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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">Usar la ruta seleccionada</string>
|
||||
<string name="active_section_use_selected_route_failed">No se pudo volver a asociar el inicio de sesión del Dashboard con la ruta seleccionada.</string>
|
||||
<string name="active_section_forget_sign_in_origin">Olvidar el origen de inicio de sesión</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<string name="notification_companion_label">Hermes-Relay 通知コンパニオン</string>
|
||||
|
||||
<string name="onboarding_skip_setup_title">セットアップをスキップしますか?</string>
|
||||
<string name="onboarding_skip_setup_text">問題ありません。デモを探索して Hermes-Relay がどのように機能するかを確認し、[設定] → [接続] からいつでも独自の Hermes サーバーに接続できます。パワーツール用のRelayペアリングは後から追加することもできます。</string>
|
||||
<string name="onboarding_skip_setup_text">問題ありません。デモを試した後でも、[設定] → [ゲートウェイ] から独自の Hermes ゲートウェイをいつでも追加できます。パワーツール用の Relay ペアリングは後から追加できます。</string>
|
||||
<string name="onboarding_skip_for_now">今のところスキップしてください</string>
|
||||
<string name="onboarding_go_back">戻る</string>
|
||||
<string name="onboarding_skip">スキップ</string>
|
||||
@@ -150,7 +150,7 @@
|
||||
<string name="chat_editing_notice">編集中 — 会話を巻き戻します</string>
|
||||
<string name="chat_mic_perm_needed">マイクの許可が必要です</string>
|
||||
<string name="chat_mic_perm_body">[設定を開く] をタップし、音声モードを使用するためのマイクへのアクセスを許可します。</string>
|
||||
<string name="chat_manage_connections">接続を管理する</string>
|
||||
<string name="chat_manage_connections">ゲートウェイを管理</string>
|
||||
<string name="chat_no_clipboard_image">クリップボードに画像がありません</string>
|
||||
<string name="chat_copied_to_clipboard">クリップボードにコピーされました</string>
|
||||
<string name="chat_camera_open_failed">カメラを開けませんでした</string>
|
||||
@@ -211,7 +211,7 @@
|
||||
<string name="conn_label_route">ルート</string>
|
||||
<string name="conn_label_status">状態</string>
|
||||
<string name="conn_label_connect">接続する</string>
|
||||
<string name="conn_label_connections">接続</string>
|
||||
<string name="conn_label_connections">ゲートウェイ</string>
|
||||
<string name="conn_detail_add_connection">バニラ Hermes API/ダッシュボード接続を追加します</string>
|
||||
<string name="conn_detail_waiting_network">Android がインターネット ルートを報告するのを待っています</string>
|
||||
<string name="conn_detail_chat_unavailable">チャットやプロフィール通話が利用できない場合があります</string>
|
||||
@@ -297,19 +297,19 @@
|
||||
<string name="error_classify_open_settings">設定を開く</string>
|
||||
|
||||
<!-- Connection wizard — Connect page essentials -->
|
||||
<string name="cw_connect_to_hermes">Hermes に接続します</string>
|
||||
<string name="cw_connect_to_hermes">ゲートウェイを追加</string>
|
||||
<string name="cw_nearby_description">このネットワーク上の Hermes を検索します。ダッシュボードとゲートウェイが、チャット、管理、音声の標準接続を提供します。</string>
|
||||
<string name="cw_connection_chooser_description">利用するセットアップを選択してください。Hermes Relay は任意です。</string>
|
||||
<string name="cw_connection_chooser_description">1 つのゲートウェイは 1 つの Hermes 環境です。この端末からの接続方法を選択してください。</string>
|
||||
<string name="cw_scan_setup_qr_title">Hermes セットアップ QR をスキャン</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">ローカル、リモート、および利用可能な Relay ルートを設定します</string>
|
||||
<string name="cw_recommended">推奨</string>
|
||||
<string name="cw_other_ways_to_connect">その他の接続方法</string>
|
||||
<string name="cw_other_ways_to_connect">ゲートウェイを選択</string>
|
||||
<string name="cw_advanced">詳細設定</string>
|
||||
<string name="cw_cloud_title">Nous ホスト版 Hermes</string>
|
||||
<string name="cw_cloud_subtitle">ホスト済みエージェントに接続します</string>
|
||||
<string name="cw_server_vps_title">サーバーまたは VPS</string>
|
||||
<string name="cw_server_vps_subtitle">安全な Dashboard アドレスを入力します</string>
|
||||
<string name="cw_relay_optional_note">標準のチャット、管理、音声は Relay なしで動作します。互換性のあるセットアップ QR では、利用可能な場合に Relay の拡張機能も追加されます。</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_cloud_entry_title">Nous ホスト版 Hermes に接続</string>
|
||||
<string name="cw_cloud_entry_description">Nous Portal に表示されるエージェントのアドレスを入力してください。Hermes が見つかった後、安全にサインインします。</string>
|
||||
<string name="cw_cloud_agent_name">エージェントのアドレス</string>
|
||||
@@ -336,7 +336,7 @@
|
||||
<string name="cw_nearby_search_again">再検索</string>
|
||||
<string name="cw_nearby_enter_address">アドレスを入力</string>
|
||||
<string name="cw_other_connection_methods">その他の接続方法</string>
|
||||
<string name="cw_manual_hermes_title">Hermes のアドレスを入力</string>
|
||||
<string name="cw_manual_hermes_title">ゲートウェイのアドレスを入力</string>
|
||||
<string name="cw_manual_hermes_description">ブラウザで開くダッシュボードアドレスを入力します。このスマートフォンで開けない場合は hermes dashboard を起動し、Wi-Fi または Tailscale を確認してください。</string>
|
||||
<string name="cw_hermes_address">Hermes アドレス</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 または hermes.example.com</string>
|
||||
@@ -429,6 +429,13 @@
|
||||
<string name="cw_pairing_code_label">ペアリングコード</string>
|
||||
<string name="cw_pairing_code_placeholder">例えばABC123</string>
|
||||
<string name="cw_pair_button">ペア</string>
|
||||
<string name="cw_mixed_route_plain">%1$s は暗号化されていない HTTP/WS を使用します。信頼できるプライベートネットワークまたは自分で管理する VPN でのみ使用してください。</string>
|
||||
<string name="cw_mixed_route_secure">%1$s はトランスポート暗号化された HTTPS/WSS を使用します。</string>
|
||||
<string name="cw_mixed_safe">アプリはこれらのルートを確認し、利用可能なルートを選択します。優先ルートは後から変更できます。</string>
|
||||
<string name="cw_pair_in_progress">処理中…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">ゲートウェイを準備中…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">安全なサインインを開いています…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Relay をペアリング中…</string>
|
||||
<string name="cw_show_code_subtitle">Relay と QR のペアをスキャンできない場合にこれを使用します。 URL を設定し、Hermes-Relay を実行しているホストに以下のコードを登録します。</string>
|
||||
<string name="cw_step_copy_code">1. このコードをコピーします</string>
|
||||
<string name="cw_copy_pairing_code">ペアリングコードをコピーする</string>
|
||||
@@ -447,9 +454,6 @@
|
||||
<string name="cw_insecure_relay_warning">このRelayはプレーンな ws:// を使用します。トラフィックは暗号化されません。</string>
|
||||
<string name="cw_insecure_relay_trust">いずれかの接続 (LAN、Tailscale、VPN) 上のネットワークを信頼する場合にのみ続行してください。</string>
|
||||
<string name="cw_insecure_ack">このペアリングではトラフィックがプレーン テキストで送信され、ネットワーク上の誰にでも表示されると理解しています。</string>
|
||||
<string name="cw_mixed_route_plain">%1$s はプレーンな ws:// です。自宅やオフィスでは問題ありませんが、公衆 Wi-Fi には適しません。</string>
|
||||
<string name="cw_mixed_route_secure">%1$s は暗号化されています (wss://) であり、%2$s に到達できない場合、アプリはそれを自動的に使用します。</string>
|
||||
<string name="cw_mixed_safe">どのネットワークでも安全です。</string>
|
||||
<string name="cw_connecting_to_hermes">Hermes に接続しています</string>
|
||||
<string name="cw_connecting_detail">API サーバー、保存されたキー、ダッシュボードを確認します。</string>
|
||||
<string name="cw_pairing_title">ペアリング中…</string>
|
||||
@@ -475,7 +479,7 @@
|
||||
<string name="cw_voice_after_connect">接続後に確認したところ</string>
|
||||
<string name="cw_remote">リモート</string>
|
||||
<string name="cw_remote_fallback_ready">自宅から離れた場所でも使用できるフォールバック ルート</string>
|
||||
<string name="cw_remote_lan_only">LAN のみ — [設定] → [接続] → [ルート] で Tailscale またはパブリック ルートを追加します。</string>
|
||||
<string name="cw_remote_lan_only">LAN のみ — [設定] → [ゲートウェイ] → [ルート] で Tailscale またはパブリックルートを追加します。</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">パワーツールをペアリングしました</string>
|
||||
<string name="cw_relay_optional">端末およびBridgeの場合はオプション</string>
|
||||
@@ -495,6 +499,17 @@
|
||||
<string name="endpoints_preferred">好ましい</string>
|
||||
<string name="endpoints_automatic">自動</string>
|
||||
<string name="endpoints_current_route">現在のルート: %1$s (%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">現在選択されているフォールバックルートはありません。</string>
|
||||
<string name="endpoints_selection_reason">優先度 %1$d(0 が最高)· %2$s</string>
|
||||
<string name="endpoints_reachable_now">現在到達可能</string>
|
||||
<string name="endpoints_last_check_failed">前回の確認に失敗しました</string>
|
||||
<string name="endpoints_reachability_not_checked">到達可能性は未確認</string>
|
||||
<string name="endpoints_security_application_tls">アプリケーション TLS</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Tailscale で暗号化 · アプリケーション TLS なし</string>
|
||||
<string name="endpoints_security_wireguard_overlay">WireGuard で暗号化 · アプリケーション TLS なし</string>
|
||||
<string name="endpoints_security_secure_link">Hermes Secure Link で暗号化</string>
|
||||
<string name="endpoints_security_private_plain">プライベートネットワーク · アプリケーション TLS なし</string>
|
||||
<string name="endpoints_security_public_plain">公開ルートは暗号化されていません</string>
|
||||
<string name="endpoints_cancel_manual_switch">手動切り替えをキャンセル — %1$s に戻る</string>
|
||||
<string name="endpoints_stop_preferring">優先をやめて自動に戻す</string>
|
||||
<string name="endpoints_checking">チェック中…</string>
|
||||
@@ -674,7 +689,7 @@
|
||||
<string name="relay_state_needs_repair">再ペアリングが必要</string>
|
||||
<string name="settings_no_connection">接続がありません</string>
|
||||
<string name="settings_server_default">サーバーのデフォルト</string>
|
||||
<string name="settings_connections">接続</string>
|
||||
<string name="settings_connections">ゲートウェイ</string>
|
||||
<string name="settings_connections_desc">API、ダッシュボード、Relayのペアリング、およびルート</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
@@ -814,16 +829,33 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">Gateway にはサインインの管理が必要です</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">[管理] タブから一度サインインすると、/api/ws を介したライブ思考のロックが解除されます。</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">一度サインインすると、この Hermes 接続の Chat、セッション、管理、標準音声を利用できます。</string>
|
||||
<string name="chat_settings_completions">完了</string>
|
||||
<string name="chat_settings_offline">オフライン</string>
|
||||
|
||||
<!-- P0: ConnectionsSettingsScreen -->
|
||||
<string name="conn_back">戻る</string>
|
||||
<string name="conn_title">接続</string>
|
||||
<string name="conn_add_connection">接続の追加</string>
|
||||
<string name="conn_no_connections">まだ接続がありません</string>
|
||||
<string name="conn_no_connections_desc">[接続の追加] をタップして Hermes に接続します。</string>
|
||||
<string name="conn_title">ゲートウェイ</string>
|
||||
<string name="conn_add_connection">ゲートウェイを追加</string>
|
||||
<string name="conn_no_connections">ゲートウェイはまだありません</string>
|
||||
<string name="conn_no_connections_desc">[ゲートウェイを追加] をタップして Hermes に接続します。</string>
|
||||
<string name="gateways_title">ゲートウェイ</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d ゲートウェイ</item><item quantity="other">%d ゲートウェイ</item></plurals>
|
||||
<string name="gateway_add">ゲートウェイを追加</string>
|
||||
<string name="gateways_empty_title">ゲートウェイはまだありません</string>
|
||||
<string name="gateways_empty_body">ゲートウェイを追加して、この端末を Hermes に接続します。</string>
|
||||
<string name="gateway_route_not_configured">ルート未設定</string>
|
||||
<string name="gateway_status_online">ゲートウェイはオンライン</string>
|
||||
<string name="gateway_status_sign_in_required">サインインが必要</string>
|
||||
<string name="gateway_status_offline">ゲートウェイはオフライン</string>
|
||||
<string name="gateway_status_checking">ゲートウェイを確認中…</string>
|
||||
<string name="gateway_status_not_checked">ゲートウェイ未確認</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">前回の確認:サインインが必要</string>
|
||||
<string name="gateway_status_last_check_succeeded">前回の確認は成功</string>
|
||||
<string name="gateway_status_last_check_failed">前回の確認は失敗</string>
|
||||
<string name="gateway_status_no_route">ゲートウェイルートなし</string>
|
||||
<string name="gateway_status_unavailable">ゲートウェイを利用できません</string>
|
||||
<string name="conn_add_requires_parent_access">ゲートウェイを追加する前に、保護者アクセスのロックを解除してください。</string>
|
||||
<string name="conn_active">アクティブ</string>
|
||||
<string name="conn_connected">接続済み</string>
|
||||
<string name="conn_standard_not_paired">標準 · Relay はペアになっていません</string>
|
||||
@@ -913,6 +945,8 @@
|
||||
<string name="detail_tab_routes">ルート</string>
|
||||
<string name="detail_tab_advanced">高度な</string>
|
||||
<string name="detail_tab_security">安全</string>
|
||||
<string name="detail_tab_access">アクセス</string>
|
||||
<string name="detail_current_route">現在のルート</string>
|
||||
<string name="detail_dashboard_primary">Dashboard を優先</string>
|
||||
<string name="detail_core_ready">Hermes コアは準備完了</string>
|
||||
<string name="detail_core_configured">Hermes コアを設定済み</string>
|
||||
@@ -976,6 +1010,8 @@
|
||||
<string name="drawer_delete_session_title">セッションを削除しますか?</string>
|
||||
<string name="drawer_delete_session_prefix">「</string>
|
||||
<string name="drawer_delete_session_suffix">」とそのメッセージ履歴を完全に削除します。</string>
|
||||
<string name="drawer_remove_provisional_thread_title">スレッドを削除しますか?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">「%1$s」をこのデバイスから削除します。昇格済みまたはサーバー上の履歴は削除されません。</string>
|
||||
<string name="drawer_untitled">無題</string>
|
||||
<string name="drawer_delete">消去</string>
|
||||
<string name="drawer_thread">糸</string>
|
||||
@@ -1006,7 +1042,7 @@
|
||||
<string name="bridge_relay_label">Relay</string>
|
||||
<string name="bridge_safety_label">安全性</string>
|
||||
<string name="bridge_not_connected_title">Relay が接続されていません</string>
|
||||
<string name="bridge_not_connected_body">Bridge コマンドはRelayを介して送信されます。Bridgeが実際に何かを実行できるようにするには、[設定] → [接続] でRelayをペアリングします。</string>
|
||||
<string name="bridge_not_connected_body">Bridge コマンドは Relay を介して送信されます。Bridge を使用するには、[設定] → [ゲートウェイ] で Relay をペアリングします。</string>
|
||||
<string name="bridge_accessibility_needed">最初にアクセシビリティ サービスを有効にする必要があります。</string>
|
||||
<string name="bridge_open_settings">設定を開く</string>
|
||||
<string name="bridge_allow_agent_control">エージェント制御を許可する</string>
|
||||
@@ -1043,8 +1079,8 @@
|
||||
<string name="bridge_core_relay_body">Bridge コアは、端末、通知、メディア、音声機能と同じペアのRelay セッションを使用します。</string>
|
||||
<string name="bridge_core_surface_title">Bridge 表面</string>
|
||||
<string name="bridge_core_surface_meta">設定では隠されていません</string>
|
||||
<string name="bridge_core_connections">接続</string>
|
||||
<string name="bridge_core_connections_sub">Relayルートのペアリング、切り替え、検証</string>
|
||||
<string name="bridge_core_connections">ゲートウェイ</string>
|
||||
<string name="bridge_core_connections_sub">Relay のペアリング、ゲートウェイの切り替え、ルートの検証</string>
|
||||
<string name="bridge_core_terminal_tile">ターミナル</string>
|
||||
<string name="bridge_core_terminal_sub">Hermes中継端末に取り付けます</string>
|
||||
<string name="bridge_core_voice">声</string>
|
||||
@@ -1402,7 +1438,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Hermes にメッセージを送ってください</string>
|
||||
<string name="proactive_allow_proactive_messages">プロアクティブなメッセージを許可する</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">エージェントは、リマインダー、完了したジョブ、アラートなど、独自に連絡を取ることができます。そのメッセージはチャットに Threads として表示され、そこで返信できます。</string>
|
||||
<string name="proactive_not_paired_warning">まだペアリングされていません — メッセージの受信を開始するには、[設定] → [接続] で Hermes サーバーとペアリングします。</string>
|
||||
<string name="proactive_not_paired_warning">まだペアリングされていません — メッセージを受信するには、[設定] → [ゲートウェイ] で Relay をペアリングします。</string>
|
||||
<string name="proactive_your_threads">あなたのThreads</string>
|
||||
<string name="proactive_your_threads_desc">エージェントが開始した各会話はチャット内のスレッドとして表示されます。セッション リストを開いて Threads にフィルターし、そこですぐに返信します。</string>
|
||||
<string name="proactive_open_chat">オープンチャット</string>
|
||||
@@ -1588,7 +1624,7 @@
|
||||
<string name="voice_settings_engine_realtime">リアルタイムエージェント</string>
|
||||
<string name="voice_settings_engine_realtime_desc">Hermes 仲介ツールを使用したプロバイダーネイティブのリアルタイム音声。ペアになった Relay が必要です。</string>
|
||||
<string name="voice_settings_experimental">実験的</string>
|
||||
<string name="voice_settings_realtime_no_relay">この接続には Relay が構成されていないため、リアルタイム エージェントを開始できません。 [設定] → [接続] で Relay をペアリングするか、Hermes チャット + 音声出力に戻します。</string>
|
||||
<string name="voice_settings_realtime_no_relay">このゲートウェイには Relay が構成されていないため、リアルタイムエージェントを開始できません。[設定] → [ゲートウェイ] で Relay をペアリングするか、Hermes チャット + 音声出力に戻します。</string>
|
||||
<string name="voice_settings_route_label">STT/TTSルート</string>
|
||||
<string name="voice_settings_status_ready">準備ができて</string>
|
||||
<string name="voice_settings_status_sign_in_required">ダッシュボードへのサインインが必要です</string>
|
||||
@@ -1809,8 +1845,8 @@
|
||||
<string name="dashboard_tile_config_sub">スキーマとランタイムのオプション</string>
|
||||
|
||||
<!-- Nav tiles -->
|
||||
<string name="dashboard_nav_connections_title">接続</string>
|
||||
<string name="dashboard_nav_connections_sub">ルートのペアリング、切り替え、検証</string>
|
||||
<string name="dashboard_nav_connections_title">ゲートウェイ</string>
|
||||
<string name="dashboard_nav_connections_sub">サインイン、Relay のペアリング、切り替え、ルートの検証</string>
|
||||
|
||||
<!-- Hub header -->
|
||||
<string name="dashboard_hub_title">Relay ハブ</string>
|
||||
@@ -1846,7 +1882,7 @@
|
||||
|
||||
<!-- Sign-in card -->
|
||||
<string name="dashboard_signin_required_title">ダッシュボードへのサインインが必要です</string>
|
||||
<string name="dashboard_signin_required_body">管理は、%1$s で Hermes ダッシュボード セッションを使用します。</string>
|
||||
<string name="dashboard_signin_required_body">%1$s の Hermes にサインインすると、Chat、セッション、Manage、標準 Voice を利用できます。</string>
|
||||
<string name="dashboard_signin_route_hint">%1$s ルートで保存済みのダッシュボード セッションを再利用できませんでした。再度サインインして、この接続の信頼済みルート全体でセッションを更新してください。</string>
|
||||
<string name="dashboard_signin_with_provider">%1$s でサインインします</string>
|
||||
<string name="dashboard_username_password">ユーザー名 & パスワード</string>
|
||||
@@ -1855,6 +1891,7 @@
|
||||
<string name="dashboard_sign_in">サインイン</string>
|
||||
<string name="dashboard_signing_in">サインイン中…</string>
|
||||
<string name="dashboard_no_supported_provider">このダッシュボードは、サポートされている Android サインイン プロバイダーをアドバタイズしていませんでした。</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">保存済みのサインインプロバイダーを利用できません。別の設定済みプロバイダーを選ぶか、後でもう一度お試しください。</string>
|
||||
|
||||
<!-- OAuth sign-in dialog -->
|
||||
<string name="dashboard_oauth_initial_status">安全なダッシュボード ページでサインインを完了します。</string>
|
||||
@@ -2306,6 +2343,8 @@
|
||||
<string name="active_section_no_response_from_relay">Relayからの応答がありません</string>
|
||||
<string name="active_section_no_route_reachable">到達可能なルートがありません</string>
|
||||
<string name="active_section_no_routes_answered_probe">プローブに応答したルートはありませんでした</string>
|
||||
<string name="active_section_no_reachable_route_title">到達可能な Gateway ルートがありません</string>
|
||||
<string name="active_section_no_reachable_route_body">構成済みの Gateway ルートはいずれも応答しませんでした。Tailscale、Wi-Fi、またはモバイルデータ通信を有効にして、もう一度確認してください。下のルートを展開すると、Dashboard、API、Relay の結果を確認できます。</string>
|
||||
<string name="active_section_not_advertised">宣伝されていない</string>
|
||||
<string name="active_section_not_checked">未チェック</string>
|
||||
<string name="active_section_not_configured">未設定</string>
|
||||
@@ -2439,7 +2478,7 @@
|
||||
<string name="conn_info_loading_profiles">プロファイルを読み込み中…</string>
|
||||
<string name="conn_info_local_display_name">ローカル表示名</string>
|
||||
<string name="conn_info_locked_to">%1$s にロックされています</string>
|
||||
<string name="conn_info_manage_connections">接続を管理する</string>
|
||||
<string name="conn_info_manage_connections">ゲートウェイを管理</string>
|
||||
<string name="conn_info_manage_profiles">プロフィール表示を管理</string>
|
||||
<string name="conn_info_manage_profiles_hint">プロフィールを並べ替えたり、使用しないものを非表示にしたりできます。アクティブなプロフィールは表示されたままです。</string>
|
||||
<string name="conn_info_move_profile_up">%1$s を上へ移動</string>
|
||||
@@ -2716,8 +2755,8 @@
|
||||
|
||||
<!-- ConnectionSwitcherSheet -->
|
||||
<string name="conn_switcher_title">スイッチ接続</string>
|
||||
<string name="conn_switcher_empty">まだ接続がありません</string>
|
||||
<string name="conn_switcher_manage">接続の管理…</string>
|
||||
<string name="conn_switcher_empty">ゲートウェイはまだありません</string>
|
||||
<string name="conn_switcher_manage">ゲートウェイを管理…</string>
|
||||
|
||||
<!-- DiagnosticsLogPanel -->
|
||||
<string name="diagnostics_title">最近の活動</string>
|
||||
@@ -3107,7 +3146,7 @@
|
||||
<string name="screen_bridge_label">Bridge</string>
|
||||
<string name="screen_manage_label">管理</string>
|
||||
<string name="screen_settings_label">設定</string>
|
||||
<string name="screen_connections_label">接続</string>
|
||||
<string name="screen_connections_label">ゲートウェイ</string>
|
||||
<string name="screen_connection_label">繋がり</string>
|
||||
<string name="screen_voice_label">声</string>
|
||||
<string name="screen_notification_companion_label">通知コンパニオン</string>
|
||||
@@ -3193,7 +3232,7 @@
|
||||
<string name="cw_hint_chat">チャット</string>
|
||||
<string name="cw_hint_manage">管理</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s は http:// または https:// を期待します (裸のホストは http://) を取得します)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s には http:// または https:// が必要です(プライベートホストは http://、公開ホストは https:// を使用します)</string>
|
||||
<string name="cw_label_api_key">API キー</string>
|
||||
<string name="cw_label_api_server">API サーバー</string>
|
||||
<string name="cw_label_dashboard">ダッシュボード</string>
|
||||
@@ -3246,7 +3285,7 @@
|
||||
<string name="cw_step_3_3">ステップ 3/3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Tailscale ネットワークが検出されました</string>
|
||||
<string name="cw_tailscale_supporting_other">サーバー ネットワークから離れている場合は、タイムアウト、アドレス、API ポート (8642) および http:// のデフォルトを手動で切り替えます。設定 → 接続 → ルートで変更できます。</string>
|
||||
<string name="cw_tailscale_supporting_other">サーバーネットワークから離れている場合は、[設定] → [ゲートウェイ] → [ルート] でタイムアウト、アドレス、API ポート (8642)、http:// のデフォルトを変更できます。</string>
|
||||
<string name="cw_value_derived">自動検出</string>
|
||||
<string name="cw_value_included">付属</string>
|
||||
<string name="cw_value_not_included">含まれていない</string>
|
||||
@@ -3439,6 +3478,7 @@
|
||||
<string name="card_send_answer_a11y">回答を送信する</string>
|
||||
<string name="card_submit">提出する</string>
|
||||
<string name="card_answer_placeholder">答えを入力してください…</string>
|
||||
<string name="card_other_answer_placeholder">その他(自由回答を入力)…</string>
|
||||
<string name="session_ttl_title">このペアリングをしばらく保持してください…</string>
|
||||
<string name="session_ttl_intro">この期間中に電話は自動的に再接続します。ペアリングはいつでも取り消すことができます。</string>
|
||||
<string name="session_ttl_stays_paired">このデバイスは、取り消すまでペアリングされたままになります。</string>
|
||||
@@ -3537,7 +3577,7 @@
|
||||
<string name="active_section_where_api_key">このキーはどこで入手しますか?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY は Hermes サーバー上で作成します。このアプリからは発行されません。任意の API サーバーを有効にする場合のみ設定します。このサーバーには使用可能なキーが必要です。同じ値をここに入力してください。</string>
|
||||
<string name="active_section_scan_relay_qr">Relay QR をスキャン</string>
|
||||
<string name="active_section_other_relay_methods">その他のペアリング方法</string>
|
||||
<string name="active_section_direct_relay_endpoint">Relay の直接エンドポイント</string>
|
||||
<string name="endpoints_tailscale_setup_hint">両方のデバイスで Tailscale に接続し、Hermes Dashboard がポート 9119 で到達可能である必要があります。</string>
|
||||
<string name="endpoints_setup_help">Tailscale セットアップヘルプ</string>
|
||||
<string name="voice_settings_provider_desc">音声を生成する場所です。利用可能な選択肢は、この Hermes ホストとインストール済みプロバイダーから取得されます。</string>
|
||||
@@ -3562,7 +3602,8 @@
|
||||
<string name="dev_settings_image_generation_lab">画像生成ラボ</string>
|
||||
<string name="dev_settings_image_generation_lab_desc">生成ループと最終画像の表示をプレビューします</string>
|
||||
<string name="dev_settings_open_image_generation_lab_cd">画像生成ラボを開く</string>
|
||||
<string name="dashboard_native_signin_opening">ブラウザでサインインを完了してから、ここに戻ってください。</string>
|
||||
<string name="dashboard_native_signin_opening">ブラウザでサインインを完了してください。プロバイダーから戻らない場合は、ここに戻って「サインインを続ける」をタップします。</string>
|
||||
<string name="dashboard_native_signin_continue">サインインを続ける</string>
|
||||
<string name="dashboard_native_signin_cancelled">ブラウザでのサインインをキャンセルしました。</string>
|
||||
<string name="dashboard_native_signin_requires_https">安全なブラウザサインインには、HTTPSのダッシュボードアドレスが必要です。</string>
|
||||
<string name="dashboard_native_signin_unavailable">この接続では安全なブラウザサインインを利用できません。接続を更新して、もう一度お試しください。</string>
|
||||
@@ -4019,6 +4060,9 @@
|
||||
<string name="plugins_remove">削除</string>
|
||||
<string name="plugins_remove_confirm">「%1$s」を削除しますか?接続された Android 端末にこのプラグインページは表示されなくなります。</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">ホストのリポジトリスキャン</string>
|
||||
<string name="git_state_host_scanning_on_desc">このゲートウェイでオン · Git への書き込みには別の権限が必要です。</string>
|
||||
<string name="git_state_host_scanning_off_desc">このスマートフォンからゲートウェイに、設定済みの Git ルート内のリポジトリ、ブランチ、変更状態をスキャンさせます。Git への書き込みには別の権限が必要です。</string>
|
||||
<string name="git_state_back">戻る</string>
|
||||
<string name="git_state_staged">ステージ済み</string>
|
||||
<string name="git_state_modified">変更</string>
|
||||
@@ -4062,7 +4106,7 @@
|
||||
<string name="git_state_switch_stash">切り替え(変更があればスタッシュ)</string>
|
||||
<string name="support_bundle_review">サポート情報を確認</string>
|
||||
<string name="support_bundle_title">サポート情報</string>
|
||||
<string name="support_bundle_privacy">自動アップロードはありません。最大 %1$d 件のレポートを含む端末内エクスポートを確認してください。</string>
|
||||
<string name="support_bundle_privacy">自動アップロードはありません。最近のレポートと診断 %1$d 件を含む端末内エクスポートを確認してください。</string>
|
||||
<string name="support_bundle_copied">サポート情報をコピーしました</string>
|
||||
<string name="support_bundle_no_share">サポート情報をコピーしました — 共有できるアプリがありません</string>
|
||||
<string name="support_bundle_share_title">Hermes-Relay サポート情報を共有</string>
|
||||
@@ -4425,7 +4469,7 @@
|
||||
<string name="custom_theme_modified">未保存の変更</string>
|
||||
<string name="custom_theme_saved_count">保存済み %1$d 件</string>
|
||||
<string name="chat_settings_show_git_workspace">チャットに Git ワークスペースを表示</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">入力欄の上にブランチと変更内容を表示します</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">ホストのリポジトリスキャンが有効な場合に、Chat に Git の状態と変更を表示します。これをオフにしても完全な Git ワークスペースは利用できます。</string>
|
||||
<string name="chat_git_open_workspace">Git ワークスペースを開く</string>
|
||||
<string name="chat_git_branch">ブランチ %1$s</string>
|
||||
<string name="chat_git_additions">%1$d 件の追加</string>
|
||||
@@ -4433,4 +4477,86 @@
|
||||
<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="current_chat_activity_title">現在のチャットのアクティビティ</string>
|
||||
<string name="current_chat_activity_subtitle">このチャットからの読み取り専用ライブ詳細</string>
|
||||
<string name="current_chat_activity_open">現在のチャットのアクティビティを表示</string>
|
||||
<string name="current_chat_activity_summary">エージェント %1$d · プロセス %2$d</string>
|
||||
<string name="current_chat_activity_close">アクティビティのプレビューを閉じる</string>
|
||||
<string name="current_chat_activity_empty">このチャットに現在のアクティビティはありません</string>
|
||||
<string name="current_chat_activity_latest">最新</string>
|
||||
<string name="agent_activity_section">エージェントのライブアクティビティ</string>
|
||||
<string name="agent_activity_disclosure">このチャットが受信した更新です。子エージェントの完全な履歴は利用できない場合があります。</string>
|
||||
<string name="agent_activity_fallback">エージェント %d</string>
|
||||
<string name="agent_activity_task_position">%2$d 件中 %1$d 件目 · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s、%2$s、%4$d 件中 %3$d 件目のエージェント</string>
|
||||
<string name="agent_activity_duration">%1$.1f秒</string>
|
||||
<string name="agent_activity_older_omitted">古いアクティビティは省略されました</string>
|
||||
<string name="agent_activity_partial">ライブ更新を再開しました。オフライン中のアクティビティが欠けている場合があります。</string>
|
||||
<string name="agent_activity_event_started">開始</string>
|
||||
<string name="agent_activity_event_update">更新</string>
|
||||
<string name="agent_activity_event_tool">ツールのプレビュー</string>
|
||||
<string name="agent_activity_status_started">開始中</string>
|
||||
<string name="agent_activity_status_thinking">思考中</string>
|
||||
<string name="agent_activity_status_tool">ツールを使用中</string>
|
||||
<string name="agent_activity_status_progress">作業中</string>
|
||||
<string name="agent_activity_status_completed">完了</string>
|
||||
<string name="agent_activity_status_failed">失敗</string>
|
||||
<string name="agent_activity_status_interrupted">中断</string>
|
||||
<string name="agent_activity_status_unavailable">最終状態を確認できません</string>
|
||||
<string name="agent_activity_child_loading">読み取り専用の子履歴を開いています…</string>
|
||||
<string name="agent_activity_child_unavailable">この Hermes のバージョンまたはルートでは子履歴を利用できません。親セッションのアクティビティは上に表示されます。</string>
|
||||
<string name="agent_activity_child_live">子履歴 · ライブ更新</string>
|
||||
<string name="agent_activity_child_history">子履歴 · 読み取り専用</string>
|
||||
<string name="agent_activity_child_truncated">最近の子アクティビティを表示 · 古い詳細または大きすぎる詳細は省略されました</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Hermes Gateway のアドレスを入力してください</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">認証済み Dashboard アドレス</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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_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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">選択したルートを使用</string>
|
||||
<string name="active_section_use_selected_route_failed">Dashboard のサインインを選択したルートに戻せませんでした。</string>
|
||||
<string name="active_section_forget_sign_in_origin">サインイン元を削除</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<string name="agent_interface">интерфейс агента</string>
|
||||
<string name="notification_companion_label">Hermes-Relay уведомление-компаньон</string>
|
||||
<string name="onboarding_skip_setup_title">Пропустить настройку?</string>
|
||||
<string name="onboarding_skip_setup_text">Не проблема — вы можете изучить демонстрацию, чтобы увидеть, как работает Hermes-Relay, и подключить свой собственный сервер Гермес в любое время из Настройки → Подключения. Парное соединение Relay для продвинутых инструментов может быть добавлено позже.</string>
|
||||
<string name="onboarding_skip_setup_text">Без проблем — изучите демоверсию, а затем в любое время добавьте свой шлюз Hermes в разделе Настройки → Шлюзы. Сопряжение Relay для расширенных инструментов можно добавить позже.</string>
|
||||
<string name="onboarding_skip_for_now">Пропустить на время</string>
|
||||
<string name="onboarding_go_back">Вернуться</string>
|
||||
<string name="onboarding_skip">Пропустить</string>
|
||||
@@ -144,7 +144,7 @@
|
||||
<string name="chat_editing_notice">Редактирование — перемотает беседу</string>
|
||||
<string name="chat_mic_perm_needed">Требуется разрешение на микрофон</string>
|
||||
<string name="chat_mic_perm_body">Нажмите Открыть настройки и предоставьте доступ к микрофону для использования голосового режима.</string>
|
||||
<string name="chat_manage_connections">Управление подключениями</string>
|
||||
<string name="chat_manage_connections">Управление шлюзами</string>
|
||||
<string name="chat_no_clipboard_image">Нет изображения в буфере обмена</string>
|
||||
<string name="chat_copied_to_clipboard">Скопировано в буфер обмена</string>
|
||||
<string name="chat_camera_open_failed">Не удалось открыть камеру</string>
|
||||
@@ -201,7 +201,7 @@
|
||||
<string name="dashboard_component_connected">подключено</string>
|
||||
<string name="dashboard_component_server_errors_5m">ошибки сервера / 5 мин</string>
|
||||
<string name="conn_label_connect">Подключить</string>
|
||||
<string name="conn_label_connections">Подключения</string>
|
||||
<string name="conn_label_connections">Шлюзы</string>
|
||||
<string name="conn_detail_add_connection">Добавить соединение с API/панелью управления Vanilla Гермеса</string>
|
||||
<string name="conn_detail_waiting_network">Ожидание отчета Android о маршруте в интернет</string>
|
||||
<string name="conn_detail_chat_unavailable">Чат и вызовы профиля могут быть недоступны</string>
|
||||
@@ -280,19 +280,19 @@
|
||||
<string name="error_classify_repair">Переподключить</string>
|
||||
<string name="error_classify_retry">Повторить</string>
|
||||
<string name="error_classify_open_settings">Открыть настройки</string>
|
||||
<string name="cw_connect_to_hermes">Подключение к Гермесу</string>
|
||||
<string name="cw_connect_to_hermes">Добавить шлюз</string>
|
||||
<string name="cw_nearby_description">Мы будем искать Гермеса в этой сети. Панель управления и шлюз обеспечивают стандартное подключение для чата, управления и голоса.</string>
|
||||
<string name="cw_connection_chooser_description">Выберите доступный способ настройки. Hermes Relay необязателен.</string>
|
||||
<string name="cw_connection_chooser_description">Один шлюз — это одна установка Hermes. Выберите, как телефону подключаться к ней.</string>
|
||||
<string name="cw_scan_setup_qr_title">Сканировать QR-код настройки Hermes</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">Настройте локальные, удалённые и доступные маршруты Relay</string>
|
||||
<string name="cw_recommended">Рекомендуется</string>
|
||||
<string name="cw_other_ways_to_connect">Другие способы подключения</string>
|
||||
<string name="cw_other_ways_to_connect">Выберите шлюз</string>
|
||||
<string name="cw_advanced">Расширенные настройки</string>
|
||||
<string name="cw_cloud_title">Hermes на хостинге Nous</string>
|
||||
<string name="cw_cloud_subtitle">Подключитесь к своему размещённому агенту</string>
|
||||
<string name="cw_server_vps_title">Сервер или VPS</string>
|
||||
<string name="cw_server_vps_subtitle">Введите защищённый адрес Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Стандартные чат, управление и голос работают без Relay. Совместимые QR-коды настройки добавляют расширенные функции Relay, когда они доступны.</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_cloud_entry_title">Подключиться к Hermes на хостинге Nous</string>
|
||||
<string name="cw_cloud_entry_description">Введите адрес агента, указанный в Nous Portal. После обнаружения Hermes вы безопасно войдёте в систему.</string>
|
||||
<string name="cw_cloud_agent_name">Адрес агента</string>
|
||||
@@ -326,7 +326,7 @@
|
||||
<string name="cw_relay_pair_qr">Соединить плагин Гермес Relay</string>
|
||||
<string name="cw_relay_pair_qr_desc">Просканируйте QR-код настройки Relay</string>
|
||||
<string name="cw_relay_enter_code">Введите код сопоставления Relay</string>
|
||||
<string name="cw_manual_hermes_title">Введите адрес вашего Гермеса</string>
|
||||
<string name="cw_manual_hermes_title">Введите адрес шлюза</string>
|
||||
<string name="cw_manual_hermes_description">Введите адрес панели управления, который вы открываете в браузере. Если он не открывается на этом телефоне, запустите панель управления Гермесом и проверьте Wi-Fi или Tailscale.</string>
|
||||
<string name="cw_hermes_address">Адрес Гермеса</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 или hermes.example.com</string>
|
||||
@@ -425,6 +425,13 @@
|
||||
<string name="cw_pairing_code_label">Код сопряжения</string>
|
||||
<string name="cw_pairing_code_placeholder">например, ABC123</string>
|
||||
<string name="cw_pair_button">Сопрячь</string>
|
||||
<string name="cw_mixed_route_plain">%1$s использует незашифрованный HTTP/WS. Используйте только в доверенной частной сети или через управляемую вами VPN.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s использует HTTPS/WSS с шифрованием транспорта.</string>
|
||||
<string name="cw_mixed_safe">Приложение проверяет эти маршруты и выбирает доступный. Предпочтительный маршрут можно изменить позже.</string>
|
||||
<string name="cw_pair_in_progress">Выполняется…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">Подготовка шлюза…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">Открытие безопасного входа…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Сопряжение Relay…</string>
|
||||
<string name="cw_show_code_subtitle">Используйте это, когда не можете отсканировать QR-код сопряжения Relay. Установите свои URL-адреса, затем зарегистрируйте код ниже на хосте, работающем с Hermes-Relay.</string>
|
||||
<string name="cw_step_copy_code">1. Скопируйте этот код</string>
|
||||
<string name="cw_copy_pairing_code">Скопировать код сопряжения</string>
|
||||
@@ -443,9 +450,6 @@
|
||||
<string name="cw_insecure_relay_warning">Этот Relay использует обычный ws:// — трафик не зашифрован.</string>
|
||||
<string name="cw_insecure_relay_trust">Продолжайте только если вы доверяете сети на любом подключении (LAN, Tailscale, VPN).</string>
|
||||
<string name="cw_insecure_ack">Я понимаю, что это сопряжение отправляет трафик в открытом виде — видимый для любого в сети.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s — это обычный ws:// — подходит дома или в офисе, но не на общественном Wi-Fi.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s зашифрован (wss://), и приложение использует его автоматически, когда %2$s недоступен.</string>
|
||||
<string name="cw_mixed_safe">Вы в безопасности на любой сети.</string>
|
||||
<string name="cw_connecting_to_hermes">Подключение к Гермесу</string>
|
||||
<string name="cw_connecting_detail">Проверка сервера API, сохраненного ключа и панели управления.</string>
|
||||
<string name="cw_pairing_title">Сопряжение…</string>
|
||||
@@ -471,7 +475,7 @@
|
||||
<string name="cw_voice_after_connect">Проверено после подключения</string>
|
||||
<string name="cw_remote">Удалённый</string>
|
||||
<string name="cw_remote_fallback_ready">Резервный маршрут готов к использованию вне дома</string>
|
||||
<string name="cw_remote_lan_only">Только LAN — добавьте маршрут Tailscale или публичный в настройках → Подключения → Маршруты</string>
|
||||
<string name="cw_remote_lan_only">Только LAN — добавьте маршрут Tailscale или публичный маршрут в Настройки → Шлюзы → Маршруты</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">Инструменты подключены</string>
|
||||
<string name="cw_relay_optional">Необязательно для Терминала и Моста</string>
|
||||
@@ -489,6 +493,17 @@
|
||||
<string name="endpoints_preferred">Предпочтительный</string>
|
||||
<string name="endpoints_automatic">Автоматический</string>
|
||||
<string name="endpoints_current_route">Текущий маршрут: %1$s (%2$s)</string>
|
||||
<string name="endpoints_no_active_fallback">Резервный маршрут сейчас не выбран.</string>
|
||||
<string name="endpoints_selection_reason">Приоритет %1$d (0 — наивысший) · %2$s</string>
|
||||
<string name="endpoints_reachable_now">Доступен сейчас</string>
|
||||
<string name="endpoints_last_check_failed">Последняя проверка завершилась ошибкой</string>
|
||||
<string name="endpoints_reachability_not_checked">Доступность не проверена</string>
|
||||
<string name="endpoints_security_application_tls">TLS на уровне приложения</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Зашифровано через Tailscale · без TLS на уровне приложения</string>
|
||||
<string name="endpoints_security_wireguard_overlay">Зашифровано через WireGuard · без TLS на уровне приложения</string>
|
||||
<string name="endpoints_security_secure_link">Зашифровано через Hermes Secure Link</string>
|
||||
<string name="endpoints_security_private_plain">Частная сеть · без TLS на уровне приложения</string>
|
||||
<string name="endpoints_security_public_plain">Публичный маршрут не зашифрован</string>
|
||||
<string name="endpoints_cancel_manual_switch">Отменить ручной переключатель — вернуться к %1$s</string>
|
||||
<string name="endpoints_stop_preferring">Остановить предпочтение — вернуться к автоматическому</string>
|
||||
<string name="endpoints_checking">Проверка…</string>
|
||||
@@ -650,7 +665,7 @@
|
||||
<string name="relay_state_needs_repair">Требуется повторное сопряжение</string>
|
||||
<string name="settings_no_connection">Нет соединения</string>
|
||||
<string name="settings_server_default">Сервер по умолчанию</string>
|
||||
<string name="settings_connections">Подключения</string>
|
||||
<string name="settings_connections">Шлюзы</string>
|
||||
<string name="settings_connections_desc">API, панель управления, сопряжение Relay и маршруты</string>
|
||||
<string name="settings_hermes">Гермес</string>
|
||||
<string name="settings_hermes_management">Управление Гермесом</string>
|
||||
@@ -788,14 +803,31 @@
|
||||
<string name="chat_settings_8k">8К</string>
|
||||
<string name="chat_settings_16k">16К</string>
|
||||
<string name="chat_settings_gateway_needs_signin">Шлюзу требуется вход в систему Manage</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Войдите один раз из вкладки Manage, чтобы разблокировать живое мышление через /api/ws.</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Войдите один раз, чтобы открыть чат, сессии, управление и стандартный голос для этого подключения Hermes.</string>
|
||||
<string name="chat_settings_completions">Завершения</string>
|
||||
<string name="chat_settings_offline">офлайн</string>
|
||||
<string name="conn_back">Назад</string>
|
||||
<string name="conn_title">Подключения</string>
|
||||
<string name="conn_add_connection">Добавить подключение</string>
|
||||
<string name="conn_no_connections">Еще нет подключений</string>
|
||||
<string name="conn_no_connections_desc">Нажмите Добавить подключение, чтобы подключиться к Гермесу.</string>
|
||||
<string name="conn_title">Шлюзы</string>
|
||||
<string name="conn_add_connection">Добавить шлюз</string>
|
||||
<string name="conn_no_connections">Шлюзов пока нет</string>
|
||||
<string name="conn_no_connections_desc">Нажмите «Добавить шлюз», чтобы подключиться к Hermes.</string>
|
||||
<string name="gateways_title">Шлюзы</string>
|
||||
<plurals name="gateway_count"><item quantity="one">%d шлюз</item><item quantity="few">%d шлюза</item><item quantity="many">%d шлюзов</item><item quantity="other">%d шлюза</item></plurals>
|
||||
<string name="gateway_add">Добавить шлюз</string>
|
||||
<string name="gateways_empty_title">Шлюзов пока нет</string>
|
||||
<string name="gateways_empty_body">Добавьте шлюз, чтобы подключить телефон к Hermes.</string>
|
||||
<string name="gateway_route_not_configured">Маршрут не настроен</string>
|
||||
<string name="gateway_status_online">Шлюз в сети</string>
|
||||
<string name="gateway_status_sign_in_required">Требуется вход</string>
|
||||
<string name="gateway_status_offline">Шлюз не в сети</string>
|
||||
<string name="gateway_status_checking">Проверка шлюза…</string>
|
||||
<string name="gateway_status_not_checked">Шлюз не проверен</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">Последняя проверка: требуется вход</string>
|
||||
<string name="gateway_status_last_check_succeeded">Последняя проверка успешна</string>
|
||||
<string name="gateway_status_last_check_failed">Последняя проверка не удалась</string>
|
||||
<string name="gateway_status_no_route">Нет маршрута шлюза</string>
|
||||
<string name="gateway_status_unavailable">Шлюз недоступен</string>
|
||||
<string name="conn_add_requires_parent_access">Разблокируйте родительский доступ, прежде чем добавлять шлюз.</string>
|
||||
<string name="conn_active">Активный</string>
|
||||
<string name="conn_connected">Подключен</string>
|
||||
<string name="conn_standard_not_paired">Стандартный · плагин Relay не сопряжен</string>
|
||||
@@ -862,6 +894,8 @@
|
||||
<string name="detail_tab_routes">Маршруты</string>
|
||||
<string name="detail_tab_advanced">Дополнительно</string>
|
||||
<string name="detail_tab_security">Безопасность</string>
|
||||
<string name="detail_tab_access">Доступ</string>
|
||||
<string name="detail_current_route">Текущий маршрут</string>
|
||||
<string name="conn_startup_title">При запуске приложения</string>
|
||||
<string name="conn_startup_last_used">Последнее использование</string>
|
||||
<string name="conn_startup_recommended">Рекомендуется</string>
|
||||
@@ -913,7 +947,7 @@
|
||||
<string name="active_section_relay_optional_bridge">Дополнительные функции моста и удаленный доступ</string>
|
||||
<string name="active_section_configure_relay">Настроить плагин Relay</string>
|
||||
<string name="active_section_scan_relay_qr">Сканировать QR-код Relay</string>
|
||||
<string name="active_section_other_relay_methods">Другие методы сопряжения</string>
|
||||
<string name="active_section_direct_relay_endpoint">Прямой адрес Relay</string>
|
||||
<string name="active_section_pair_device_using_code">Сопрячьте это устройство с помощью кода с сервера.</string>
|
||||
<string name="active_section_enter_pairing_code">Введите код сопряжения</string>
|
||||
<string name="active_section_done">Готово</string>
|
||||
@@ -992,6 +1026,8 @@
|
||||
<string name="drawer_delete_session_title">Удалить сессию?</string>
|
||||
<string name="drawer_delete_session_prefix">Это навсегда удалит "</string>
|
||||
<string name="drawer_delete_session_suffix">" и историю сообщений.</string>
|
||||
<string name="drawer_remove_provisional_thread_title">Удалить поток?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">Это удалит «%1$s» с этого устройства. Повышенная или серверная история не будет удалена.</string>
|
||||
<string name="drawer_untitled">Без названия</string>
|
||||
<string name="drawer_delete">Удалить</string>
|
||||
<string name="drawer_thread">Ветка</string>
|
||||
@@ -1020,7 +1056,7 @@
|
||||
<string name="bridge_relay_label">Relay</string>
|
||||
<string name="bridge_safety_label">безопасность</string>
|
||||
<string name="bridge_not_connected_title">плагин Relay не подключен</string>
|
||||
<string name="bridge_not_connected_body">Команды моста передаются через Relay. Сопрягите Relay в Настройки → Подключения, чтобы мост мог выполнять действия.</string>
|
||||
<string name="bridge_not_connected_body">Команды моста передаются через Relay. Сопрягите Relay в разделе Настройки → Шлюзы, чтобы использовать мост.</string>
|
||||
<string name="bridge_accessibility_needed">Сначала необходимо включить Службу доступности.</string>
|
||||
<string name="bridge_open_settings">Открыть настройки</string>
|
||||
<string name="bridge_allow_agent_control">Разрешить управление агентом</string>
|
||||
@@ -1055,8 +1091,8 @@
|
||||
<string name="bridge_core_relay_body">Ядро моста использует ту же сопряженную сессию Relay, что и терминал, уведомления, медиа и голосовые функции.</string>
|
||||
<string name="bridge_core_surface_title">Поверхность моста</string>
|
||||
<string name="bridge_core_surface_meta">не скрыто в настройках</string>
|
||||
<string name="bridge_core_connections">Подключения</string>
|
||||
<string name="bridge_core_connections_sub">Сопряжение, переключение и проверка маршрутов Relay</string>
|
||||
<string name="bridge_core_connections">Шлюзы</string>
|
||||
<string name="bridge_core_connections_sub">Сопряжение Relay, переключение шлюзов и проверка маршрутов</string>
|
||||
<string name="bridge_core_terminal_tile">Терминал</string>
|
||||
<string name="bridge_core_terminal_sub">Подключитесь к терминалу Relay вашего Гермеса</string>
|
||||
<string name="bridge_core_voice">Голос</string>
|
||||
@@ -1405,7 +1441,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Позволить Гермесу отправлять мне сообщения</string>
|
||||
<string name="proactive_allow_proactive_messages">Разрешить проактивные сообщения</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">Ваш агент может связаться с вами самостоятельно — напоминания, выполненные задачи, предупреждения. Его сообщения отображаются как потоки в чате, где вы можете ответить.</string>
|
||||
<string name="proactive_not_paired_warning">Еще не сопряжено — сопрягите с вашим сервером Гермеса в настройках → Подключения, чтобы начать получать сообщения.</string>
|
||||
<string name="proactive_not_paired_warning">Еще не сопряжено — сопрягите Relay в разделе Настройки → Шлюзы, чтобы начать получать сообщения.</string>
|
||||
<string name="proactive_your_threads">Ваши потоки</string>
|
||||
<string name="proactive_your_threads_desc">Каждая беседа, начатая вашим агентом, отображается как поток в чате — откройте список сессий, отфильтруйте потоки и отвечайте прямо там.</string>
|
||||
<string name="proactive_open_chat">Открыть чат</string>
|
||||
@@ -1583,7 +1619,7 @@
|
||||
<string name="voice_settings_engine_realtime">Агент в реальном времени</string>
|
||||
<string name="voice_settings_engine_realtime_desc">Живая сессия поставщика обрабатывает прослушивание и речь с собственной голосовой моделью и голосом. Гермес по-прежнему обрабатывает инструменты, память и подтверждения. Требуется сопряженный плагин Relay.</string>
|
||||
<string name="voice_settings_experimental">Экспериментальный</string>
|
||||
<string name="voice_settings_realtime_no_relay">плагин Relay не настроен для этого подключения, поэтому агент в реальном времени не может запуститься. Сопряжите плагин Relay в настройках → Подключения или переключитесь обратно на чат Гермес + голосовой вывод.</string>
|
||||
<string name="voice_settings_realtime_no_relay">Relay не настроен для этого шлюза, поэтому агент в реальном времени не может запуститься. Сопрягите Relay в разделе Настройки → Шлюзы или вернитесь к чату Hermes + голосовому выводу.</string>
|
||||
<string name="voice_settings_route_label">Маршрут STT/TTS</string>
|
||||
<string name="voice_settings_status_ready">Готово</string>
|
||||
<string name="voice_settings_status_sign_in_required">Требуется вход в панель управления</string>
|
||||
@@ -1849,8 +1885,8 @@
|
||||
<string name="dashboard_tile_keys_sub">Ключи поставщика + секреты среды</string>
|
||||
<string name="dashboard_tile_config_title">Конфигурация</string>
|
||||
<string name="dashboard_tile_config_sub">Схема и параметры выполнения</string>
|
||||
<string name="dashboard_nav_connections_title">Подключения</string>
|
||||
<string name="dashboard_nav_connections_sub">Сопоставление, переключение, проверка маршрутов</string>
|
||||
<string name="dashboard_nav_connections_title">Шлюзы</string>
|
||||
<string name="dashboard_nav_connections_sub">Вход, сопряжение Relay, переключение и проверка маршрутов</string>
|
||||
<string name="dashboard_hub_title">Relay Hub</string>
|
||||
<string name="dashboard_hub_meta">обзор</string>
|
||||
<string name="dashboard_health_loading">…</string>
|
||||
@@ -1874,7 +1910,7 @@
|
||||
<string name="dashboard_minutes_ago">%1$dm назад</string>
|
||||
<string name="dashboard_hours_ago">%1$dh назад</string>
|
||||
<string name="dashboard_signin_required_title">Требуется вход в панель управления</string>
|
||||
<string name="dashboard_signin_required_body">Manage использует сеанс панели управления Гермесом по адресу %1$s.</string>
|
||||
<string name="dashboard_signin_required_body">Войдите в Hermes по адресу %1$s для чата, сеансов, управления и стандартного голоса.</string>
|
||||
<string name="dashboard_signin_route_hint">Сохраненный сеанс панели управления не может быть повторно использован на маршруте %1$s. Войдите снова, чтобы обновить его на всех доверенных маршрутах этого подключения.</string>
|
||||
<string name="dashboard_signin_with_provider">Войти с помощью %1$s</string>
|
||||
<string name="dashboard_username_password">Имя пользователя и пароль</string>
|
||||
@@ -1883,11 +1919,13 @@
|
||||
<string name="dashboard_sign_in">Войти</string>
|
||||
<string name="dashboard_signing_in">Вход…</string>
|
||||
<string name="dashboard_no_supported_provider">Эта панель управления не рекламирует поддерживаемого поставщика входа для Android.</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">Сохранённый поставщик входа недоступен. Выберите другого настроенного поставщика или повторите попытку позже.</string>
|
||||
<string name="dashboard_oauth_initial_status">Завершите вход на защищенной странице панели управления.</string>
|
||||
<string name="dashboard_oauth_verifying">Проверка сеанса панели управления…</string>
|
||||
<string name="dashboard_oauth_not_accepted">Вход еще не принят. Завершите процесс панели управления, чтобы продолжить.</string>
|
||||
<string name="dashboard_oauth_verify_failed">Проверка входа в панель управления не удалась</string>
|
||||
<string name="dashboard_native_signin_opening">Завершите вход в браузере, затем вернитесь сюда.</string>
|
||||
<string name="dashboard_native_signin_opening">Завершите вход в браузере. Если провайдер не вернул вас, вернитесь сюда и нажмите «Продолжить вход».</string>
|
||||
<string name="dashboard_native_signin_continue">Продолжить вход</string>
|
||||
<string name="dashboard_native_signin_cancelled">Вход в браузере отменен.</string>
|
||||
<string name="dashboard_native_signin_requires_https">Безопасный вход в браузере требует HTTPS-адреса панели управления.</string>
|
||||
<string name="dashboard_native_signin_unavailable">Безопасный вход в браузере недоступен для этого подключения. Обновите подключение и попробуйте снова.</string>
|
||||
@@ -2301,6 +2339,8 @@
|
||||
<string name="active_section_no_response_from_relay">Нет ответа от Relay</string>
|
||||
<string name="active_section_no_route_reachable">Нет доступных маршрутов</string>
|
||||
<string name="active_section_no_routes_answered_probe">Маршруты не ответили на запрос</string>
|
||||
<string name="active_section_no_reachable_route_title">Нет доступного маршрута Gateway</string>
|
||||
<string name="active_section_no_reachable_route_body">Ни один из настроенных маршрутов Gateway не ответил. Включите Tailscale, Wi-Fi или мобильную передачу данных и повторите проверку. Разверните маршрут ниже, чтобы увидеть результаты Dashboard, API и Relay.</string>
|
||||
<string name="active_section_not_advertised">Не объявлено</string>
|
||||
<string name="active_section_not_checked">Не проверено</string>
|
||||
<string name="active_section_not_configured">Не настроено</string>
|
||||
@@ -2432,7 +2472,7 @@
|
||||
<string name="conn_info_loading_profiles">Загрузка профилей…</string>
|
||||
<string name="conn_info_local_display_name">Локальное отображаемое имя</string>
|
||||
<string name="conn_info_locked_to">Заблокировано на %1$s</string>
|
||||
<string name="conn_info_manage_connections">Управление подключениями</string>
|
||||
<string name="conn_info_manage_connections">Управление шлюзами</string>
|
||||
<string name="conn_info_manage_profiles">Управление отображением профилей</string>
|
||||
<string name="conn_info_manage_profiles_hint">Измените порядок профилей или скройте те, которые не используете. Активный профиль останется видимым.</string>
|
||||
<string name="conn_info_move_profile_up">Переместить %1$s вверх</string>
|
||||
@@ -2691,8 +2731,8 @@
|
||||
<string name="conn_security_empty">Нет активного маршрута. Подключитесь к серверу, чтобы узнать, как защищена каждая часть подключения.</string>
|
||||
<string name="conn_security_learn_more">Узнать о безопасности подключения \&#8594;</string>
|
||||
<string name="conn_switcher_title">Переключить подключение</string>
|
||||
<string name="conn_switcher_empty">Нет подключений</string>
|
||||
<string name="conn_switcher_manage">Управление подключениями\&#8230;</string>
|
||||
<string name="conn_switcher_empty">Шлюзов пока нет</string>
|
||||
<string name="conn_switcher_manage">Управление шлюзами\&#8230;</string>
|
||||
<string name="diagnostics_title">Недавняя активность</string>
|
||||
<string name="diagnostics_clear">Очистить</string>
|
||||
<string name="diagnostics_all">Все</string>
|
||||
@@ -2989,7 +3029,7 @@
|
||||
<string name="screen_bridge_label">Мост</string>
|
||||
<string name="screen_manage_label">Управление</string>
|
||||
<string name="screen_settings_label">Настройки</string>
|
||||
<string name="screen_connections_label">Подключения</string>
|
||||
<string name="screen_connections_label">Шлюзы</string>
|
||||
<string name="screen_connection_label">Подключение</string>
|
||||
<string name="screen_voice_label">Голос</string>
|
||||
<string name="screen_notification_companion_label">Уведомления</string>
|
||||
@@ -3066,7 +3106,7 @@
|
||||
<string name="cw_hint_chat">Чат</string>
|
||||
<string name="cw_hint_manage">Управление</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s ожидает http:// или https:// (голые хосты получают http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s ожидает http:// или https:// (частные хосты используют http://, публичные — https://)</string>
|
||||
<string name="cw_label_api_key">Ключ API</string>
|
||||
<string name="cw_label_api_server">Сервер API</string>
|
||||
<string name="cw_label_dashboard">Панель управления</string>
|
||||
@@ -3103,7 +3143,7 @@
|
||||
<string name="cw_step_3_3">Шаг 3 из 3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Обнаружена сеть Tailscale</string>
|
||||
<string name="cw_tailscale_supporting_other">При отсутствии сети сервера вручную измените тайм-аут, адрес, порт API (8642) и настройки по умолчанию http:// в разделе Настройки → Подключения → Маршруты.</string>
|
||||
<string name="cw_tailscale_supporting_other">Вне сети сервера изменяйте тайм-аут, адрес, порт API (8642) и значения http:// в разделе Настройки → Шлюзы → Маршруты.</string>
|
||||
<string name="cw_value_derived">Автоопределено</string>
|
||||
<string name="cw_value_included">Включено</string>
|
||||
<string name="cw_value_not_included">Не включено</string>
|
||||
@@ -3298,6 +3338,7 @@
|
||||
<string name="card_send_answer_a11y">Отправить ответ</string>
|
||||
<string name="card_submit">Отправить</string>
|
||||
<string name="card_answer_placeholder">Введите ответ…</string>
|
||||
<string name="card_other_answer_placeholder">Другое (введите свой ответ)…</string>
|
||||
<string name="session_ttl_title">Сохранить это сопряжение на…</string>
|
||||
<string name="session_ttl_intro">Ваш телефон будет автоматически переподключаться в течение этого периода. Вы можете отозвать сопряжение в любой момент.</string>
|
||||
<string name="session_ttl_stays_paired">Это устройство останется сопряженным, пока вы не отзовёте его.</string>
|
||||
@@ -3753,6 +3794,9 @@
|
||||
<string name="plugins_remove">Удалить</string>
|
||||
<string name="plugins_remove_confirm">Удалить «%1$s»? Эта страница плагина больше не будет отображаться на подключённых устройствах Android.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">Сканирование репозиториев на хосте</string>
|
||||
<string name="git_state_host_scanning_on_desc">Включено для этого шлюза · Для записи Git по-прежнему нужно отдельное разрешение.</string>
|
||||
<string name="git_state_host_scanning_off_desc">Разрешает телефону запрашивать у этого шлюза сканирование настроенных корней Git для поиска репозиториев, веток и изменений. Для записи Git нужно отдельное разрешение.</string>
|
||||
<string name="git_state_back">Назад</string>
|
||||
<string name="git_state_staged">В индексе</string>
|
||||
<string name="git_state_modified">Изменённые</string>
|
||||
@@ -3796,7 +3840,7 @@
|
||||
<string name="git_state_switch_stash">Переключить (сохранить изменения, если есть)</string>
|
||||
<string name="support_bundle_review">Проверить сведения для поддержки</string>
|
||||
<string name="support_bundle_title">Сведения для поддержки</string>
|
||||
<string name="support_bundle_privacy">Ничего не загружается автоматически. Проверьте локальный экспорт с не более чем %1$d отчётами.</string>
|
||||
<string name="support_bundle_privacy">Ничего не загружается автоматически. Проверьте локальный экспорт с %1$d недавними отчётами и записями диагностики.</string>
|
||||
<string name="support_bundle_copied">Сведения для поддержки скопированы</string>
|
||||
<string name="support_bundle_no_share">Сведения для поддержки скопированы — приложение для отправки не найдено</string>
|
||||
<string name="support_bundle_share_title">Поделиться сведениями поддержки Hermes-Relay</string>
|
||||
@@ -4166,7 +4210,7 @@
|
||||
<string name="custom_theme_modified">Несохраненные изменения</string>
|
||||
<string name="custom_theme_saved_count">Сохранено тем: %1$d</string>
|
||||
<string name="chat_settings_show_git_workspace">Показывать рабочую область Git в чате</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Показывает ветку и изменения над полем ввода</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Показывает состояние Git и изменения в чате, когда сканирование репозиториев на хосте включено. Полная рабочая область Git остаётся доступной, когда этот параметр выключен.</string>
|
||||
<string name="chat_git_open_workspace">Открыть рабочую область Git</string>
|
||||
<string name="chat_git_branch">Ветка %1$s</string>
|
||||
<string name="chat_git_additions">Добавлено строк: %1$d</string>
|
||||
@@ -4174,4 +4218,86 @@
|
||||
<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="current_chat_activity_title">Текущая активность чата</string>
|
||||
<string name="current_chat_activity_subtitle">Доступные только для чтения сведения в реальном времени из этого чата</string>
|
||||
<string name="current_chat_activity_open">Просмотреть текущую активность чата</string>
|
||||
<string name="current_chat_activity_summary">Агенты: %1$d · процессы: %2$d</string>
|
||||
<string name="current_chat_activity_close">Закрыть просмотр активности</string>
|
||||
<string name="current_chat_activity_empty">В этом чате сейчас нет активности</string>
|
||||
<string name="current_chat_activity_latest">Последнее</string>
|
||||
<string name="agent_activity_section">Активность агентов в реальном времени</string>
|
||||
<string name="agent_activity_disclosure">Обновления, полученные этим чатом. Полная история дочернего агента может быть недоступна.</string>
|
||||
<string name="agent_activity_fallback">Агент %d</string>
|
||||
<string name="agent_activity_task_position">%1$d из %2$d · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s, %2$s, агент %3$d из %4$d</string>
|
||||
<string name="agent_activity_duration">%1$.1f с</string>
|
||||
<string name="agent_activity_older_omitted">Более ранняя активность опущена</string>
|
||||
<string name="agent_activity_partial">Обновления возобновлены. Активность во время отсутствия подключения может быть пропущена.</string>
|
||||
<string name="agent_activity_event_started">Запущено</string>
|
||||
<string name="agent_activity_event_update">Обновление</string>
|
||||
<string name="agent_activity_event_tool">Предпросмотр инструмента</string>
|
||||
<string name="agent_activity_status_started">Запуск</string>
|
||||
<string name="agent_activity_status_thinking">Размышляет</string>
|
||||
<string name="agent_activity_status_tool">Использует инструмент</string>
|
||||
<string name="agent_activity_status_progress">Работает</string>
|
||||
<string name="agent_activity_status_completed">Завершено</string>
|
||||
<string name="agent_activity_status_failed">Ошибка</string>
|
||||
<string name="agent_activity_status_interrupted">Прервано</string>
|
||||
<string name="agent_activity_status_unavailable">Итоговое состояние недоступно</string>
|
||||
<string name="agent_activity_child_loading">Открывается дочерняя история только для чтения…</string>
|
||||
<string name="agent_activity_child_unavailable">Дочерняя история недоступна в этой версии или маршруте Hermes. Активность родительского сеанса показана выше.</string>
|
||||
<string name="agent_activity_child_live">Дочерняя история · обновления в реальном времени</string>
|
||||
<string name="agent_activity_child_history">Дочерняя история · только чтение</string>
|
||||
<string name="agent_activity_child_truncated">Показана недавняя дочерняя активность · более ранние или слишком большие сведения опущены</string>
|
||||
<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="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>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<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="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>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Введите адрес Hermes Gateway</string>
|
||||
<string name="dashboard_gateway_configured">Configured 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="dashboard_gateway_secure_origin">Адрес аутентифицированной панели</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<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_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>
|
||||
<string name="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">Использовать выбранный маршрут</string>
|
||||
<string name="active_section_use_selected_route_failed">Не удалось вернуть вход в Dashboard к выбранному маршруту.</string>
|
||||
<string name="active_section_forget_sign_in_origin">Забыть источник входа</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
</resources>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<string name="notification_companion_label">Hermes-Relay notification companion</string>
|
||||
|
||||
<string name="onboarding_skip_setup_title">Skip setup?</string>
|
||||
<string name="onboarding_skip_setup_text">No problem — you can explore the demo to see how Hermes-Relay works, and connect your own Hermes server anytime from Settings → Connections. Relay pairing for power tools can be added later too.</string>
|
||||
<string name="onboarding_skip_setup_text">No problem — you can explore the demo to see how Hermes-Relay works, and add your own Hermes Gateway anytime from Settings → Gateways. Relay pairing for power tools can be added later too.</string>
|
||||
<string name="onboarding_skip_for_now">Skip for now</string>
|
||||
<string name="onboarding_go_back">Go back</string>
|
||||
<string name="onboarding_skip">Skip</string>
|
||||
@@ -154,7 +154,7 @@
|
||||
<string name="chat_editing_notice">Editing — will rewind the conversation</string>
|
||||
<string name="chat_mic_perm_needed">Microphone permission needed</string>
|
||||
<string name="chat_mic_perm_body">Tap Open Settings and grant Microphone access to use voice mode.</string>
|
||||
<string name="chat_manage_connections">Manage connections</string>
|
||||
<string name="chat_manage_connections">Manage gateways</string>
|
||||
<string name="chat_no_clipboard_image">No image on the clipboard</string>
|
||||
<string name="chat_copied_to_clipboard">Copied to clipboard</string>
|
||||
<string name="chat_camera_open_failed">Couldn\'t open the camera</string>
|
||||
@@ -217,7 +217,7 @@
|
||||
<string name="dashboard_component_connected">connected</string>
|
||||
<string name="dashboard_component_server_errors_5m">server errors / 5m</string>
|
||||
<string name="conn_label_connect">Connect</string>
|
||||
<string name="conn_label_connections">Connections</string>
|
||||
<string name="conn_label_connections">Gateways</string>
|
||||
<string name="conn_detail_add_connection">Add a Vanilla Hermes API/dashboard connection</string>
|
||||
<string name="conn_detail_waiting_network">Waiting for Android to report an internet route</string>
|
||||
<string name="conn_detail_chat_unavailable">Chat and profile calls may not be available</string>
|
||||
@@ -303,19 +303,19 @@
|
||||
<string name="error_classify_open_settings">Open Settings</string>
|
||||
|
||||
<!-- Connection wizard — Connect page essentials -->
|
||||
<string name="cw_connect_to_hermes">Connect to Hermes</string>
|
||||
<string name="cw_connect_to_hermes">Add gateway</string>
|
||||
<string name="cw_nearby_description">We’ll look for Hermes on this network. Dashboard and Gateway provide the standard Chat, Manage, and Voice connection.</string>
|
||||
<string name="cw_connection_chooser_description">Choose the setup you have. Hermes Relay is optional.</string>
|
||||
<string name="cw_connection_chooser_description">A gateway is one Hermes installation. Choose how this phone can reach it.</string>
|
||||
<string name="cw_scan_setup_qr_title">Scan Hermes setup QR</string>
|
||||
<string name="cw_scan_setup_qr_subtitle">Configure local, remote, and available Relay routes</string>
|
||||
<string name="cw_recommended">Recommended</string>
|
||||
<string name="cw_other_ways_to_connect">Other ways to connect</string>
|
||||
<string name="cw_other_ways_to_connect">Choose a gateway</string>
|
||||
<string name="cw_advanced">Advanced</string>
|
||||
<string name="cw_cloud_title">Nous-hosted Hermes</string>
|
||||
<string name="cw_cloud_subtitle">Connect to your hosted agent</string>
|
||||
<string name="cw_server_vps_title">Server or VPS</string>
|
||||
<string name="cw_server_vps_subtitle">Enter a secure Dashboard address</string>
|
||||
<string name="cw_relay_optional_note">Standard Chat, Manage, and Voice work without Relay. Compatible setup QRs add Relay power features when available.</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_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>
|
||||
@@ -349,7 +349,7 @@
|
||||
<string name="cw_relay_pair_qr">Pair Hermes Relay</string>
|
||||
<string name="cw_relay_pair_qr_desc">Scan a Relay setup QR</string>
|
||||
<string name="cw_relay_enter_code">Enter a Relay pairing code</string>
|
||||
<string name="cw_manual_hermes_title">Enter your Hermes address</string>
|
||||
<string name="cw_manual_hermes_title">Enter gateway address</string>
|
||||
<string name="cw_manual_hermes_description">Enter the Dashboard address you open in a browser. If it does not open on this phone, start hermes dashboard and check Wi-Fi or Tailscale.</string>
|
||||
<string name="cw_hermes_address">Hermes address</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 or hermes.example.com</string>
|
||||
@@ -485,12 +485,16 @@
|
||||
<string name="cw_insecure_relay_warning">This relay uses plain ws:// — traffic is not encrypted.</string>
|
||||
<string name="cw_insecure_relay_trust">Only continue if you trust the network on any connection (LAN, Tailscale, VPN).</string>
|
||||
<string name="cw_insecure_ack">I understand this pairing sends traffic in plain text — visible to anyone on the network.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s is plain ws:// — fine at home or the office, not on public Wi-Fi.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s is encrypted (wss://) and the app uses it automatically when %2$s is unreachable.</string>
|
||||
<string name="cw_mixed_safe">You\'re safe on any network.</string>
|
||||
<string name="cw_mixed_route_plain">%1$s uses plain HTTP/WS. Use it only on a trusted private network or through a VPN you control.</string>
|
||||
<string name="cw_mixed_route_secure">%1$s uses HTTPS/WSS with transport encryption.</string>
|
||||
<string name="cw_mixed_safe">The app probes these routes and selects an available one. You can change the preferred route later.</string>
|
||||
<string name="cw_connecting_to_hermes">Connecting to Hermes</string>
|
||||
<string name="cw_connecting_detail">Checking the API server, saved key, and dashboard.</string>
|
||||
<string name="cw_pairing_title">Pairing…</string>
|
||||
<string name="cw_pair_in_progress">Working…</string>
|
||||
<string name="cw_pair_status_preparing_gateway">Preparing gateway…</string>
|
||||
<string name="cw_pair_status_opening_sign_in">Opening secure sign-in…</string>
|
||||
<string name="cw_pair_status_pairing_relay">Pairing Relay…</string>
|
||||
<string name="cw_pairing_failed">Pairing failed</string>
|
||||
<string name="cw_negotiating_relay">Negotiating with the relay…</string>
|
||||
<string name="cw_paired_opening_chat">Paired — opening chat…</string>
|
||||
@@ -513,7 +517,7 @@
|
||||
<string name="cw_voice_after_connect">Checked after connecting</string>
|
||||
<string name="cw_remote">Remote</string>
|
||||
<string name="cw_remote_fallback_ready">Fallback route ready for use away from home</string>
|
||||
<string name="cw_remote_lan_only">LAN only — add a Tailscale or public route in Settings → Connections → Routes</string>
|
||||
<string name="cw_remote_lan_only">LAN only — add a Tailscale or public route in Settings → Gateways → Routes</string>
|
||||
<string name="cw_relay">Relay</string>
|
||||
<string name="cw_relay_paired">Power tools paired</string>
|
||||
<string name="cw_relay_optional">Optional for Terminal and Bridge</string>
|
||||
@@ -532,7 +536,18 @@
|
||||
<string name="endpoints_manual_until_disconnect">Manual — until disconnect</string>
|
||||
<string name="endpoints_preferred">Preferred</string>
|
||||
<string name="endpoints_automatic">Automatic</string>
|
||||
<string name="endpoints_current_route">Current route: %1$s (%2$s)</string>
|
||||
<string name="endpoints_current_route">Selected candidate: %1$s · %2$s</string>
|
||||
<string name="endpoints_no_active_fallback">No fallback route is currently selected.</string>
|
||||
<string name="endpoints_selection_reason">Priority %1$d (0 is highest) · %2$s</string>
|
||||
<string name="endpoints_reachable_now">Reachable now</string>
|
||||
<string name="endpoints_last_check_failed">Last check failed</string>
|
||||
<string name="endpoints_reachability_not_checked">Reachability not checked</string>
|
||||
<string name="endpoints_security_application_tls">Application TLS</string>
|
||||
<string name="endpoints_security_tailscale_overlay">Encrypted by Tailscale · no application TLS</string>
|
||||
<string name="endpoints_security_wireguard_overlay">Encrypted by WireGuard · no application TLS</string>
|
||||
<string name="endpoints_security_secure_link">Encrypted by Hermes Secure Link</string>
|
||||
<string name="endpoints_security_private_plain">Private network · no application TLS</string>
|
||||
<string name="endpoints_security_public_plain">Public route is not encrypted</string>
|
||||
<string name="endpoints_cancel_manual_switch">Cancel manual switch — back to %1$s</string>
|
||||
<string name="endpoints_stop_preferring">Stop preferring — back to automatic</string>
|
||||
<string name="endpoints_checking">Checking…</string>
|
||||
@@ -567,6 +582,13 @@
|
||||
<string name="endpoints_save">Save</string>
|
||||
<string name="endpoints_close">Close</string>
|
||||
<string name="endpoints_actions">Endpoint actions</string>
|
||||
<string name="dashboard_address_editor_title">Gateway address</string>
|
||||
<string name="dashboard_address_editor_body">Set the Dashboard and Gateway address this phone should use. Private LAN and Tailscale routes may use HTTP or HTTPS; public routes require HTTPS.</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_required">Enter your Hermes Gateway address</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
|
||||
<!-- BridgeMasterToggle -->
|
||||
<string name="bmt_agent_control">Agent Control</string>
|
||||
@@ -714,8 +736,8 @@
|
||||
<string name="relay_state_needs_repair">Needs re-pair</string>
|
||||
<string name="settings_no_connection">No connection</string>
|
||||
<string name="settings_server_default">Server default</string>
|
||||
<string name="settings_connections">Connections</string>
|
||||
<string name="settings_connections_desc">API, dashboard, relay pairing, and routes</string>
|
||||
<string name="settings_connections">Gateways</string>
|
||||
<string name="settings_connections_desc">Hermes installations, routes, sign-in, and extensions</string>
|
||||
<string name="settings_hermes">Hermes</string>
|
||||
<string name="settings_hermes_management">Hermes management</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard features: skills, cron, MCP, profiles, models</string>
|
||||
@@ -805,7 +827,7 @@
|
||||
<string name="chat_settings_large_pastes">Convert large pastes to attachments</string>
|
||||
<string name="chat_settings_large_pastes_desc">Turn pastes of 5,000 or more characters into reviewable text attachments. On by default.</string>
|
||||
<string name="chat_settings_show_git_workspace">Show Git workspace in Chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Show the Git status entry and changes rail in Chat. The full Git workspace remains available when this is off.</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Show the Git status entry and changes rail in Chat when host repository scanning is enabled. The full Git workspace remains available when this is off.</string>
|
||||
<string name="chat_git_open_workspace">Open Git workspace</string>
|
||||
<string name="chat_git_branch">Git branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d additions</string>
|
||||
@@ -864,16 +886,36 @@
|
||||
<string name="chat_settings_8k">8K</string>
|
||||
<string name="chat_settings_16k">16K</string>
|
||||
<string name="chat_settings_gateway_needs_signin">Gateway needs Manage sign-in</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Sign in once from the Manage tab to unlock live thinking over /api/ws.</string>
|
||||
<string name="chat_settings_gateway_needs_signin_desc">Sign in once to unlock Chat, sessions, Manage, and standard voice for this Hermes connection.</string>
|
||||
<string name="chat_settings_completions">Completions</string>
|
||||
<string name="chat_settings_offline">offline</string>
|
||||
|
||||
<!-- P0: ConnectionsSettingsScreen -->
|
||||
<string name="conn_back">Back</string>
|
||||
<string name="conn_title">Connections</string>
|
||||
<string name="conn_add_connection">Add connection</string>
|
||||
<string name="conn_no_connections">No connections yet</string>
|
||||
<string name="conn_no_connections_desc">Tap Add connection to connect to Hermes.</string>
|
||||
<string name="conn_title">Gateways</string>
|
||||
<string name="conn_add_connection">Add gateway</string>
|
||||
<string name="conn_no_connections">No gateways yet</string>
|
||||
<string name="conn_no_connections_desc">Tap Add gateway to connect to Hermes.</string>
|
||||
<string name="gateways_title">Gateways</string>
|
||||
<plurals name="gateway_count">
|
||||
<item quantity="one">%d gateway</item>
|
||||
<item quantity="other">%d gateways</item>
|
||||
</plurals>
|
||||
<string name="gateway_add">Add gateway</string>
|
||||
<string name="gateways_empty_title">No gateways yet</string>
|
||||
<string name="gateways_empty_body">Add a gateway to connect this phone to Hermes.</string>
|
||||
<string name="gateway_route_not_configured">No route configured</string>
|
||||
<string name="gateway_status_online">Gateway online</string>
|
||||
<string name="gateway_status_sign_in_required">Sign-in required</string>
|
||||
<string name="gateway_status_offline">Gateway offline</string>
|
||||
<string name="gateway_status_checking">Checking gateway…</string>
|
||||
<string name="gateway_status_not_checked">Gateway not checked</string>
|
||||
<string name="gateway_status_last_check_sign_in_required">Last check: sign-in required</string>
|
||||
<string name="gateway_status_last_check_succeeded">Last check succeeded</string>
|
||||
<string name="gateway_status_last_check_failed">Last check failed</string>
|
||||
<string name="gateway_status_no_route">No gateway route</string>
|
||||
<string name="gateway_status_unavailable">Gateway unavailable</string>
|
||||
<string name="conn_add_requires_parent_access">Unlock parent access before adding a gateway.</string>
|
||||
<string name="conn_active">Active</string>
|
||||
<string name="conn_connected">Connected</string>
|
||||
<string name="conn_standard_not_paired">Standard · Relay not paired</string>
|
||||
@@ -954,6 +996,8 @@
|
||||
<string name="detail_tab_routes">Routes</string>
|
||||
<string name="detail_tab_advanced">Advanced</string>
|
||||
<string name="detail_tab_security">Security</string>
|
||||
<string name="detail_tab_access">Access</string>
|
||||
<string name="detail_current_route">Current route</string>
|
||||
<string name="conn_startup_title">On app start</string>
|
||||
<string name="conn_startup_last_used">Last used</string>
|
||||
<string name="conn_startup_recommended">Recommended</string>
|
||||
@@ -972,6 +1016,29 @@
|
||||
<string name="conn_dashboard_only_route">Dashboard only</string>
|
||||
<string name="conn_no_routes">No routes configured</string>
|
||||
<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="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_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>
|
||||
<string name="active_section_fallbacks">Fallbacks</string>
|
||||
<string name="active_section_configured_not_probed">Network routes are configured; Routes shows their latest reachability.</string>
|
||||
<string name="active_section_relay_ownership">Relay owns extension tools only; standard Hermes stays independent.</string>
|
||||
<string name="active_section_no_sign_in_required">No sign-in required</string>
|
||||
<string name="active_section_use_selected_route">Use selected route</string>
|
||||
<string name="active_section_use_selected_route_failed">Couldn’t switch Dashboard sign-in back to the selected route.</string>
|
||||
<string name="active_section_forget_sign_in_origin">Forget sign-in origin</string>
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="active_section_dashboard_reachable_signed_in">Reachable · Signed in</string>
|
||||
<string name="active_section_dashboard_reachable">Reachable</string>
|
||||
<string name="active_section_dashboard_not_checked">Not checked yet</string>
|
||||
@@ -1009,7 +1076,7 @@
|
||||
<string name="active_section_relay_optional_bridge">Optional bridge features and remote access</string>
|
||||
<string name="active_section_configure_relay">Configure Relay</string>
|
||||
<string name="active_section_scan_relay_qr">Scan Relay QR</string>
|
||||
<string name="active_section_other_relay_methods">Other pairing methods</string>
|
||||
<string name="active_section_direct_relay_endpoint">Direct Relay endpoint</string>
|
||||
<string name="active_section_pair_device_using_code">Pair this device using a code from the server.</string>
|
||||
<string name="active_section_enter_pairing_code">Enter pairing code</string>
|
||||
<string name="active_section_done">Done</string>
|
||||
@@ -1026,9 +1093,16 @@
|
||||
<string name="active_section_session_activity">Session activity</string>
|
||||
<string name="active_section_last_checked_just_now">Last checked just now</string>
|
||||
<string name="active_section_protected">Protected</string>
|
||||
<string name="active_section_mixed_protection">Mixed protection</string>
|
||||
<string name="active_section_not_encrypted">Not encrypted</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_no_security_issues">No security issues detected</string>
|
||||
<string name="active_section_mixed_protection_summary">Active surfaces use different protection</string>
|
||||
<string name="active_section_unencrypted_transport">This connection uses an unencrypted transport</string>
|
||||
<string name="active_section_no_active_surfaces">No configured surface is currently in use</string>
|
||||
<string name="active_section_in_use_mechanism">In use · %1$s</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="active_section_actions">Actions</string>
|
||||
<string name="active_section_revoke_relay">Revoke Relay pairing</string>
|
||||
|
||||
@@ -1090,6 +1164,8 @@
|
||||
<string name="drawer_delete_session_title">Delete Session?</string>
|
||||
<string name="drawer_delete_session_prefix">This will permanently delete \"</string>
|
||||
<string name="drawer_delete_session_suffix">\" and its message history.</string>
|
||||
<string name="drawer_remove_provisional_thread_title">Remove Thread?</string>
|
||||
<string name="drawer_remove_provisional_thread_message">This removes \"%1$s\" from this device. It does not delete promoted or server history.</string>
|
||||
<string name="drawer_untitled">Untitled</string>
|
||||
<string name="drawer_delete">Delete</string>
|
||||
<string name="drawer_thread">Thread</string>
|
||||
@@ -1120,7 +1196,7 @@
|
||||
<string name="bridge_relay_label">relay</string>
|
||||
<string name="bridge_safety_label">safety</string>
|
||||
<string name="bridge_not_connected_title">Relay not connected</string>
|
||||
<string name="bridge_not_connected_body">Bridge commands travel over the relay. Pair a relay in Settings → Connections for the bridge to actually do anything.</string>
|
||||
<string name="bridge_not_connected_body">Bridge commands travel over Relay. Pair Relay in Settings → Gateways for the bridge to actually do anything.</string>
|
||||
<string name="bridge_accessibility_needed">Accessibility Service must be enabled first.</string>
|
||||
<string name="bridge_open_settings">Open Settings</string>
|
||||
<string name="bridge_allow_agent_control">Allow Agent Control</string>
|
||||
@@ -1157,8 +1233,8 @@
|
||||
<string name="bridge_core_relay_body">Bridge Core uses the same paired relay session as terminal, notification, media, and voice features.</string>
|
||||
<string name="bridge_core_surface_title">Bridge Surface</string>
|
||||
<string name="bridge_core_surface_meta">not hidden in settings</string>
|
||||
<string name="bridge_core_connections">Connections</string>
|
||||
<string name="bridge_core_connections_sub">Pair, switch, and verify relay routes</string>
|
||||
<string name="bridge_core_connections">Gateways</string>
|
||||
<string name="bridge_core_connections_sub">Pair Relay, switch gateways, and verify routes</string>
|
||||
<string name="bridge_core_terminal_tile">Terminal</string>
|
||||
<string name="bridge_core_terminal_sub">Attach to your Hermes relay terminal</string>
|
||||
<string name="bridge_core_voice">Voice</string>
|
||||
@@ -1599,7 +1675,7 @@
|
||||
<string name="proactive_let_hermes_message_me">Let Hermes message me</string>
|
||||
<string name="proactive_allow_proactive_messages">Allow proactive messages</string>
|
||||
<string name="proactive_allow_proactive_messages_desc">Your agent can reach out on its own — reminders, finished jobs, alerts. Its messages appear as Threads in Chat, where you can reply.</string>
|
||||
<string name="proactive_not_paired_warning">Not paired yet — pair with your Hermes server under Settings → Connections to start receiving messages.</string>
|
||||
<string name="proactive_not_paired_warning">Not paired yet — pair Relay under Settings → Gateways to start receiving messages.</string>
|
||||
<string name="proactive_your_threads">Your Threads</string>
|
||||
<string name="proactive_your_threads_desc">Each conversation your agent starts shows as a Thread in Chat — open the session list, filter to Threads, and reply right there.</string>
|
||||
<string name="proactive_open_chat">Open Chat</string>
|
||||
@@ -1789,7 +1865,7 @@
|
||||
<string name="voice_settings_engine_realtime">Realtime Agent</string>
|
||||
<string name="voice_settings_engine_realtime_desc">A live provider session handles listening and speaking with its own voice model and voice. Hermes still handles tools, memory, and confirmations. Requires a paired Relay.</string>
|
||||
<string name="voice_settings_experimental">Experimental</string>
|
||||
<string name="voice_settings_realtime_no_relay">No Relay is configured for this connection, so the Realtime Agent can\'t start. Pair Relay in Settings → Connections, or switch back to Hermes Chat + Voice Output.</string>
|
||||
<string name="voice_settings_realtime_no_relay">No Relay is configured for this gateway, so the Realtime Agent can\'t start. Pair Relay in Settings → Gateways, or switch back to Hermes Chat + Voice Output.</string>
|
||||
<string name="voice_settings_route_label">STT/TTS route</string>
|
||||
<string name="voice_settings_status_ready">Ready</string>
|
||||
<string name="voice_settings_status_sign_in_required">Dashboard sign-in required</string>
|
||||
@@ -2033,8 +2109,8 @@
|
||||
<string name="dashboard_tile_config_sub">Schema and runtime options</string>
|
||||
|
||||
<!-- Nav tiles -->
|
||||
<string name="dashboard_nav_connections_title">Connections</string>
|
||||
<string name="dashboard_nav_connections_sub">Pair, switch, verify routes</string>
|
||||
<string name="dashboard_nav_connections_title">Gateways</string>
|
||||
<string name="dashboard_nav_connections_sub">Sign in, pair Relay, switch, and verify routes</string>
|
||||
|
||||
<!-- Hub header -->
|
||||
<string name="dashboard_hub_title">Relay Hub</string>
|
||||
@@ -2070,7 +2146,7 @@
|
||||
|
||||
<!-- Sign-in card -->
|
||||
<string name="dashboard_signin_required_title">Dashboard sign-in required</string>
|
||||
<string name="dashboard_signin_required_body">Manage uses the Hermes dashboard session at %1$s.</string>
|
||||
<string name="dashboard_signin_required_body">Sign in to Hermes at %1$s for Chat, sessions, Manage, and standard voice.</string>
|
||||
<string name="dashboard_signin_route_hint">The saved dashboard session could not be reused on the %1$s route. Sign in again to refresh it across this connection\'s trusted routes.</string>
|
||||
<string name="dashboard_signin_with_provider">Sign in with %1$s</string>
|
||||
<string name="dashboard_username_password">Username & Password</string>
|
||||
@@ -2079,25 +2155,34 @@
|
||||
<string name="dashboard_sign_in">Sign in</string>
|
||||
<string name="dashboard_signing_in">Signing in…</string>
|
||||
<string name="dashboard_no_supported_provider">This dashboard did not advertise a supported Android sign-in provider.</string>
|
||||
<string name="dashboard_signin_provider_unavailable_choose">Your saved sign-in provider is unavailable. Choose another configured provider or try again later.</string>
|
||||
|
||||
<!-- OAuth sign-in dialog -->
|
||||
<string name="dashboard_oauth_initial_status">Complete sign-in in the secure dashboard page.</string>
|
||||
<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="dashboard_oauth_origin_confirm_title">Use this sign-in address?</string>
|
||||
<string name="dashboard_oauth_origin_confirm_body">The identity provider returned to a different Hermes Dashboard address. Review it before Android uses it for Dashboard and Gateway.</string>
|
||||
<string name="dashboard_oauth_origin_identity_missing">This Hermes version does not expose an installation ID, so Android cannot automatically prove that both addresses reach the same installation.</string>
|
||||
<string name="dashboard_oauth_origin_install_mismatch">The sign-in address belongs to a different Hermes installation and was not saved.</string>
|
||||
<string name="dashboard_oauth_origin_use_button">Use address</string>
|
||||
<string name="dashboard_oauth_verifying">Verifying dashboard session…</string>
|
||||
<string name="dashboard_oauth_not_accepted">Sign-in was not accepted yet. Finish the dashboard flow to continue.</string>
|
||||
<string name="dashboard_oauth_verify_failed">Dashboard sign-in verification failed</string>
|
||||
<string name="dashboard_native_signin_opening">Complete sign-in in your browser, then return here.</string>
|
||||
<string name="dashboard_native_signin_opening">Complete sign-in in your browser. If your provider signs you in without returning, come back and tap Continue sign-in.</string>
|
||||
<string name="dashboard_native_signin_continue">Continue sign-in</string>
|
||||
<string name="dashboard_native_signin_cancelled">Browser sign-in cancelled.</string>
|
||||
<string name="dashboard_native_signin_requires_https">Secure browser sign-in requires an HTTPS dashboard address.</string>
|
||||
<string name="dashboard_native_signin_unavailable">Secure browser sign-in is unavailable for this connection. Refresh the connection and try again.</string>
|
||||
<string name="dashboard_native_signin_embedded_fallback">Secure browser sign-in was unavailable, so Hermes opened its compatible in-app sign-in.</string>
|
||||
<string name="dashboard_native_signin_transport_retry">The secure connection was interrupted. Tap the sign-in button to try again.</string>
|
||||
<string name="dashboard_native_signin_callback_rejected">The provider did not approve this sign-in. If you cancelled, no action is needed; otherwise start a fresh sign-in attempt.</string>
|
||||
<string name="dashboard_native_signin_code_rejected">Google sign-in finished, but hosted Hermes rejected the one-time callback code before it could create a session. Start a fresh sign-in attempt.</string>
|
||||
<string name="dashboard_native_signin_gateway_rejected">Hosted Hermes refused the session exchange. Check that the hosted agent is current, then start sign-in again.</string>
|
||||
<string name="dashboard_native_signin_rate_limited">Hosted Hermes received too many sign-in attempts. Wait a moment, then try again.</string>
|
||||
<string name="dashboard_native_signin_gateway_unavailable">Google sign-in finished, but the hosted Hermes sign-in service is unavailable. Wait a moment, then try again.</string>
|
||||
<string name="dashboard_native_signin_response_unsupported">Hosted Hermes returned a sign-in response this app could not use. Check for Hermes Relay and hosted agent updates.</string>
|
||||
<string name="dashboard_native_signin_code_rejected">Browser sign-in finished, but Hermes rejected the one-time callback code before it could create a session. Start a fresh sign-in attempt.</string>
|
||||
<string name="dashboard_native_signin_gateway_rejected">Hermes refused the session exchange. Check that the Dashboard is current, then start sign-in again.</string>
|
||||
<string name="dashboard_native_signin_rate_limited">Hermes received too many sign-in attempts. Wait a moment, then try again.</string>
|
||||
<string name="dashboard_native_signin_gateway_unavailable">Browser sign-in finished, but the Hermes sign-in service is unavailable. Wait a moment, then try again.</string>
|
||||
<string name="dashboard_native_signin_response_unsupported">Hermes returned a sign-in response this app could not use. Check for app and Dashboard updates.</string>
|
||||
<string name="dashboard_native_signin_attempt_inactive">This sign-in attempt was cancelled or replaced. Close the old browser tab and start again.</string>
|
||||
<string name="dashboard_native_signin_storage_failed">Google sign-in finished, but Android could not securely save the Hermes session. Try again; if it repeats, open Diagnostics for the failure stage.</string>
|
||||
<string name="dashboard_native_signin_storage_failed">Browser sign-in finished, but Android could not securely save the Hermes session. Try again; if it repeats, open Diagnostics for the failure stage.</string>
|
||||
<string name="dashboard_close_signin">Close sign-in</string>
|
||||
|
||||
<!-- Error body -->
|
||||
@@ -2591,8 +2676,11 @@
|
||||
<string name="active_section_no_response_from_relay">No response from relay</string>
|
||||
<string name="active_section_no_route_reachable">No route reachable</string>
|
||||
<string name="active_section_no_routes_answered_probe">No routes answered the probe</string>
|
||||
<string name="active_section_no_reachable_route_title">No reachable Gateway route</string>
|
||||
<string name="active_section_no_reachable_route_body">None of the configured Gateway routes responded. Turn on Tailscale, Wi-Fi, or mobile data, then recheck. Expand a route below for Dashboard, API, and Relay results.</string>
|
||||
<string name="active_section_not_advertised">Not advertised</string>
|
||||
<string name="active_section_not_checked">Not checked</string>
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_not_configured">Not configured</string>
|
||||
<string name="active_section_offline">Offline</string>
|
||||
<string name="active_section_open_tailscale">Open Tailscale</string>
|
||||
@@ -2733,7 +2821,7 @@
|
||||
<string name="conn_info_loading_profiles">Loading profiles…</string>
|
||||
<string name="conn_info_local_display_name">Local display name</string>
|
||||
<string name="conn_info_locked_to">Locked to %1$s</string>
|
||||
<string name="conn_info_manage_connections">Manage connections</string>
|
||||
<string name="conn_info_manage_connections">Manage gateways</string>
|
||||
<string name="conn_info_manage_profiles">Manage profile display</string>
|
||||
<string name="conn_info_manage_profiles_hint">Reorder profiles or hide ones you do not use. The active profile stays visible.</string>
|
||||
<string name="conn_info_move_profile_up">Move %1$s up</string>
|
||||
@@ -3022,8 +3110,8 @@
|
||||
|
||||
<!-- ConnectionSwitcherSheet -->
|
||||
<string name="conn_switcher_title">Switch connection</string>
|
||||
<string name="conn_switcher_empty">No connections yet</string>
|
||||
<string name="conn_switcher_manage">Manage connections…</string>
|
||||
<string name="conn_switcher_empty">No gateways yet</string>
|
||||
<string name="conn_switcher_manage">Manage gateways…</string>
|
||||
|
||||
<!-- DiagnosticsLogPanel -->
|
||||
<string name="diagnostics_title">Recent activity</string>
|
||||
@@ -3197,7 +3285,7 @@
|
||||
<string name="transport_badge_insecure_lan_only">Plain (LAN only)</string>
|
||||
<string name="transport_badge_encrypted_tls">Encrypted · TLS</string>
|
||||
<string name="transport_badge_encrypted_tailscale">Encrypted · Tailscale</string>
|
||||
<string name="transport_badge_mixed_routes">Mixed routes</string>
|
||||
<string name="transport_badge_mixed_routes">Mixed protection</string>
|
||||
<string name="transport_badge_not_encrypted">Not encrypted</string>
|
||||
<string name="transport_badge_checking">Checking…</string>
|
||||
<string name="transport_badge_glyph_tls">Encrypted (TLS)</string>
|
||||
@@ -3420,7 +3508,7 @@
|
||||
<string name="screen_bridge_label">Bridge</string>
|
||||
<string name="screen_manage_label">Manage</string>
|
||||
<string name="screen_settings_label">Settings</string>
|
||||
<string name="screen_connections_label">Connections</string>
|
||||
<string name="screen_connections_label">Gateways</string>
|
||||
<string name="screen_connection_label">Connection</string>
|
||||
<string name="screen_voice_label">Voice</string>
|
||||
<string name="screen_notification_companion_label">Notification companion</string>
|
||||
@@ -3506,7 +3594,7 @@
|
||||
<string name="cw_hint_chat">Chat</string>
|
||||
<string name="cw_hint_manage">Manage</string>
|
||||
<string name="cw_http_url_field_label">URL</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s expects http:// or https:// (bare hosts get http://)</string>
|
||||
<string name="cw_http_url_scheme_error">%1$s expects http:// or https:// (bare private hosts use http://; bare public hosts use https://)</string>
|
||||
<string name="cw_label_api_key">API Key</string>
|
||||
<string name="cw_label_api_server">API Server</string>
|
||||
<string name="cw_label_dashboard">Dashboard</string>
|
||||
@@ -3559,7 +3647,7 @@
|
||||
<string name="cw_step_3_3">Step 3 of 3</string>
|
||||
<string name="cw_tailscale_placeholder">http://100.x.x.x:8642</string>
|
||||
<string name="cw_tailscale_supporting_detected">Tailscale network detected</string>
|
||||
<string name="cw_tailscale_supporting_other">When away from the server network, manually switch timeout, address, API port (8642) and http:// defaults can be changed in Settings → Connections → Routes.</string>
|
||||
<string name="cw_tailscale_supporting_other">When away from the server network, manually switch timeout, address, API port (8642), and http:// defaults can be changed in Settings → Gateways → Routes.</string>
|
||||
<string name="cw_value_derived">Auto-detected</string>
|
||||
<string name="cw_value_included">Included</string>
|
||||
<string name="cw_value_not_included">Not included</string>
|
||||
@@ -3659,13 +3747,15 @@
|
||||
<string name="relay_app_reconnecting">Reconnecting…</string>
|
||||
<string name="relay_app_rename_failed">Rename failed</string>
|
||||
<string name="relay_app_revoke_only_active">Revoke</string>
|
||||
<string name="security_sheet_explain_mixed">Mixed security — some connections use TLS, some don\u0027t</string>
|
||||
<string name="security_sheet_explain_mixed">Active surfaces use different protection. Unavailable fallbacks are not included in this verdict.</string>
|
||||
<string name="security_sheet_explain_overlay">Overlay connection uses Wi-Fi peer-to-peer</string>
|
||||
<string name="security_sheet_explain_plain">No encryption — plain HTTP connection</string>
|
||||
<string name="security_sheet_explain_tls">Encrypted — TLS connection</string>
|
||||
<string name="security_sheet_learn_more">Learn about connection security →</string>
|
||||
<string name="security_sheet_no_route">No route configured</string>
|
||||
<string name="security_sheet_title">Connection security</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="subagent_lane_a11y">%1$s %2$s</string>
|
||||
<string name="subagent_lane_label_fallback">Agent</string>
|
||||
<string name="subagent_lane_running_count">%d running</string>
|
||||
@@ -3735,6 +3825,40 @@
|
||||
<string name="tool_failed_a11y">Failed</string>
|
||||
<string name="background_process_count">Background · %1$d</string>
|
||||
<string name="background_processes_title">Background processes</string>
|
||||
<string name="current_chat_activity_title">Current chat activity</string>
|
||||
<string name="current_chat_activity_subtitle">Read-only live details from this chat</string>
|
||||
<string name="current_chat_activity_open">Preview current chat activity</string>
|
||||
<string name="current_chat_activity_summary">%1$d agents · %2$d processes</string>
|
||||
<string name="current_chat_activity_close">Close activity preview</string>
|
||||
<string name="current_chat_activity_empty">No current activity in this chat</string>
|
||||
<string name="current_chat_activity_latest">Latest</string>
|
||||
<string name="agent_activity_section">Live agent activity</string>
|
||||
<string name="agent_activity_disclosure">Updates received by this chat. Full child history may be unavailable.</string>
|
||||
<string name="agent_activity_fallback">Agent %d</string>
|
||||
<string name="agent_activity_task_position">%1$d of %2$d · %3$s</string>
|
||||
<string name="agent_activity_lane_a11y">%1$s, %2$s, agent %3$d of %4$d</string>
|
||||
<string name="agent_activity_duration">%1$.1fs</string>
|
||||
<string name="agent_activity_older_omitted">Older activity omitted</string>
|
||||
<string name="agent_activity_partial">Live updates resumed. Activity while offline may be missing.</string>
|
||||
<string name="agent_activity_event_started">Started</string>
|
||||
<string name="agent_activity_event_update">Update</string>
|
||||
<string name="agent_activity_event_tool">Tool preview</string>
|
||||
<string name="agent_activity_status_started">Starting</string>
|
||||
<string name="agent_activity_status_thinking">Thinking</string>
|
||||
<string name="agent_activity_status_tool">Using a tool</string>
|
||||
<string name="agent_activity_status_progress">Working</string>
|
||||
<string name="agent_activity_status_completed">Completed</string>
|
||||
<string name="agent_activity_status_failed">Failed</string>
|
||||
<string name="agent_activity_status_interrupted">Interrupted</string>
|
||||
<string name="agent_activity_status_unavailable">Final state unavailable</string>
|
||||
<string name="agent_activity_child_loading">Opening read-only child history…</string>
|
||||
<string name="agent_activity_child_unavailable">Child transcript unavailable on this Hermes version or route. Parent-session activity is shown above.</string>
|
||||
<string name="agent_activity_child_live">Child history · live updates</string>
|
||||
<string name="agent_activity_child_history">Child history · read only</string>
|
||||
<string name="agent_activity_child_truncated">Recent child activity shown · older or oversized details omitted</string>
|
||||
<string name="agent_activity_child_role_task">Task</string>
|
||||
<string name="agent_activity_child_role_agent">Agent</string>
|
||||
<string name="agent_activity_child_role_system">System</string>
|
||||
<string name="background_processes_refresh_a11y">Refresh processes</string>
|
||||
<string name="background_processes_subtitle">Current chat · live output and recent results</string>
|
||||
<string name="background_processes_stop">Stop</string>
|
||||
@@ -3754,6 +3878,7 @@
|
||||
<string name="card_send_answer_a11y">Send answer</string>
|
||||
<string name="card_submit">Submit</string>
|
||||
<string name="card_answer_placeholder">Type an answer…</string>
|
||||
<string name="card_other_answer_placeholder">Other (type your answer)…</string>
|
||||
<string name="session_ttl_title">Keep this pairing for…</string>
|
||||
<string name="session_ttl_intro">Your phone will reconnect automatically during this window. You can revoke the pairing at any time.</string>
|
||||
<string name="session_ttl_stays_paired">This device will stay paired until you revoke it.</string>
|
||||
@@ -4228,6 +4353,9 @@
|
||||
<string name="plugins_remove">Remove</string>
|
||||
<string name="plugins_remove_confirm">Remove “%1$s”? This plugin page will no longer appear on connected Android devices.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_host_scanning">Host repository scanning</string>
|
||||
<string name="git_state_host_scanning_on_desc">On for this gateway · Git writes remain separately permissioned.</string>
|
||||
<string name="git_state_host_scanning_off_desc">Let this phone ask this gateway to scan its configured Git roots for repositories, branches, and change status. Git writes require separate permission.</string>
|
||||
<string name="git_state_back">Back</string>
|
||||
<string name="git_state_staged">Staged</string>
|
||||
<string name="git_state_modified">Modified</string>
|
||||
@@ -4274,7 +4402,7 @@
|
||||
|
||||
<string name="support_bundle_review">Review support information</string>
|
||||
<string name="support_bundle_title">Support information</string>
|
||||
<string name="support_bundle_privacy">Nothing is uploaded automatically. Review the exact local export below. It contains up to %1$d recent reports.</string>
|
||||
<string name="support_bundle_privacy">Nothing is uploaded automatically. Review the exact local export below. It contains %1$d recent reports and diagnostics.</string>
|
||||
<string name="support_bundle_copied">Support information copied</string>
|
||||
<string name="support_bundle_no_share">Support information copied — no app found to share to</string>
|
||||
<string name="support_bundle_share_title">Share Hermes-Relay support information</string>
|
||||
@@ -4450,4 +4578,5 @@
|
||||
<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>
|
||||
</resources>
|
||||
|
||||
+116
@@ -65,6 +65,122 @@ class AssistantSessionProtocolTest {
|
||||
assertEquals("Microphone unavailable", error.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun idleNoSpeech_isAVisibleRetryNotice() {
|
||||
val snapshot = AssistantSessionProtocol.snapshotFromVoiceState(
|
||||
VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Idle,
|
||||
assistantNotice = AssistantSessionNotice.NoSpeech,
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(AssistantSessionPhase.Idle, snapshot.phase)
|
||||
assertEquals(AssistantSessionNotice.NoSpeech, snapshot.notice)
|
||||
assertNull(snapshot.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lockedPresentation_redactsConversationButKeepsGenericNotice() {
|
||||
val presented = assistantSnapshotForPresentation(
|
||||
AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Error,
|
||||
transcript = "private request",
|
||||
response = "private response",
|
||||
notice = AssistantSessionNotice.NoSpeech,
|
||||
error = "private route detail",
|
||||
),
|
||||
locked = true,
|
||||
)
|
||||
|
||||
assertNull(presented.transcript)
|
||||
assertEquals("", presented.response)
|
||||
assertNull(presented.error)
|
||||
assertEquals(AssistantSessionNotice.NoSpeech, presented.notice)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unlockedPresentation_restoresConversationContent() {
|
||||
val snapshot = AssistantSessionSnapshot(
|
||||
phase = AssistantSessionPhase.Speaking,
|
||||
transcript = "request",
|
||||
response = "response",
|
||||
)
|
||||
|
||||
assertEquals(snapshot, assistantSnapshotForPresentation(snapshot, locked = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveKeyguardState_overridesLaunchFallbackInBothDirections() {
|
||||
assertTrue(
|
||||
assistantPresentationLocked(
|
||||
currentKeyguardLocked = true,
|
||||
fallbackLocked = false,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
assistantPresentationLocked(
|
||||
currentKeyguardLocked = false,
|
||||
fallbackLocked = true,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun statusSnapshots_areFencedToTheCurrentActivation() {
|
||||
assertTrue(assistantSnapshotMatchesActivation("activation-b", "activation-b"))
|
||||
assertFalse(assistantSnapshotMatchesActivation("activation-b", "activation-a"))
|
||||
assertFalse(assistantSnapshotMatchesActivation("activation-b", null))
|
||||
assertFalse(assistantSnapshotMatchesActivation(null, "activation-b"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun voiceStateRetainsItsOwningActivationAcrossLaterRuntimeChanges() {
|
||||
val activationA = VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Listening,
|
||||
assistantActivationId = "activation-a",
|
||||
)
|
||||
val currentRuntimeActivation = "activation-b"
|
||||
|
||||
assertEquals("activation-a", activationA.assistantActivationId)
|
||||
assertFalse(
|
||||
assistantSnapshotMatchesActivation(
|
||||
expectedActivationId = currentRuntimeActivation,
|
||||
receivedActivationId = activationA.assistantActivationId,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalVoiceStateRetainsActivationForClosedPublication() {
|
||||
val exited = com.hermesandroid.relay.viewmodel.voiceSessionExitState(
|
||||
VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Speaking,
|
||||
assistantActivationId = "activation-a",
|
||||
)
|
||||
)
|
||||
|
||||
assertFalse(exited.voiceMode)
|
||||
assertEquals("activation-a", exited.assistantActivationId)
|
||||
assertEquals(
|
||||
AssistantSessionPhase.Closed,
|
||||
AssistantSessionProtocol.snapshotFromVoiceState(exited).phase,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun subsequentOrdinaryVoiceEntryClearsPreviousAssistantOwner() {
|
||||
val ordinaryEntry = VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Idle,
|
||||
assistantActivationId = null,
|
||||
)
|
||||
|
||||
assertNull(ordinaryEntry.assistantActivationId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedSessionMarker_expiresAfterBoundedRecoveryWindow() {
|
||||
val now = 2_000_000L
|
||||
|
||||
@@ -277,4 +277,40 @@ class AgentDisplayTest {
|
||||
assertEquals("conn::__server_default__", AgentDisplay.profileContextKey("conn", null))
|
||||
assertEquals("conn::mizu", AgentDisplay.profileContextKey("conn", "mizu"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseProfileContextKey_preservesRequestIdentityAndConnectionScope() {
|
||||
val serverDefault = AgentDisplay.parseProfileContextKey(
|
||||
AgentDisplay.profileContextKey("connection-a", null),
|
||||
)
|
||||
assertEquals("connection-a", serverDefault?.connectionId)
|
||||
assertEquals(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, serverDefault?.profileKey)
|
||||
assertNull(serverDefault?.requestProfileName)
|
||||
|
||||
val literalDefault = AgentDisplay.parseProfileContextKey(
|
||||
AgentDisplay.profileContextKey("connection-a", "default"),
|
||||
)
|
||||
assertEquals("default", literalDefault?.profileKey)
|
||||
assertEquals("default", literalDefault?.requestProfileName)
|
||||
|
||||
val named = AgentDisplay.parseProfileContextKey(
|
||||
AgentDisplay.profileContextKey("connection-b", "mizu"),
|
||||
)
|
||||
assertEquals("connection-b", named?.connectionId)
|
||||
assertEquals("mizu", named?.requestProfileName)
|
||||
|
||||
val delimitedProfile = AgentDisplay.parseProfileContextKey(
|
||||
AgentDisplay.profileContextKey("connection-c", "team::writer"),
|
||||
)
|
||||
assertEquals("connection-c", delimitedProfile?.connectionId)
|
||||
assertEquals("team::writer", delimitedProfile?.requestProfileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseProfileContextKey_failsClosedForLegacyOrMalformedKeys() {
|
||||
assertNull(AgentDisplay.parseProfileContextKey("connection/profile-default"))
|
||||
assertNull(AgentDisplay.parseProfileContextKey("connection-a::"))
|
||||
assertNull(AgentDisplay.parseProfileContextKey("::default"))
|
||||
assertNull(AgentDisplay.parseProfileContextKey(null))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +87,20 @@ class ChatTurnCheckpointStoreTest {
|
||||
assertEquals(checkpoint, store.read())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checkpointWithoutProfileKey_remainsReadableAsLegacyIdentity() = runTest {
|
||||
val current = sampleCheckpoint().copy(profileKey = "default")
|
||||
val legacyJson = Json.encodeToString(current)
|
||||
.replace("\"profileKey\":\"default\",", "")
|
||||
dataStore.edit { preferences ->
|
||||
preferences[stringPreferencesKey("chat_inflight_turn_checkpoint_v1")] = legacyJson
|
||||
}
|
||||
|
||||
val restored = store.read()
|
||||
assertEquals(current.contextKey, restored?.contextKey)
|
||||
assertNull(restored?.profileKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multipleRunningSessions_mergeAndRemoveIndependently() = runTest {
|
||||
val first = sampleCheckpoint()
|
||||
@@ -106,7 +120,8 @@ class ChatTurnCheckpointStoreTest {
|
||||
}
|
||||
|
||||
private fun sampleCheckpoint() = ChatTurnCheckpoint(
|
||||
contextKey = "connection-a/profile-default",
|
||||
contextKey = AgentDisplay.profileContextKey("connection-a", null),
|
||||
profileKey = AgentDisplay.SERVER_DEFAULT_PROFILE_KEY,
|
||||
sessionId = "stored-42",
|
||||
liveSessionId = "live-42",
|
||||
transport = "gateway",
|
||||
|
||||
@@ -67,6 +67,43 @@ class ConnectionDashboardFieldsTest {
|
||||
assertEquals("https://dashboard.example.com", connection.resolvedDashboardUrl)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolvedDashboardUrl_prefersAuthenticatedOriginWithoutReplacingConfiguredRoute() {
|
||||
val connection = sampleConnection(
|
||||
dashboardUrl = "http://192.168.1.20:9119",
|
||||
).copy(authenticatedDashboardOrigin = "https://hermes.example.com")
|
||||
|
||||
assertEquals("https://hermes.example.com", connection.resolvedDashboardUrl)
|
||||
assertEquals("http://192.168.1.20:9119", connection.configuredDashboardUrl)
|
||||
assertEquals("http://192.168.1.20:9119", connection.dashboardUrl)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun privateHttpAuthenticatedOrigin_survivesResolutionAndReload() {
|
||||
listOf(
|
||||
"http://100.75.1.2:9119",
|
||||
"http://127.0.0.1:9119",
|
||||
"http://[::1]:9119",
|
||||
).forEach { origin ->
|
||||
val stored = sampleConnection(dashboardUrl = "http://192.168.1.20:9119")
|
||||
.copy(authenticatedDashboardOrigin = origin)
|
||||
|
||||
assertEquals(origin, stored.resolvedDashboardUrl)
|
||||
assertEquals(origin, stored.withDashboardDefaults().authenticatedDashboardOrigin)
|
||||
assertEquals(
|
||||
origin,
|
||||
json.decodeFromString<Connection>(
|
||||
json.encodeToString(Connection.serializer(), stored),
|
||||
).withDashboardDefaults().resolvedDashboardUrl,
|
||||
)
|
||||
}
|
||||
assertNull(
|
||||
sampleConnection().copy(
|
||||
authenticatedDashboardOrigin = "http://public.example.test:9119",
|
||||
).withDashboardDefaults().authenticatedDashboardOrigin,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolvedDashboardUrl_derivesWhenMissing() {
|
||||
val connection = sampleConnection(dashboardUrl = null)
|
||||
@@ -92,6 +129,19 @@ class ConnectionDashboardFieldsTest {
|
||||
assertEquals("http://localhost:9119", connection.resolvedDashboardUrl)
|
||||
assertTrue(Connection.isAutoManagedDashboardUrl(connection.dashboardUrl, connection.apiServerUrl))
|
||||
assertEquals(0, connection.routeCandidates.size)
|
||||
assertEquals(false, connection.gitRepoScanningEnabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gitRepoScanningConsent_roundTripsPerConnection() {
|
||||
val enabled = sampleConnection().copy(gitRepoScanningEnabled = true)
|
||||
|
||||
val decoded = json.decodeFromString<Connection>(
|
||||
json.encodeToString(Connection.serializer(), enabled),
|
||||
)
|
||||
|
||||
assertTrue(decoded.gitRepoScanningEnabled)
|
||||
assertEquals(false, sampleConnection().gitRepoScanningEnabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -180,6 +230,57 @@ class ConnectionDashboardFieldsTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun legacyAuthenticatedDashboardRoute_migratesToIndependentOrigin() {
|
||||
val lan = EndpointCandidate(
|
||||
role = "lan",
|
||||
priority = 0,
|
||||
api = ApiEndpoint("192.168.1.20", 8642),
|
||||
relay = RelayEndpoint("ws://192.168.1.20:8767"),
|
||||
dashboard = DashboardEndpoint("http://192.168.1.20:9119"),
|
||||
)
|
||||
val legacyAuthenticationRoute = EndpointCandidate(
|
||||
role = LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE,
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint("https://hermes.example.com/"),
|
||||
)
|
||||
val stored = sampleConnection(dashboardUrl = "https://hermes.example.com").copy(
|
||||
routeCandidates = listOf(lan, legacyAuthenticationRoute),
|
||||
preferredRouteRole = LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE,
|
||||
)
|
||||
|
||||
val migrated = stored.withDashboardDefaults()
|
||||
|
||||
assertEquals("https://hermes.example.com", migrated.authenticatedDashboardOrigin)
|
||||
assertEquals(listOf(lan), migrated.routeCandidates)
|
||||
assertNull(migrated.preferredRouteRole)
|
||||
assertEquals(migrated, migrated.withDashboardDefaults())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun migration_preservesUnrelatedPreferredRouteAndRejectsCleartextOrigin() {
|
||||
val lan = EndpointCandidate(
|
||||
role = "lan",
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint("http://192.168.1.20:9119"),
|
||||
)
|
||||
val unsafeLegacyAuthenticationRoute = EndpointCandidate(
|
||||
role = LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE,
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint("http://hermes.example.com"),
|
||||
)
|
||||
val stored = sampleConnection(dashboardUrl = "http://192.168.1.20:9119").copy(
|
||||
routeCandidates = listOf(lan, unsafeLegacyAuthenticationRoute),
|
||||
preferredRouteRole = "lan",
|
||||
)
|
||||
|
||||
val migrated = stored.withDashboardDefaults()
|
||||
|
||||
assertNull(migrated.authenticatedDashboardOrigin)
|
||||
assertEquals(listOf(lan), migrated.routeCandidates)
|
||||
assertEquals("lan", migrated.preferredRouteRole)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardRouteBuilder_acceptsBareTailscaleHostWithoutOptionalSurfaces() {
|
||||
val route = Connection.endpointCandidateFromDashboardUrl(
|
||||
@@ -212,9 +313,22 @@ class ConnectionDashboardFieldsTest {
|
||||
fun inferRouteRole_detectsTailscaleCgnat() {
|
||||
assertEquals("tailscale", Connection.inferRouteRole("https://100.75.1.2:8642"))
|
||||
assertEquals("lan", Connection.inferRouteRole("http://10.0.0.5:8642"))
|
||||
assertEquals("lan", Connection.inferRouteRole("http://homelab.lan:9119"))
|
||||
assertEquals("lan", Connection.inferRouteRole("http://hermes-box:9119"))
|
||||
assertEquals("lan", Connection.inferRouteRole("http://[fd00::10]:9119"))
|
||||
assertEquals("lan", Connection.inferRouteRole("http://[fe80::10]:9119"))
|
||||
assertEquals("tailscale", Connection.inferRouteRole("http://[fd7a:115c:a1e0::10]:9119"))
|
||||
assertEquals("public", Connection.inferRouteRole("https://[2001:4860:4860::8888]:9119"))
|
||||
assertEquals("public", Connection.inferRouteRole("https://hermes.example.com:8642"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeDashboardUrlInput_usesHttpsForBarePublicHosts() {
|
||||
assertEquals("https://hermes.example.com", Connection.normalizeDashboardUrlInput("hermes.example.com"))
|
||||
assertEquals("http://homelab.lan:9119", Connection.normalizeDashboardUrlInput("homelab.lan"))
|
||||
assertEquals("http://100.75.1.2:9119", Connection.normalizeDashboardUrlInput("100.75.1.2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun discoveredLabel_prefersHostnameForAnUncustomizedIpLabel() {
|
||||
assertEquals(
|
||||
|
||||
@@ -167,4 +167,109 @@ class ConnectionSecurityTest {
|
||||
assertEquals(true, result.isEncrypted)
|
||||
assertEquals(setOf("Hermes Secure Link"), result.surfaces.map { it.mechanism }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun healthyPlainApiFallback_doesNotMakeActiveHttpsDashboardMixed() {
|
||||
val result = computeConnectionSecurity(
|
||||
apiUrl = "http://h:8642",
|
||||
dashboardUrl = "https://h:9119",
|
||||
relayUrl = "",
|
||||
relayConfigured = false,
|
||||
activeEndpoint = endpoint("lan"),
|
||||
isTailscaleDetected = false,
|
||||
dashboardInUse = true,
|
||||
apiInUse = false,
|
||||
apiAvailable = true,
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activePlainApiFallback_countsWhenGatewayIsUnavailable() {
|
||||
val result = computeConnectionSecurity(
|
||||
apiUrl = "http://h:8642",
|
||||
dashboardUrl = "https://h:9119",
|
||||
relayUrl = "",
|
||||
relayConfigured = false,
|
||||
activeEndpoint = endpoint("lan"),
|
||||
isTailscaleDetected = false,
|
||||
dashboardInUse = false,
|
||||
apiInUse = true,
|
||||
apiAvailable = true,
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unavailableApiAndRelay_stayNeutralWhileDashboardHttpsIsActive() {
|
||||
val result = computeConnectionSecurity(
|
||||
apiUrl = "http://h:8642",
|
||||
dashboardUrl = "https://h:9119",
|
||||
relayUrl = "ws://h:8767",
|
||||
relayConfigured = true,
|
||||
activeEndpoint = endpoint("lan"),
|
||||
isTailscaleDetected = false,
|
||||
dashboardInUse = true,
|
||||
apiInUse = false,
|
||||
apiAvailable = false,
|
||||
relayInUse = false,
|
||||
)
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Tls, result.level)
|
||||
assertEquals(
|
||||
listOf(SurfaceUseState.InUse, SurfaceUseState.Unavailable, SurfaceUseState.Unavailable),
|
||||
result.surfaces.map { it.useState },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun distinctSurfaceOwners_classifyDashboardApiAndRelayIndependently() {
|
||||
val result = computeConnectionSecurity(
|
||||
apiUrl = "http://100.64.0.10:8642",
|
||||
dashboardUrl = "https://hermes.example.com",
|
||||
relayUrl = "ws://192.168.1.10:8767",
|
||||
relayConfigured = true,
|
||||
activeEndpoint = endpoint("public"),
|
||||
apiEndpoint = endpoint("tailscale"),
|
||||
relayEndpoint = endpoint("lan"),
|
||||
isTailscaleDetected = false,
|
||||
dashboardInUse = true,
|
||||
apiInUse = true,
|
||||
relayInUse = true,
|
||||
)
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Mixed, result.level)
|
||||
assertEquals(
|
||||
listOf("TLS", "Tailscale", "Plain"),
|
||||
result.surfaces.map { it.mechanism },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun relaySecurityUsesRelayWinnerNotDashboardWinner() {
|
||||
val result = computeConnectionSecurity(
|
||||
apiUrl = "",
|
||||
dashboardUrl = "http://192.168.1.10:9119",
|
||||
relayUrl = "ws://100.71.0.1:8767",
|
||||
relayConfigured = true,
|
||||
activeEndpoint = endpoint("lan"),
|
||||
relayEndpoint = endpoint("tailscale"),
|
||||
isTailscaleDetected = false,
|
||||
dashboardInUse = false,
|
||||
apiInUse = false,
|
||||
relayInUse = true,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"Tailscale",
|
||||
result.surfaces.single { it.label == "Relay tools" }.mechanism,
|
||||
)
|
||||
assertEquals(ConnectionSecurityLevel.Overlay, result.level)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class EndpointPresentationTest {
|
||||
@Test
|
||||
fun `authenticated dashboard role never exposes its internal key`() {
|
||||
val candidate = EndpointCandidate(
|
||||
role = "authenticated_dashboard",
|
||||
dashboard = DashboardEndpoint("https://hermes.example.com"),
|
||||
)
|
||||
|
||||
assertEquals("HTTPS Dashboard", candidate.displayLabel())
|
||||
assertTrue(candidate.isKnownRole())
|
||||
assertTrue(candidate.isDashboardOnlyRoute())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown transport is a custom route not a vpn`() {
|
||||
val candidate = EndpointCandidate(
|
||||
role = "reverse-proxy-west",
|
||||
dashboard = DashboardEndpoint("https://west.example.com"),
|
||||
api = ApiEndpoint("west.example.com", 8642, tls = true),
|
||||
)
|
||||
|
||||
assertEquals("Custom route (reverse-proxy-west)", candidate.displayLabel())
|
||||
assertFalse(candidate.isDashboardOnlyRoute())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ProactiveInboxStoreTest {
|
||||
|
||||
@Test
|
||||
fun `remove thread matches the rendered connection row and preserves other rows`() = runBlocking {
|
||||
val repository = ProactiveInboxRepository(InMemoryPreferencesDataStore())
|
||||
repository.add(entry("owned", "reminders", "connection-a", notificationId = 42))
|
||||
repository.add(entry("legacy", "reminders", null))
|
||||
repository.add(entry("other-connection", "reminders", "connection-b"))
|
||||
repository.add(entry("other-thread", "updates", "connection-a"))
|
||||
|
||||
val removed = repository.removeThread("reminders", "connection-a")
|
||||
|
||||
assertEquals(setOf("owned", "legacy"), removed.map { it.id }.toSet())
|
||||
assertEquals(listOf(42), removed.mapNotNull { it.notificationId })
|
||||
assertEquals(
|
||||
setOf("other-connection", "other-thread"),
|
||||
repository.entries.first().map { it.id }.toSet(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blank chat id removes only the local phone fallback row`() = runBlocking {
|
||||
val repository = ProactiveInboxRepository(InMemoryPreferencesDataStore())
|
||||
repository.add(entry("default", null, "connection-a"))
|
||||
repository.add(entry("named", "reminders", "connection-a"))
|
||||
|
||||
repository.removeThread("phone", "connection-a")
|
||||
|
||||
assertEquals(listOf("named"), repository.entries.first().map { it.id })
|
||||
}
|
||||
|
||||
private fun entry(
|
||||
id: String,
|
||||
chatId: String?,
|
||||
connectionId: String?,
|
||||
notificationId: Int? = null,
|
||||
) =
|
||||
ProactiveInboxEntry(
|
||||
id = id,
|
||||
title = "Hermes",
|
||||
text = id,
|
||||
receivedAt = 1L,
|
||||
chatId = chatId,
|
||||
connectionId = connectionId,
|
||||
notificationId = notificationId,
|
||||
)
|
||||
|
||||
private class InMemoryPreferencesDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow<Preferences>(emptyPreferences())
|
||||
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(
|
||||
transform: suspend (t: Preferences) -> Preferences,
|
||||
): Preferences {
|
||||
val next = transform(state.value)
|
||||
state.value = next
|
||||
return next
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class ProfileSessionStoreTest {
|
||||
|
||||
private val store = ProfileSessionStore(InMemoryPreferencesDataStore())
|
||||
private val dataStore = InMemoryPreferencesDataStore()
|
||||
private val store = ProfileSessionStore(dataStore)
|
||||
|
||||
@Test
|
||||
fun setAndGet_defaultProfileSession() = runBlocking {
|
||||
@@ -85,6 +86,26 @@ class ProfileSessionStoreTest {
|
||||
assertEquals("session-sse", store.sessionIdFlow("conn-1", "mizu", SSE).first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearedDraftSurvivesStoreRecreationAndPreservesOtherScopes() = runBlocking {
|
||||
store.setSessionId("conn-1", "mizu", GATEWAY, "session-gw")
|
||||
store.setSessionId("conn-1", "mizu", SSE, "session-sse")
|
||||
store.setSessionId("conn-2", "mizu", GATEWAY, "session-other")
|
||||
|
||||
store.setSessionId("conn-1", "mizu", GATEWAY, null)
|
||||
val restartedStore = ProfileSessionStore(dataStore)
|
||||
|
||||
assertNull(restartedStore.sessionIdFlow("conn-1", "mizu", GATEWAY).first())
|
||||
assertEquals(
|
||||
"session-sse",
|
||||
restartedStore.sessionIdFlow("conn-1", "mizu", SSE).first(),
|
||||
)
|
||||
assertEquals(
|
||||
"session-other",
|
||||
restartedStore.sessionIdFlow("conn-2", "mizu", GATEWAY).first(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearConnectionRemovesAllProfilesAndTransportsForThatConnectionOnly() = runBlocking {
|
||||
store.setSessionId("conn-1", null, GATEWAY, "session-default")
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RelayEndpointContractTest {
|
||||
@@ -38,6 +40,26 @@ class RelayEndpointContractTest {
|
||||
assertEquals(first, RelayEndpointContract.parseOrNull(first.healthUrl))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard plugin ingress is recognized across canonical route forms`() {
|
||||
val base = "https://dashboard.example.test/api/plugins/hermes-relay/transport"
|
||||
|
||||
assertTrue(isDashboardRelayIngressUrl(base))
|
||||
assertTrue(isDashboardRelayIngressUrl(base.replace("https://", "wss://") + "/ws"))
|
||||
assertTrue(isDashboardRelayIngressUrl("$base/health"))
|
||||
assertTrue(
|
||||
isDashboardRelayIngressUrl(
|
||||
"wss://dashboard.example.test/base/api/plugins/hermes-relay/transport/ws",
|
||||
),
|
||||
)
|
||||
assertFalse(isDashboardRelayIngressUrl("wss://dashboard.example.test/relay/ws"))
|
||||
assertFalse(
|
||||
isDashboardRelayIngressUrl(
|
||||
"wss://dashboard.example.test/not-api/plugins/hermes-relay/transportish/ws",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unsafe or malformed relay inputs fail closed`() {
|
||||
listOf(
|
||||
|
||||
@@ -51,4 +51,27 @@ class DiagnosticsLogTest {
|
||||
fun sanitizeUrlHandlesBlank() {
|
||||
assertNull(DiagnosticsLog.sanitizeUrl(" "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun supportTextIsBoundedAndReappliesSecretRedaction() {
|
||||
val entries = (1..85).map { index ->
|
||||
DiagnosticLogEntry(
|
||||
timestampMs = index.toLong(),
|
||||
category = DiagnosticCategory.Auth,
|
||||
severity = DiagnosticSeverity.Info,
|
||||
title = "Auth $index",
|
||||
detail = "token=secret-$index",
|
||||
operation = "dashboard_native_pkce",
|
||||
configuredUrl = "https://private.example.test/path?token=secret-$index",
|
||||
)
|
||||
}
|
||||
|
||||
val text = DiagnosticsLog.supportText(entries)
|
||||
|
||||
assertEquals(80, Regex("===== Diagnostic ").findAll(text).count())
|
||||
assertFalse(text.contains("secret-"))
|
||||
assertFalse(text.contains("private.example.test"))
|
||||
assertFalse(text.contains("Auth 1\n"))
|
||||
assertTrue(text.contains("Auth 85"))
|
||||
}
|
||||
}
|
||||
|
||||
+393
-1
@@ -5,15 +5,22 @@ import android.net.ConnectivityManager
|
||||
import com.hermesandroid.relay.data.ApiEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpoint
|
||||
import com.hermesandroid.relay.data.DashboardEndpoint
|
||||
import com.hermesandroid.relay.network.shared.EndpointResolver
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okhttp3.mockwebserver.Dispatcher
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okhttp3.mockwebserver.RecordedRequest
|
||||
import okhttp3.mockwebserver.SocketPolicy
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
@@ -27,6 +34,9 @@ import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowNetwork
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
/**
|
||||
* Standard-route (no relay socket) coverage for [ConnectionManager]'s ADR 24
|
||||
@@ -63,7 +73,7 @@ class ConnectionManagerRouteTest {
|
||||
server = MockWebServer()
|
||||
server.dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse =
|
||||
if (request.path?.endsWith("/health") == true) {
|
||||
if (request.path?.endsWith("/health") == true || request.path == "/api/status") {
|
||||
MockResponse().setResponseCode(200)
|
||||
} else {
|
||||
MockResponse().setResponseCode(404)
|
||||
@@ -91,14 +101,29 @@ class ConnectionManagerRouteTest {
|
||||
)
|
||||
|
||||
private fun buildManager(
|
||||
relayCandidateEligibility: (EndpointCandidate) -> Boolean = { true },
|
||||
dashboardRelayRequestProvider: (suspend (String) -> Request?)? = null,
|
||||
candidates: () -> List<EndpointCandidate>,
|
||||
): ConnectionManager = ConnectionManager(
|
||||
ChannelMultiplexer(),
|
||||
context = context,
|
||||
endpointResolver = EndpointResolver(httpClient = OkHttpClient()),
|
||||
endpointCandidatesProvider = { candidates() },
|
||||
relayCandidateEligibility = relayCandidateEligibility,
|
||||
dashboardRelayRequestProvider = dashboardRelayRequestProvider,
|
||||
).also { managers.add(it) }
|
||||
|
||||
private fun ingressRoute(
|
||||
role: String,
|
||||
priority: Int,
|
||||
): EndpointCandidate = EndpointCandidate(
|
||||
role = role,
|
||||
priority = priority,
|
||||
relay = RelayEndpoint(
|
||||
"ws://${server.hostName}:${server.port}/$role/api/plugins/hermes-relay/transport",
|
||||
),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `network callback registers at construction without connect`() {
|
||||
val before = registeredCallbacks()
|
||||
@@ -177,6 +202,57 @@ class ConnectionManagerRouteTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `initial Relay resolution skips higher priority ineligible ingress`() {
|
||||
val requestUrl = CompletableDeferred<String>()
|
||||
val tailscale = ingressRoute("tailscale", priority = 0)
|
||||
val public = ingressRoute("public", priority = 1)
|
||||
val manager = buildManager(
|
||||
candidates = { listOf(tailscale, public) },
|
||||
relayCandidateEligibility = { it.role == "public" },
|
||||
dashboardRelayRequestProvider = { url ->
|
||||
requestUrl.complete(url)
|
||||
Request.Builder().url("$url?ticket=public-ticket").build()
|
||||
},
|
||||
)
|
||||
manager.setInsecureMode(true)
|
||||
|
||||
manager.connect(public.relay!!.url)
|
||||
|
||||
val winner = runBlocking {
|
||||
withTimeout(10_000) { manager.activeRelayEndpoint.first { it?.role == "public" } }
|
||||
}
|
||||
assertEquals("public", winner?.role)
|
||||
assertEquals(
|
||||
public.relay!!.url.trimEnd('/') + "/ws",
|
||||
runBlocking { withTimeout(10_000) { requestUrl.await() } },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `explicit re-resolve re-evaluates dynamic Relay eligibility`() {
|
||||
val allowedRole = AtomicReference("public")
|
||||
val tailscale = ingressRoute("tailscale", priority = 0)
|
||||
val public = ingressRoute("public", priority = 1)
|
||||
val manager = buildManager(
|
||||
candidates = { listOf(tailscale, public) },
|
||||
relayCandidateEligibility = { it.role == allowedRole.get() },
|
||||
dashboardRelayRequestProvider = { url ->
|
||||
Request.Builder().url("$url?ticket=test-ticket").build()
|
||||
},
|
||||
)
|
||||
manager.setInsecureMode(true)
|
||||
manager.connect(public.relay!!.url)
|
||||
runBlocking {
|
||||
withTimeout(10_000) { manager.activeRelayEndpoint.first { it?.role == "public" } }
|
||||
}
|
||||
|
||||
allowedRole.set("tailscale")
|
||||
runBlocking { manager.probeAndReconnectNow() }
|
||||
|
||||
assertEquals("tailscale", manager.activeRelayEndpoint.value?.role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `probeAndReconnectNow publishes null when every route fails its probe`() {
|
||||
val manager = buildManager { listOf(candidate()) }
|
||||
@@ -197,6 +273,141 @@ class ConnectionManagerRouteTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed Dashboard candidate is not probed again as Standard fallback`() {
|
||||
server.dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse = when (request.path) {
|
||||
"/api/health" -> MockResponse().setResponseCode(404)
|
||||
"/api/status" -> MockResponse().setResponseCode(503)
|
||||
"/health" -> MockResponse().setResponseCode(200)
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
val dashboardRoute = EndpointCandidate(
|
||||
role = "lan",
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint(server.url("/").toString().trimEnd('/')),
|
||||
api = ApiEndpoint(host = server.hostName, port = server.port, tls = false),
|
||||
)
|
||||
val manager = buildManager { listOf(dashboardRoute) }
|
||||
|
||||
val winner = runBlocking { manager.resolveBestEndpoint() }
|
||||
|
||||
assertNull("a failed Dashboard probe must not select the route", winner)
|
||||
assertEquals(
|
||||
"Standard fallback must not repeat the Dashboard health/fallback probe pair",
|
||||
2,
|
||||
server.requestCount,
|
||||
)
|
||||
assertEquals("/api/health", server.takeRequest(1, TimeUnit.SECONDS)?.path)
|
||||
assertEquals("/api/status", server.takeRequest(1, TimeUnit.SECONDS)?.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `API-only legacy candidate remains eligible for Standard fallback`() {
|
||||
val legacyRoute = EndpointCandidate(
|
||||
role = "legacy-api",
|
||||
priority = 0,
|
||||
api = ApiEndpoint(host = server.hostName, port = server.port, tls = false),
|
||||
)
|
||||
val manager = buildManager { listOf(legacyRoute) }
|
||||
|
||||
val winner = runBlocking { manager.resolveBestEndpoint() }
|
||||
|
||||
assertEquals("legacy-api", winner?.role)
|
||||
assertEquals(1, server.requestCount)
|
||||
assertEquals("/health", server.takeRequest(1, TimeUnit.SECONDS)?.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `optional API timeout does not block healthy Dashboard refresh and is deduplicated`() {
|
||||
val slowApi = MockWebServer().apply {
|
||||
enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE))
|
||||
start()
|
||||
}
|
||||
val route = EndpointCandidate(
|
||||
role = "lan",
|
||||
priority = 0,
|
||||
dashboard = DashboardEndpoint(server.url("/").toString().trimEnd('/')),
|
||||
api = ApiEndpoint(host = slowApi.hostName, port = slowApi.port, tls = false),
|
||||
)
|
||||
val manager = buildManager { listOf(route) }
|
||||
|
||||
try {
|
||||
val firstElapsed = measureTimeMillis {
|
||||
val winner = runBlocking { manager.refreshActiveEndpoint() }
|
||||
assertEquals("lan", winner?.role)
|
||||
}
|
||||
assertEquals("the healthy Dashboard route must publish immediately", "lan", manager.activeEndpoint.value?.role)
|
||||
org.junit.Assert.assertTrue(
|
||||
"optional API discovery must not add its four-second timeout to Dashboard readiness (elapsed=${firstElapsed}ms)",
|
||||
firstElapsed < 1_500L,
|
||||
)
|
||||
assertNotNull("background API discovery should still run", slowApi.takeRequest(2, TimeUnit.SECONDS))
|
||||
|
||||
val secondElapsed = measureTimeMillis {
|
||||
runBlocking { manager.refreshActiveEndpoint() }
|
||||
}
|
||||
org.junit.Assert.assertTrue(
|
||||
"a concurrent refresh must not wait for the in-flight optional probe (elapsed=${secondElapsed}ms)",
|
||||
secondElapsed < 1_500L,
|
||||
)
|
||||
assertEquals("the in-flight optional probe must be coalesced", 1, slowApi.requestCount)
|
||||
} finally {
|
||||
slowApi.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale optional API probe cannot publish over a newer route set`() {
|
||||
val slowApi = MockWebServer().apply {
|
||||
enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE))
|
||||
start()
|
||||
}
|
||||
val fastApi = MockWebServer().apply {
|
||||
enqueue(MockResponse().setResponseCode(200))
|
||||
start()
|
||||
}
|
||||
var routes = listOf(
|
||||
EndpointCandidate(
|
||||
role = "connection-a",
|
||||
dashboard = DashboardEndpoint(server.url("/").toString().trimEnd('/')),
|
||||
api = ApiEndpoint(slowApi.hostName, slowApi.port, tls = false),
|
||||
),
|
||||
)
|
||||
val manager = buildManager { routes }
|
||||
|
||||
try {
|
||||
runBlocking { manager.refreshActiveEndpoint() }
|
||||
assertNotNull(slowApi.takeRequest(2, TimeUnit.SECONDS))
|
||||
|
||||
routes = listOf(
|
||||
EndpointCandidate(
|
||||
role = "connection-b",
|
||||
dashboard = DashboardEndpoint(server.url("/").toString().trimEnd('/')),
|
||||
api = ApiEndpoint(fastApi.hostName, fastApi.port, tls = false),
|
||||
),
|
||||
)
|
||||
runBlocking { manager.refreshActiveEndpoint() }
|
||||
|
||||
val current = runBlocking {
|
||||
withTimeout(10_000L) {
|
||||
manager.activeApiEndpoint.first { it?.role == "connection-b" }
|
||||
}
|
||||
}
|
||||
assertEquals("connection-b", current?.role)
|
||||
assertEquals(
|
||||
"the completed stale probe must never become active while the current route resolves",
|
||||
"connection-b",
|
||||
manager.activeApiEndpoint.value?.role,
|
||||
)
|
||||
assertEquals(1, fastApi.requestCount)
|
||||
} finally {
|
||||
slowApi.shutdown()
|
||||
fastApi.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `route qualified input opens canonical websocket without double append`() {
|
||||
val manager = ConnectionManager(ChannelMultiplexer()).also { managers.add(it) }
|
||||
@@ -208,4 +419,185 @@ class ConnectionManagerRouteTest {
|
||||
assertNotNull(request)
|
||||
assertEquals("/relay/ws", request!!.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fresh pairing dials supplied websocket before relay health resolution`() {
|
||||
val manager = buildManager { listOf(candidate(role = "slow-health")) }
|
||||
manager.setInsecureMode(true)
|
||||
|
||||
manager.connectPairing("ws://${server.hostName}:${server.port}")
|
||||
|
||||
val request = server.takeRequest(5, TimeUnit.SECONDS)
|
||||
assertNotNull(request)
|
||||
assertEquals("/ws", request!!.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard relay ingress asks for a fresh authorized request per dial`() {
|
||||
val requestCount = AtomicInteger(0)
|
||||
val manager = ConnectionManager(
|
||||
ChannelMultiplexer(),
|
||||
dashboardRelayRequestProvider = { url ->
|
||||
val ticket = requestCount.incrementAndGet()
|
||||
Request.Builder().url("$url?ticket=ticket-$ticket").build()
|
||||
},
|
||||
).also { managers.add(it) }
|
||||
manager.setInsecureMode(true)
|
||||
val ingress = "ws://${server.hostName}:${server.port}" +
|
||||
"/api/plugins/hermes-relay/transport/ws"
|
||||
|
||||
manager.connect(ingress)
|
||||
val first = server.takeRequest(5, TimeUnit.SECONDS)
|
||||
manager.disconnect()
|
||||
manager.connect(ingress)
|
||||
val second = server.takeRequest(5, TimeUnit.SECONDS)
|
||||
|
||||
assertEquals(2, requestCount.get())
|
||||
assertEquals(
|
||||
"/api/plugins/hermes-relay/transport/ws?ticket=ticket-1",
|
||||
first?.path,
|
||||
)
|
||||
assertEquals(
|
||||
"/api/plugins/hermes-relay/transport/ws?ticket=ticket-2",
|
||||
second?.path,
|
||||
)
|
||||
}
|
||||
|
||||
private fun ingressCandidate(priority: Int = 0) = EndpointCandidate(
|
||||
role = "dashboard-ingress",
|
||||
priority = priority,
|
||||
relay = RelayEndpoint(
|
||||
"ws://${server.hostName}:${server.port}/api/plugins/hermes-relay/transport",
|
||||
),
|
||||
)
|
||||
|
||||
private fun directCandidate(priority: Int = 1) = EndpointCandidate(
|
||||
role = "direct",
|
||||
priority = priority,
|
||||
relay = RelayEndpoint("ws://${server.hostName}:${server.port}"),
|
||||
)
|
||||
|
||||
private fun ingressFallbackManager(
|
||||
requestProvider: (suspend (String) -> Request?)?,
|
||||
): ConnectionManager = ConnectionManager(
|
||||
ChannelMultiplexer(),
|
||||
context = context,
|
||||
endpointResolver = EndpointResolver(httpClient = OkHttpClient()),
|
||||
endpointCandidatesProvider = { listOf(ingressCandidate(), directCandidate()) },
|
||||
dashboardRelayRequestProvider = requestProvider,
|
||||
).also {
|
||||
managers.add(it)
|
||||
it.setInsecureMode(true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing dashboard ingress request provider falls back to direct relay`() {
|
||||
val manager = ingressFallbackManager(requestProvider = null)
|
||||
|
||||
manager.connect("ws://${server.hostName}:${server.port}")
|
||||
|
||||
val winner = runBlocking {
|
||||
withTimeout(5_000) { manager.activeRelayEndpoint.first { it?.role == "direct" } }
|
||||
}
|
||||
assertEquals("direct", winner?.role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard ingress ticket failure falls back to direct relay`() {
|
||||
val manager = ingressFallbackManager(requestProvider = { null })
|
||||
|
||||
manager.connect("ws://${server.hostName}:${server.port}")
|
||||
|
||||
val winner = runBlocking {
|
||||
withTimeout(5_000) { manager.activeRelayEndpoint.first { it?.role == "direct" } }
|
||||
}
|
||||
assertEquals("direct", winner?.role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard ingress admission close falls back to direct relay`() {
|
||||
val ingressListener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
webSocket.close(4403, "admission denied")
|
||||
}
|
||||
}
|
||||
val directListener = object : WebSocketListener() {}
|
||||
server.dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse = when {
|
||||
request.path?.endsWith("/health") == true -> MockResponse().setResponseCode(200)
|
||||
request.path?.startsWith("/api/plugins/hermes-relay/transport/ws") == true ->
|
||||
MockResponse().withWebSocketUpgrade(ingressListener)
|
||||
request.path == "/ws" -> MockResponse().withWebSocketUpgrade(directListener)
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
val manager = ingressFallbackManager { url ->
|
||||
Request.Builder().url("$url?ticket=admission-ticket").build()
|
||||
}
|
||||
|
||||
manager.connect("ws://${server.hostName}:${server.port}")
|
||||
|
||||
val winner = runBlocking {
|
||||
withTimeout(5_000) { manager.activeRelayEndpoint.first { it?.role == "direct" } }
|
||||
}
|
||||
assertEquals("direct", winner?.role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale ingress close cannot poison successful same-url replacement`() {
|
||||
val fallbackStarted = CompletableDeferred<Unit>()
|
||||
val releaseFallback = CompletableDeferred<Unit>()
|
||||
val replacementOpened = CompletableDeferred<Unit>()
|
||||
val ingressSockets = AtomicInteger(0)
|
||||
val ticketRequests = AtomicInteger(0)
|
||||
server.dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse = when {
|
||||
request.path?.endsWith("/health") == true -> MockResponse().setResponseCode(200)
|
||||
request.path?.startsWith("/api/plugins/hermes-relay/transport/ws") == true -> {
|
||||
val number = ingressSockets.incrementAndGet()
|
||||
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
if (number == 1) {
|
||||
webSocket.close(4403, "old admission denied")
|
||||
} else {
|
||||
webSocket.send(
|
||||
"""{"channel":"system","type":"auth.ok","payload":{}}""",
|
||||
)
|
||||
replacementOpened.complete(Unit)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
val manager = ConnectionManager(
|
||||
ChannelMultiplexer(),
|
||||
context = context,
|
||||
endpointResolver = EndpointResolver(httpClient = OkHttpClient()),
|
||||
endpointCandidatesProvider = { listOf(ingressCandidate(), directCandidate()) },
|
||||
dashboardRelayRequestProvider = { url ->
|
||||
val ticket = ticketRequests.incrementAndGet()
|
||||
Request.Builder().url("$url?ticket=ticket-$ticket").build()
|
||||
},
|
||||
beforeIngressFailureCommit = {
|
||||
fallbackStarted.complete(Unit)
|
||||
releaseFallback.await()
|
||||
},
|
||||
).also {
|
||||
managers.add(it)
|
||||
it.setInsecureMode(true)
|
||||
}
|
||||
|
||||
manager.connect("ws://${server.hostName}:${server.port}")
|
||||
runBlocking { withTimeout(5_000) { fallbackStarted.await() } }
|
||||
assertEquals(true, manager.reconnectForAuthenticatedMetadataUpdate())
|
||||
runBlocking { withTimeout(5_000) { replacementOpened.await() } }
|
||||
releaseFallback.complete(Unit)
|
||||
Thread.sleep(100)
|
||||
|
||||
assertEquals("dashboard-ingress", manager.activeRelayEndpoint.value?.role)
|
||||
assertEquals(ConnectionState.Connected, manager.connectionState.value)
|
||||
assertEquals(2, ticketRequests.get())
|
||||
}
|
||||
}
|
||||
|
||||
+19
@@ -2,6 +2,8 @@ package com.hermesandroid.relay.network.relay
|
||||
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertEquals
|
||||
import okhttp3.Request
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
@@ -36,4 +38,21 @@ class ConnectionManagerUrlGuardTest {
|
||||
assertNull("expected null for malformed relay url '$bad'", buildRelayRequestOrNull(bad))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `relay credential uses a separate header only for dashboard ingress`() {
|
||||
val ingress = Request.Builder()
|
||||
.url("https://dashboard.example.test/api/plugins/hermes-relay/transport/health")
|
||||
.relaySessionCredential("relay-session", dashboardIngress = true)
|
||||
.build()
|
||||
val direct = Request.Builder()
|
||||
.url("https://relay.example.test/health")
|
||||
.relaySessionCredential("relay-session", dashboardIngress = false)
|
||||
.build()
|
||||
|
||||
assertEquals("relay-session", ingress.header(RELAY_SESSION_HEADER))
|
||||
assertNull(ingress.header("Authorization"))
|
||||
assertEquals("Bearer relay-session", direct.header("Authorization"))
|
||||
assertNull(direct.header(RELAY_SESSION_HEADER))
|
||||
}
|
||||
}
|
||||
|
||||
+5
-4
@@ -3,9 +3,7 @@ package com.hermesandroid.relay.network.relay
|
||||
import android.content.Context
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import com.hermesandroid.relay.notifications.ProactiveMessageNotifier
|
||||
import io.mockk.Runs
|
||||
import io.mockk.every
|
||||
import io.mockk.just
|
||||
import io.mockk.mockk
|
||||
import io.mockk.mockkObject
|
||||
import io.mockk.unmockkObject
|
||||
@@ -26,7 +24,7 @@ class ProactiveMessageHandlerTest {
|
||||
mockkObject(ProactiveMessageNotifier)
|
||||
every {
|
||||
ProactiveMessageNotifier.notify(any(), any(), any(), any(), any())
|
||||
} just Runs
|
||||
} returns 42
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -44,6 +42,7 @@ class ProactiveMessageHandlerTest {
|
||||
handler.onMessage(messageEnvelope(surfacing = "notification"))
|
||||
|
||||
assertEquals(1, persisted.size)
|
||||
assertEquals(42, persisted.single().notificationId)
|
||||
verify(exactly = 1) {
|
||||
ProactiveMessageNotifier.notify(context, "Hermes", "ready", "m-1", "phone")
|
||||
}
|
||||
@@ -51,7 +50,8 @@ class ProactiveMessageHandlerTest {
|
||||
|
||||
@Test
|
||||
fun `inbox surfacing persists silently`() {
|
||||
val handler = ProactiveMessageHandler(context, toInbox = {}).apply {
|
||||
val persisted = mutableListOf<ProactiveMessage>()
|
||||
val handler = ProactiveMessageHandler(context, toInbox = persisted::add).apply {
|
||||
injectIntoThread = { true }
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ class ProactiveMessageHandlerTest {
|
||||
verify(exactly = 0) {
|
||||
ProactiveMessageNotifier.notify(any(), any(), any(), any(), any())
|
||||
}
|
||||
assertEquals(null, persisted.single().notificationId)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+83
@@ -10,9 +10,11 @@ import okhttp3.mockwebserver.MockWebServer
|
||||
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.Test
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
class RelayHttpClientDiagnosticsTest {
|
||||
@Before
|
||||
@@ -75,4 +77,85 @@ class RelayHttpClientDiagnosticsTest {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardIngressUsesOuterAuthClientAndSeparateRelayHeader() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.enqueue(MockResponse().setResponseCode(200).setBody("""{"sessions":[]}"""))
|
||||
server.start()
|
||||
try {
|
||||
val ingress = "http://${server.hostName}:${server.port}" +
|
||||
"/api/plugins/hermes-relay/transport"
|
||||
val providerCalls = AtomicInteger(0)
|
||||
val outerAuthClient = OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
chain.proceed(
|
||||
chain.request().newBuilder()
|
||||
.header("X-Dashboard-Test-Auth", "ready")
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
.build()
|
||||
val client = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { ingress },
|
||||
sessionTokenProvider = { "relay-session" },
|
||||
dashboardHttpClientProvider = {
|
||||
providerCalls.incrementAndGet()
|
||||
outerAuthClient
|
||||
},
|
||||
)
|
||||
|
||||
assertTrue(client.listSessions().isSuccess)
|
||||
val request = server.takeRequest()
|
||||
assertEquals(1, providerCalls.get())
|
||||
assertEquals("/api/plugins/hermes-relay/transport/sessions", request.path)
|
||||
assertEquals("ready", request.getHeader("X-Dashboard-Test-Auth"))
|
||||
assertEquals("relay-session", request.getHeader(RELAY_SESSION_HEADER))
|
||||
assertNull(request.getHeader("Authorization"))
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardIngressHealthTimeoutClientDerivesFromOuterAuthClient() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(200).setBody(
|
||||
"""{"status":"ok","version":"1.0.0","clients":0,"sessions":0}""",
|
||||
),
|
||||
)
|
||||
server.start()
|
||||
try {
|
||||
val ingress = "http://${server.hostName}:${server.port}" +
|
||||
"/api/plugins/hermes-relay/transport"
|
||||
val providerCalls = AtomicInteger(0)
|
||||
val client = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { ingress },
|
||||
sessionTokenProvider = { null },
|
||||
dashboardHttpClientProvider = {
|
||||
providerCalls.incrementAndGet()
|
||||
OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
chain.proceed(
|
||||
chain.request().newBuilder()
|
||||
.header("X-Dashboard-Test-Auth", "ready")
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
.build()
|
||||
},
|
||||
)
|
||||
|
||||
assertTrue(client.probeHealth(ingress).isSuccess)
|
||||
val request = server.takeRequest()
|
||||
assertEquals(1, providerCalls.get())
|
||||
assertEquals("ready", request.getHeader("X-Dashboard-Test-Auth"))
|
||||
assertEquals("/api/plugins/hermes-relay/transport/health", request.path)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user