Compare commits

...
Author SHA1 Message Date
Bailey Dixon 447ec356d7 Merge pull request #359 from Codename-11/dev
release(android): android-v1.9.0
2026-08-14 21:32:50 -04:00
Bailey Dixon ab359e5efb release(android): android-v1.9.0 2026-08-14 21:01:51 -04:00
Bailey Dixon 86b8161cb7 feat(android): refine sessions and messaging 2026-08-14 20:58:31 -04:00
Bailey Dixon e401fdb0c7 fix(android): persist landed message reactions 2026-08-14 17:04:54 -04:00
Bailey Dixon d4325d5aab fix(android): restore compact chat interactions 2026-08-14 16:57:19 -04:00
Bailey Dixon c734d75484 feat(android): add desktop-style session profiles 2026-08-14 16:57:18 -04:00
Bailey Dixon 0411804780 fix(android): accept compatible session flags 2026-08-14 16:57:18 -04:00
Bailey Dixon 8f89c2841d fix(android): keep dashboard teardown off main thread 2026-08-14 16:57:18 -04:00
Bailey Dixon 933c1842a0 Merge pull request #358 from Codename-11/chore/backmerge-desktop-beta3
chore: back-merge Desktop beta.3 release
2026-08-14 16:31:24 -04:00
Bailey Dixon dfe1b53327 chore: back-merge desktop beta.3 release 2026-08-14 16:30:37 -04:00
Bailey Dixon d36580a983 Merge pull request #356 from Codename-11/dev
release: Desktop beta.3 process-containment patch
2026-08-14 16:11:35 -04:00
Bailey Dixon 2d178ff884 Merge pull request #357 from Codename-11/release/desktop-0.4.0-beta.3
fix(desktop): close process containment race
2026-08-14 16:05:00 -04:00
Bailey Dixon d61955f82a fix(desktop): close process containment race 2026-08-14 15:58:57 -04:00
Bailey Dixon adec6ed2c0 Merge pull request #355 from Codename-11/release/desktop-0.4.0-beta.3
release(desktop): desktop-v0.4.0-beta.3
2026-08-14 15:44:24 -04:00
Bailey Dixon e9e44c8bb2 release(desktop): desktop-v0.4.0-beta.3 2026-08-14 15:36:53 -04:00
Bailey Dixon c6b0732a02 Merge pull request #354 from Codename-11/fix/desktop-tray-process-containment
fix(desktop): contain tray subprocess storms
2026-08-14 15:22:21 -04:00
Bailey Dixon d919115788 fix(desktop): contain tray subprocess storms 2026-08-14 15:15:12 -04:00
Bailey Dixon 49da085ae8 Merge pull request #353 from Codename-11/chore/backmerge-desktop-beta2-server-1.8.0
chore: backmerge Desktop beta.2 and Server 1.8.0 releases
2026-08-14 15:05:21 -04:00
Bailey Dixon 889b6f0858 chore: merge desktop beta.2 and server 1.8.0 release history into dev 2026-08-14 15:05:12 -04:00
Bailey Dixon 5100c524f6 Merge pull request #351 from Codename-11/dev
release: Desktop beta.2 and Server 1.8.0
2026-08-14 15:04:03 -04:00
Bailey Dixon c609ae867f Merge pull request #352 from Codename-11/chore/backmerge-desktop-beta1
chore: back-merge Desktop beta.1 release history
2026-08-14 14:49:23 -04:00
Bailey Dixon 107f8c7720 chore: merge desktop beta.1 release history into dev 2026-08-14 14:49:08 -04:00
Bailey Dixon 8963e4fafd Merge pull request #350 from Codename-11/release/server-1.8.0
release(server): server-v1.8.0
2026-08-14 14:46:57 -04:00
Bailey Dixon 5d9624e2ef release(server): server-v1.8.0 2026-08-14 14:35:01 -04:00
Bailey Dixon 4b063d3fd7 Merge pull request #349 from Codename-11/release/desktop-0.4.0-beta.2
release(desktop): desktop-v0.4.0-beta.2
2026-08-14 12:56:04 -04:00
Bailey Dixon 9b9d7b654c release(desktop): desktop-v0.4.0-beta.2 2026-08-14 12:45:56 -04:00
Bailey Dixon a26e17e72c Merge pull request #348 from Codename-11/fix/cua-windows-health-compat
feat(desktop): enhance activity and control diagnostics
2026-08-14 12:38:12 -04:00
Bailey Dixon a3a6a9bb13 fix(desktop): satisfy tray release lint 2026-08-14 12:36:46 -04:00
Bailey Dixon 169bd09559 merge: sync desktop activity work with dev
# Conflicts:
#	CHANGELOG.md
2026-08-14 11:32:56 -04:00
Bailey Dixon 45d631e7ac feat(desktop): enhance activity and control diagnostics 2026-08-14 11:30:36 -04:00
Bailey Dixon eb6a6c95d2 merge: integrate official desktop relay plugin 2026-08-14 07:58:10 -04:00
Bailey Dixon 3b102663c2 feat(plugin): add official desktop relay surface 2026-08-14 07:56:26 -04:00
Bailey Dixon 0e5fc4c606 Merge branch 'fix/android-proactive-thread-entry' into dev 2026-08-14 07:50:07 -04:00
Bailey Dixon c3189f2cbb fix(android): open proactive messages as threads 2026-08-14 07:49:39 -04:00
Bailey Dixon 0d6c3bd6b0 Merge pull request #346 from Codename-11/dev
release(desktop): desktop-v0.4.0-beta.1
2026-08-13 21:18:41 -04:00
Bailey Dixon 06d88ad40a Merge pull request #345 from Codename-11/release/desktop-0.4.0-beta.1
release(desktop): desktop-v0.4.0-beta.1
2026-08-13 21:11:57 -04:00
Bailey Dixon 8ae5b3fbc2 release(desktop): desktop-v0.4.0-beta.1 2026-08-13 21:04:07 -04:00
Bailey Dixon 39b7a8f108 Merge pull request #344 from Codename-11/fix/desktop-updater-cua-hardening
feat(desktop): adopt CUA as primary control backend
2026-08-13 20:57:50 -04:00
Bailey Dixon af6e167692 fix(desktop): normalize Windows installer paths 2026-08-13 20:51:17 -04:00
Bailey Dixon 274bd6ae98 fix(desktop): honor CUA health schema 2026-08-13 20:45:58 -04:00
Bailey Dixon 9fc55b379a fix(desktop): clarify CUA readiness fallback 2026-08-13 20:34:45 -04:00
Bailey Dixon 559a0ffdc8 feat(desktop): make CUA the primary control backend 2026-08-13 20:16:03 -04:00
Bailey Dixon 75bcd9180f feat(desktop): add optional CUA control engine 2026-08-13 19:33:11 -04:00
Bailey Dixon 9c995a443d fix(desktop): harden bundle updates 2026-08-13 19:06:25 -04:00
Bailey Dixon 7440ef2948 Merge pull request #343 from Codename-11/dev
release: server 1.7.0 and desktop 0.4.0-alpha.8
2026-08-13 17:14:58 -04:00
Bailey Dixon a88539bc59 fix(android): dequeue reach frames compatibly 2026-08-13 16:56:54 -04:00
Bailey Dixon b2ccfdc500 fix(security): carry secure link trust anchor 2026-08-13 16:49:44 -04:00
Bailey Dixon 481c62ac59 fix(desktop): bind pinned secure link probes 2026-08-13 16:42:37 -04:00
Bailey Dixon 5d415fbaf0 fix(android): use compatible reach buffer removal 2026-08-13 16:39:26 -04:00
Bailey Dixon 074b715055 fix(android): complete secure route translations 2026-08-13 16:37:32 -04:00
Bailey Dixon f63ee8721e release(desktop): desktop-v0.4.0-alpha.8 2026-08-13 16:21:51 -04:00
Bailey Dixon 777bc80bcc release(server): server-v1.7.0 2026-08-13 16:21:50 -04:00
Bailey Dixon 9539975bb5 merge: integrate native secure routes 2026-08-13 15:41:46 -04:00
Bailey Dixon 2863a1bc8f merge: reconcile native secure routes with dev 2026-08-13 15:31:53 -04:00
Bailey Dixon b0a7cf0494 feat: add self-hosted secure connection routes 2026-08-13 15:31:46 -04:00
Bailey Dixon 76b4084310 merge: integrate Android and Relay upstream work 2026-08-13 13:24:32 -04:00
Bailey Dixon 2ace70c4fc test: close integration verification gaps 2026-08-13 13:24:02 -04:00
Bailey Dixon 4f52f371ba fix(ops): fail closed on unsafe certification state 2026-08-13 11:16:27 -04:00
Bailey Dixon 064c89bda4 docs: record Android and Relay integration 2026-08-13 11:08:27 -04:00
Bailey Dixon 0cb1e3642f feat(android): add gateway-native profile editor 2026-08-13 11:03:10 -04:00
Bailey Dixon cf4bf87242 fix(android): honor upstream routing contracts 2026-08-13 11:00:39 -04:00
Bailey Dixon 9cbed21014 fix(android): preserve durable gateway rewinds 2026-08-13 10:58:55 -04:00
Bailey Dixon ce75c0fa01 docs: add controlled runtime safety preflight 2026-08-13 10:50:52 -04:00
Bailey Dixon bf2aece6e6 docs: reconcile upstream architecture evaluations 2026-08-13 10:50:14 -04:00
Bailey Dixon 198da78fc8 fix(android): honor upstream approval and compression outcomes 2026-08-13 10:50:14 -04:00
Bailey Dixon 986ce3b12b fix(plugin): isolate profile-owned registrations 2026-08-13 10:50:14 -04:00
Bailey Dixon b53f757830 fix(plugin): support strict phone targets 2026-08-13 10:50:14 -04:00
Bailey Dixon cdeccd69e4 feat: add secure relay route selection 2026-08-12 20:10:41 -04:00
Bailey Dixon bb72516bb5 Merge pull request #340 from Codename-11/chore/backmerge-server-1.6.4
chore: back-merge server-v1.6.4 hotfix
2026-08-12 18:43:50 -04:00
Bailey Dixon 3a51644342 chore: merge server-v1.6.4 release history into dev
# Conflicts:
#	docs/decisions.md
#	user-docs/desktop/tools.md
2026-08-12 18:43:39 -04:00
Bailey Dixon 51c0c7dee9 Merge pull request #338 from Codename-11/fix/server-multidevice-hotfix
fix(server): release targeted multi-desktop routing
2026-08-12 18:39:31 -04:00
Bailey Dixon 7ef2420c85 release(server): server-v1.6.4 2026-08-12 18:38:32 -04:00
Bailey Dixon 6a810c850b fix(server): route concurrent desktop clients explicitly 2026-08-12 18:38:02 -04:00
Bailey Dixon d383002583 Merge pull request #336 from Codename-11/release/server-1.6.4
release(server): server-v1.6.4
2026-08-12 18:35:31 -04:00
222 changed files with 22254 additions and 1434 deletions
+37 -2
View File
@@ -80,7 +80,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.x'
bun-version-file: 'desktop/.bun-version'
- name: Install deps
run: npm ci
@@ -153,6 +153,40 @@ jobs:
desktop/dist/bin/hermes-relay-darwin-arm64
retention-days: 7
smoke-windows-cli-release-asset:
name: Smoke exact Windows CLI release asset
runs-on: windows-latest
needs:
- validate-release
- build-cli-binaries
steps:
- uses: actions/download-artifact@v8
with:
name: cli-binaries
path: release-assets
- name: Repeated launch and process cleanup gate
shell: pwsh
env:
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
run: |
$ErrorActionPreference = 'Stop'
$exe = (Resolve-Path 'release-assets/hermes-relay-win-x64.exe').Path
1..20 | ForEach-Object {
$output = & $exe --version
if ($LASTEXITCODE -ne 0) { throw "Windows CLI smoke failed with exit $LASTEXITCODE" }
if ($output -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
throw "Unexpected Windows CLI version output: $output"
}
}
Start-Sleep -Milliseconds 500
$leftovers = Get-CimInstance Win32_Process | Where-Object {
$_.ExecutablePath -eq $exe
}
if ($leftovers) {
throw "Windows CLI smoke left $(@($leftovers).Count) process(es) behind"
}
build-windows-tray-installer:
name: Build Windows tray installer
runs-on: windows-latest
@@ -175,7 +209,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.x'
bun-version-file: 'desktop/.bun-version'
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
@@ -375,6 +409,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build-cli-binaries
- smoke-windows-cli-release-asset
- build-windows-tray-installer
steps:
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
+88 -18
View File
@@ -6,33 +6,103 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
## [Unreleased]
## [1.9.0] - 2026-08-14
### Added
- **Windows management separates each Relay host from this PC.** Host detail is now the per-host hub for identity, connection and pairing/session metadata, access, capabilities, authorized-client deauthorization, re-pairing, and guarded removal. Settings owns local daemon lifecycle, separate UI-at-sign-in and daemon-with-UI preferences, explicit UAC elevation and return to user mode, terminal/CLI launchers, daemon logs, diagnostics, updates, and a Help & About page with version details and documentation links. Existing installs keep automatic daemon startup off until enabled.
- **Desktop access uses four clear presets.** Restricted keeps every desktop capability off, Ask Every Time requests local approval for each available operation, Standard allows files while asking for screen/input/USB and withholding raw commands, and Full Access allows every available capability without task grants. New pairings default to Ask Every Time; existing hosts keep their stored policy. Individual changes snap to an exact preset when possible and otherwise become Custom.
- **The connected-host control is visibly interactive.** The compact Agent-to-PC route now gives the selected host a labeled server icon, host identity, Change affordance, stronger card treatment, and responsive width instead of presenting the host name as a cramped status pill.
- **The connection route shows real bidirectional traffic.** Staggered data packets now travel continuously from Agent to PC and PC to Agent, pass behind the selected host as the relay hop, and stop animating when the tunnel is offline or reduced motion is requested.
- **Nested management pages have a clear return control.** Host access, capabilities, activity, and host detail views now use a bordered Back button with a larger target, visible focus treatment, and explicit destination. Access copy also spells out that Standard allows files, asks for screen/input/USB, and keeps raw commands off.
- **Desktop activity supports evidence-first drilldown.** Overview shows the latest three events; the full activity view opens each event into bounded, locally stored request, stdout, stderr, structured result, exit, timing, and truncation details with sensitive request fields excluded.
- **Android session browsing matches Hermes Desktop's recent organization model.** The primary session drawer can toggle between the active profile and all profiles, group by recency, project, status, or profile, order by supported session metrics, and narrow rows by status, project, profile, or pull-request state without collapsing duplicate IDs across profile stores. Named profiles receive stable identity-color badges with locally persisted color overrides.
- **Android can edit current Hermes profiles through the standard Gateway.** The Profile Inspector capability-gates `profiles.describe` and `profiles.configure`, keeps Relay-only memory editing and older-Hermes fallback intact, and reports partial section saves without discarding failed drafts.
- **Android sessions show their coding context when Hermes supplies it.** Session rows can display repository, Git branch, and the current state of the pull request created by that session while older hosts remain unchanged.
- Android Manage can now finish host-owned backup workflows, edit or remove learning nodes with explicit recovery guidance, configure and activate memory providers, and complete profile-scoped WhatsApp QR onboarding through the authenticated upstream Dashboard contracts.
### Changed
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients now honor explicit custom headers, custom CA bundles, the standard CA environment precedence, and an opt-in warned `ssl_verify=false` development mode without changing public-provider defaults or logging header values.
- **Voice Lab xAI sign-in uses device authorization.** The standalone xAI login now shows a verification URL and user code and polls for approval, matching upstream Hermes and removing the loopback callback/SSH-tunnel requirement while preserving existing Voice Lab token files and refresh behavior.
### Fixed
- **Ask-mode approval cards show the requested action.** A bounded command or action preview appears in the compact card, with full context in the expandable detail view and an option to review the live request in the main UI.
- **Mixed desktop capability policies are labeled Custom.** Overview no longer presents a misleading preset when individual capability controls differ.
- **Desktop pairing and connection security are explicit.** The management UI supports URL/code pairing directly and distinguishes encrypted `wss://` relay connections from unencrypted `ws://` routes.
- **Windows tray placement follows the notification-area monitor at its real DPI.** The management popup now derives responsive logical dimensions from the tray monitor's work area instead of guessing scale from the icon slot, keeping compact and high-DPI desktops consistently anchored.
- **PowerShell success output is complete and self-describing.** Scripts execute through a private UTF-8 temporary file, native exit status propagates, stdout and stderr are drained independently, and bounded output reports total, captured, and truncated bytes instead of returning unexplained empty success.
- **Phone is discoverable as a proactive delivery target.** The Relay phone adapter now publishes its configured home destination through Hermes' standard channel directory, so target listings can offer `phone` before any historical phone session exists.
- **Android network clients shut down safely during route changes.** Replacing an authenticated Dashboard client now moves OkHttp connection-pool eviction off the main thread, preventing a live TLS socket close from crashing the app with `NetworkOnMainThreadException`. (#334)
- **Android preserves authoritative Gateway outcomes.** Protected-file cards cannot offer forbidden persistent scopes, compression no-ops show the server result, bounded resume failures do not create context-free replacement sessions, and edit/regenerate retains durable row identities across consecutive rewinds.
- **Android routes and uploads against live upstream truth.** Multiplex API fallback trusts `served_profiles` instead of installed profiles, and generic documents carry the Gateway-issued `@file:` reference into ordinary and queued prompts.
- **Android clarify cards preserve upstream decision semantics.** Multi-select prompts keep independent selections and submit one exact list, while server expiry events—not an invented local deadline—retire unanswered cards.
- **Android keeps profile management and retained automation truthful.** Custom Endpoint list and mutation routes now follow the selected Hermes profile, while completed one-shot cron jobs show their retained outcome and expose only valid Runs/Delete actions.
- **Android and Relay recover more generated media reliably.** Android accepts upstream-valid wrapped, punctuated, adjacent, spaced, and Windows `MEDIA:` markers without consuming fenced examples, and Relay translates Docker-visible workspace, home, cache, and configured-mount paths before applying its existing credential, sandbox, and size checks.
- **Android keeps cross-profile sessions with their owning agent.** Opening a session from All Profiles hydrates, resumes, sends, and renders with that session's profile without changing the global profile selection; New Chat from that view starts with the default profile.
- **Android reactions and standard voice follow the active conversation.** Reactions resolve durable rows for both user and assistant messages, while Vanilla Hermes voice remains on the authenticated Gateway instead of requiring the optional API fallback.
- **Android session navigation behaves predictably.** The drawer closes on outside taps, uses an ungrouped recent-session list by default, retains project grouping as an explicit option, and exposes secondary actions in All Profiles mode.
## [0.4.0-beta.3] - 2026-08-14
### Fixed
- **Windows tray polling can no longer accumulate unbounded helper processes.** Grant discovery now uses lightweight local state, management refreshes are single-flight and visibility-aware, and child probes have hard timeouts, bounded output, tree cleanup, caching, and backoff. A dedicated bounded `tray.log` records sanitized operational failures without mixing them into daemon logs.
- **Concurrent Desktop lifecycle requests cannot start duplicate daemons.** Cross-process lifecycle and runtime ownership locks serialize startup and recovery while preserving stale-owner cleanup.
## [1.8.0] - 2026-08-14
### Added
- **Official Hermes Desktop can surface Relay through its supported runtime Plugin SDK.** The unified plugin package now includes an opt-in, profile-scoped Desktop pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management. Loading, startup, reconnects, profile changes, and updates never open it; only labeled sidebar, status-bar, or command-palette actions register and reveal the movable native pane.
## [0.4.0-beta.2] - 2026-08-14
### Added
- **Desktop Activity now keeps inspectable local evidence.** Commands, files, devices, connection lifecycle, and computer control share a truthful event stepper with dedicated failure details; screenshot events can retain bounded local PNG evidence and open it in a larger borderless viewer. Settings controls retention as Off, 1 day, 7 days, or 30 days and shows local file usage.
### Fixed
- **Tunnel state stays responsive through interruption and retry.** The CLI UI distinguishes connected, reconnecting, and stopped states, exposes retry attempt/timing and a Retry now action, records connection failures and recovery in Activity, and shows compact connection cards only while the main UI is hidden.
- **Windows CUA readiness no longer depends on the flaky whole-desktop health scan.** Hermes-Relay verifies the canonical runtime, manifest, required tools, daemon, and safe permission mode before starting structured sessions, while accessibility health remains an explicit CLI/UI diagnostic that can be rechecked without forcing the compatibility backend. This temporary workaround is scoped to the upstream fixed-timeout issue and keeps individual actions fail-closed.
## [0.4.0-beta.1] - 2026-08-14
### Added
- **CUA Driver is the preferred Windows structured-control engine.** New local settings prefer a verified CUA runtime for window-targeted background actions, fresh snapshot tokens, and optional per-session animated agent cursors without moving the physical pointer; Windows Input is the explicit compatibility backend and backend choice is fixed for each control session. Full-display observation remains on the read-only system capture path. CLI and UI can explicitly install, check, or update the canonical CUA package after verifying the upstream release manifest and installer checksum; nothing is bundled or updated automatically, driver telemetry stays off for Hermes sessions, and activity records contain only bounded, redacted control metadata.
### Fixed
- **Windows bundle updates fail closed when installed processes retain a binary lock.** Setup waits for the invoking CLI, quiesces the tray and its short-lived CLI children, checks every payload extraction before writing release metadata, preserves custom install directories, and returns a failure instead of reporting a mixed-version installation.
- **CUA readiness follows the published driver contract.** Hermes accepts the documented `ok` health state, distinguishes an installed-but-degraded runtime from a missing installation, and constructs trusted Windows installer paths consistently across verification environments.
## [1.7.0] - 2026-08-13
### Added
- **Hermes Secure Link provides self-hosted pinned TLS ingress.** Relay, API, and Dashboard namespaces share one operator-owned TLS endpoint while retaining their native authentication boundaries, QR-carried certificate continuity, explicit rotation, and fail-closed route validation.
- **Hermes Reach is available for explicit experimentation.** The optional self-hosted rendezvous broker carries opaque Secure Link TLS records over outbound-only connections with bounded multiplexing, hashed credentials, replay protection, persistence, revocation, and no access to Hermes payloads.
- **Remote-access management exposes supported reachability clearly.** Dashboard status and pairing metadata distinguish Tailscale reachability, Secure Link transport protection, direct routes, and experimental Reach without presenting the broker as a replacement for authentication.
### Changed
- **Tailscale is the recommended remote route.** Pairing, Dashboard, documentation, and public site guidance present Tailscale as the easiest supported remote-access path; Reach remains disabled by default, advanced, and lower priority than supported routes.
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients honor custom headers, custom CA bundles, standard CA environment precedence, and an explicitly warned development-only verification override.
- **Voice Lab xAI sign-in uses device authorization.** The standalone login shows a verification URL and user code and polls for approval without requiring a loopback callback.
### Fixed
- **Phone delivery remains compatible with strict Hermes targets.** Version-tolerant parser and validator hooks retain older-host registration and exactly-once standalone delivery.
- **Profile-owned Relay registrations stay isolated.** Current Hermes uses profile-scoped ownership and context-local profile homes while legacy hosts retain a guarded compatibility path.
- **Phone is discoverable before its first historical session.** The Relay phone adapter publishes its configured home destination through Hermes' standard channel directory.
## [0.4.0-alpha.8] - 2026-08-13
### Added
- **Windows management separates each Relay host from this PC.** Host detail owns identity, pairing, access, capabilities, authorized clients, re-pairing, and guarded removal; Settings owns local daemon lifecycle, startup, privilege, terminal, logs, diagnostics, updates, and Help & About.
- **Desktop access uses clear host-scoped presets and capabilities.** Restricted, Ask Every Time, Standard, Full Access, and Custom remain explicit across commands, files, screen/input, USB, microphone, and camera controls.
- **Activity drilldown preserves bounded execution evidence.** Overview shows the latest three events and detail views expose request, output, result, exit, duration, and truncation metadata without copying sensitive inputs.
- **Connection presentation shows the live Agent-to-PC path.** Host selection, bidirectional packet motion, transition feedback, route details, and connection testing stay compact, responsive, and reduced-motion aware.
### Changed
- **Connect and disconnect remain responsive during daemon work.** Lifecycle calls and snapshot collection run outside the UI thread, transition status polls quickly without overlapping probes, and progress remains visible until authoritative daemon state arrives.
- **Tailscale is recommended for remote access.** Secure Link and direct TLS routes remain supported, while Hermes Reach is visibly experimental and lower priority.
### Fixed
- **Connection tests classify legacy private routes correctly.** A saved generic role is inferred from its actual endpoint, so LAN and Tailscale routes no longer appear as Custom VPN; results include reachability, latency, security, endpoint, and route count.
- **Ask-mode approval cards show the requested action.** A bounded preview appears in the compact card with full context and an Open in UI action.
- **Mixed capability policies are labeled Custom.** Overview no longer claims a preset when individual capability controls differ.
- **Tray placement follows the notification-area monitor and DPI.** Responsive popup geometry stays anchored above the tray icon across compact and high-DPI desktops.
- **PowerShell success output is complete and self-describing.** Scalar, pipeline, JSON, native stdout/stderr, exit status, and truncation metadata survive the desktop RPC response.
## [1.6.4] - 2026-08-12
@@ -616,7 +686,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
- **Spoken-turn badges (chat).** Voice-mode replies now carry a "Voice" chip and realtime replies a "Realtime Agent" chip — both with a speaker glyph — so spoken turns are distinguishable from typed ones in the scrollback.
- **App themes.** A new theme picker in Settings → Appearance ships eight looks: the signature Hermes Relay brand (with full light/dark) plus ports of the Nous Hermes baselines — Hermes Teal, Nous Blue (light), Midnight, Ember, Mono, Cyberpunk, and Rosé. The whole app — brand chrome, accents, and chat background — follows the chosen theme. Light/Dark/Auto applies to themes that ship both modes; fixed-mode themes show their own complete look.
- **Hot-swappable agent sphere.** The orb is now a pluggable "skin": an Adaptive skin that recolors to match your theme, built-in Classic / Aurora / Solar / Mono looks, and support for **user-authored skins** loaded from a small JSON spec. Each skin declares which live signals it reacts to (voice, tool bursts, activity), shown as capability badges in the picker. See `docs/sphere-spec.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. A plugin-provided **Secure proxy** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. The optional plugin-provided **Hermes Secure Link** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Enhanced voice control (Gemini & xAI).** When the relay uses a Gemini or xAI voice provider, Voice Settings can now steer it: pick a Gemini voice and model and turn on expressive tone tags (with optional natural-language voice direction), or set an xAI voice with expressive speech tags. Expressive tags also apply to xAI on the streaming voice-output renderer. Standard (no-plugin) voice stays configured server-side.
- **Voice render-path visibility.** Voice Settings shows which path is rendering speech (streaming vs. basic), and Diagnostics records it each session, making voice issues easier to troubleshoot.
- **Agent pets — a living, swappable avatar.** The orb can be replaced with an animated "pet" that reacts to what the agent is doing: idle / thinking / writing / speaking / listening states, a distinct **working** pose during tool calls, one-shot **greet** / **celebrate** reactions, and a loop that quickens as output streams. Add or remove pets right in Settings → Appearance (no `adb` needed), with a live state preview, a playback-speed slider, and optional frame auto-stabilization; capability badges (Voice · Tools · Activity) show honestly what each pet actually reacts to. Pets are pure data — an AI authoring kit and a JSON schema let you generate one from sprite art. See `docs/pet-spec.md` and the custom-avatars guide.
+8 -19
View File
@@ -1,34 +1,23 @@
# Hermes-Relay CLI v__VERSION__
**Release Date:** 2026-08-11
**Release Date:** 2026-08-14
This alpha replaces the right-click-only Windows tray with the compact **Hermes-Relay CLI UI** popup while keeping Hermes-Relay's desktop boundary narrow. Chat, the remote TUI, plugins, voice, and agent sessions remain CLI or upstream desktop concerns.
This patch prevents the Windows management tray from accumulating Hermes-Relay, registry, and ADB helper processes when a refresh is slow or fails, and adds bounded diagnostics for future recovery.
**Experimental phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the management tray is Windows-only.
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the management UI is Windows-only.
## What's changed
### Added
- **Compact Windows management tray.** The popup provides connection status, host selection, per-host access, pending approval dialogs, recent activity, daemon controls, startup settings, and authorized-client revocation.
- **Host-aware desktop access.** `hermes-relay hosts` lists and selects paired Hermes instances and stores independent Ask, Trusted, or Full Access policy for each canonical relay URL.
- **In-window grant decisions.** New computer-use requests bring the tray forward and show the requesting host, scope, reason, and duration with explicit Approve and Reject actions.
- **Supported UI lifecycle from the CLI.** `hermes-relay ui install|open|status` lets a CLI-only Windows installation add, reveal, or inspect the optional management UI without rerunning setup by hand.
### Changed
- **Daemon startup is connectivity-first.** Ask mode can keep an authenticated daemon connected with zero desktop tools attached, so starting the daemon does not itself grant authority.
- **Full Access is explicit and host-scoped.** Trusted hosts may use command and file tools while screen/input remains task-granted. Full Access also removes task prompts for screen, input, and file patches for that host, while authentication, audit, revocation, emergency stop, and UAC boundaries remain enforced.
- **Host changes apply immediately.** Selecting a different host or changing its access mode restarts an already-running daemon and the UI verifies that the daemon URL matches the selected host before showing it as connected.
- **PowerShell remains first-class.** Agents should prefer the dedicated `desktop_powershell` RPC for native Windows work; `desktop_terminal` remains cmd-compatible for existing callers.
- **CLI and UI updates share one verified installer.** Bundle updates coordinate shutdown and restart, allow same-version UI repair, and refuse accidental downgrade unless explicitly forced.
- **Grant discovery stays lightweight.** The approval window reads local bridge state instead of rebuilding the complete management snapshot, schedules each refresh only after the previous one finishes, and pauses idle polling while hidden.
- **Management refreshes are visibility-aware and resilient.** Concurrent snapshot requests share one bounded result, optional static checks are cached, and repeated failures back off instead of creating more work.
### Fixed
- **Detached daemon start reports real readiness.** `daemon start` waits for the spawned PID to authenticate and connect, and reports configuration, authentication, early-exit, and timeout diagnostics instead of returning a false success.
- **Normal tray operation no longer requires opening a CLI for grants.** Pending requests are resolved directly in the focused management dialog.
- **Release checks match the management tray.** CI builds the React assets, validates Tauri metadata, and smoke-tests the packaged tray without obsolete menu-only size or window assertions.
- **Installed tray builds no longer depend on a localhost development server.** Local and packaged builds embed their UI assets, eliminating the `127.0.0.1 refused to connect` failure.
- **Windows helper processes are contained.** Tray-launched commands have hard deadlines, bounded output capture, descendant cleanup, and suppressed loader-error dialogs, preventing stalled probes from growing into a process storm.
- **Daemon startup is serialized across launchers.** Cross-process lifecycle and runtime ownership locks prevent concurrent start or restart requests from leaving duplicate daemons behind.
- **Tray failures are diagnosable without exposing command data.** A rotated, sanitized `tray.log` records bounded probe and lifecycle outcomes separately from `daemon.log`.
## Install
+9 -10
View File
@@ -1,23 +1,22 @@
# Hermes-Relay-Server v__VERSION__
**Release Date:** August 12, 2026
**Release Date:** August 14, 2026
This patch adds safe simultaneous routing for multiple connected desktop PCs and makes host selection explicit across command, file, screen, USB, and ADB operations.
This release adds an official, opt-in Relay pane for Hermes Desktop through the supported runtime Plugin SDK. It keeps Relay management profile-scoped and user-invoked without opening a pane during startup, reconnects, profile changes, or plugin updates.
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
## What's changed
### Fixed
- **No more latest-client-wins routing.** Connecting a second desktop no longer evicts the first. Requests are bound to the selected desktop WebSocket, and a response from another PC cannot satisfy them.
- **Ambiguous calls fail closed.** With more than one desktop online, client-routed tools require a stable device ID or unambiguous computer name instead of silently choosing the latest heartbeat.
- **Pairing preserves existing PCs.** Placeholder legacy device identifiers no longer collide and revoke another desktop's session.
### Added
- **Target discovery.** `desktop_health` lists every connected desktop with its stable ID, name, and advertised tools.
- **Two-level USB targeting.** USB and ADB tools use `device` for the host PC; ADB operations retain `serial` for the attached Android device.
- **Official Hermes Desktop pane.** The unified plugin package registers a movable native pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management.
- **Explicit entry points.** Labeled sidebar, status-bar, and command-palette actions register and reveal the pane lazily; repeated opens reuse the same surface.
- **Profile-scoped state.** Cached Relay state follows the active Hermes profile and is disposed cleanly when the plugin unloads.
### Changed
- **Plugin loading stays passive.** Loading, startup, reconnects, profile changes, and updates never reveal the pane or perform pane-owned network work.
## Install / update
+23
View File
@@ -70,6 +70,21 @@ an HTTPS reverse proxy. The [full walkthrough](https://hermes-relay.dev/docs/gui
covers Windows, remote access, and dashboard authentication. You do not need to
enable the separate API server or invent an API key for the standard path.
For plugin-enabled setups, optional **Hermes Secure Link** presents Relay, API,
and Dashboard routes through one pairing-pinned TLS origin. It protects traffic
to the paired endpoint while each service keeps its own authentication; it does
not provide reachability or independently identify the physical host. You still
use LAN routing, Tailscale or another VPN, or an operator-managed public route
to reach the listener. Secure Link is off by default and requires a fresh QR
pairing after it is enabled. See the
[remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
**Hermes Reach** is an experimental, advanced outbound-broker route. It remains
available for development and self-hosted evaluation, but it is disabled by
default, ordered after supported routes, and not recommended for normal remote
access. Use Tailscale for the easiest supported remote setup, or a public TLS
domain / Direct Secure Link when you want to own the complete network path.
### 3 · Connect and talk
Open the app, choose **Connect to Hermes**, and enter or discover the dashboard
@@ -204,6 +219,14 @@ It pairs against the **same relay and credential store** as the Android app —
On Windows, the default installer adds the optional compact **Hermes-Relay CLI UI** tray popup for host selection and pairing, connection and daemon state, per-host Ask/Trusted/Full Access, local grant dialogs, authorized-client revocation, activity, settings, and emergency stop. It is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
Structured Windows computer control prefers a compatible local CUA Driver
runtime for window-targeted background actions and virtual per-session agent
cursors. It remains behind Hermes host policy, grants, targeting, audit, and
emergency stop; Windows input is an explicit compatibility backend. CUA is not
bundled or updated automatically, but the local CLI/UI can explicitly install,
check, or update its verified canonical package. It is never exposed as a raw
remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs/desktop/tools.html#computer-use-engines).
- **Docs:** [CLI guide](https://hermes-relay.dev/docs/desktop/) · [`desktop/README.md`](desktop/README.md)
- **AI-agent setup recipe:** `/hermes-relay-desktop-setup`
+3
View File
@@ -128,6 +128,7 @@ optional Windows installer.
| File | Purpose |
|---|---|
| `desktop/package.json` | canonical CLI version |
| `desktop/.bun-version` | exact Bun compiler/runtime for standalone binaries |
| `desktop/package-lock.json` | npm root/workspace package metadata |
| `desktop/src/version.ts` | compiled CLI runtime version |
| `desktop/tray/Cargo.toml` | native systray package version |
@@ -152,6 +153,8 @@ manually, run `npm run sync:version` before checking. `npm run verify` is the
single Windows release-parity gate: version sync, type-check, tests, TypeScript
build, compiled CLI smoke, and tray formatting, Clippy, check, and tests. CI runs
the portable portions on every desktop change and the Windows tray gates separately.
Release jobs read `desktop/.bun-version`; cross-built and Windows-built artifacts
must not silently embed different Bun runtime versions.
## Branching policy
+27 -13
View File
@@ -1,10 +1,10 @@
# Hermes-Relay-Android v1.8.1
# Hermes-Relay-Android v1.9.0
**Release Date:** August 9, 2026
**Release Date:** August 14, 2026
## Download
> Installing on your phone? Download `hermes-relay-1.8.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
> Installing on your phone? Download `hermes-relay-1.9.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,22 +12,36 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
## Summary
This patch keeps long Hermes conversations complete and aligns Android's
Gateway behavior with current upstream turn contracts.
This release makes multi-profile session browsing feel native, keeps reactions
and voice attached to the correct conversation, and expands standard Gateway
management without requiring the optional Relay plugin.
## Added
- Browse one profile or all profiles, customize sorting and filters, and
optionally group sessions by project, recency, status, or profile.
- See profile identity, repository, branch, and pull-request context directly
in session rows when Hermes supplies it.
- Edit current Hermes profiles and complete more Manage workflows through the
authenticated standard Gateway.
## Fixed
- Complete transcript reads page explicitly across both API-server and
profile-scoped Dashboard routes, so sessions beyond Hermes' latest-500
default retain stable history, sharing, retry, edit, and recovery anchors.
- Gateway submit rejections preserve the authoritative server message without
silently falling through to SSE.
- Gateway event envelopes reconcile consistently, and edit-and-regenerate
requests send the required truncation confirmation.
- Cross-profile sessions hydrate and resume with their owning agent while All
Profiles remains selected; New Chat from that view respects the default
profile.
- Reactions pin to both user and assistant messages using durable message rows.
- Vanilla Hermes voice stays on the Gateway instead of depending on the
optional API fallback.
- Session navigation defaults to an ungrouped list, keeps project grouping
opt-in, restores secondary actions, and closes on outside taps.
- Route changes shut down network clients off the main thread, and Gateway
outcomes, uploads, clarify cards, automation state, and media recovery follow
authoritative upstream behavior.
## Install / Verify
- App version: **1.8.1** (versionCode **42**).
- App version: **1.9.0** (versionCode **43**).
- Standard Chat, sessions, Manage, and Vanilla Hermes voice continue to work
against unmodified upstream Hermes.
- The optional Relay plugin is not required for standard Android chat or hosted
+42 -2
View File
@@ -6,6 +6,27 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
---
## Certify the official Desktop Relay plugin
The unified `plugin/desktop/plugin.js` implementation is covered by source-level
SDK contract, packaging, explicit-open, no-auto-open, close, unload, and profile
cache-isolation tests. A physical official Hermes Desktop session is still
required before calling the UX live-certified:
- Test default and named local profiles, ordinary authenticated remote mode,
and SSH mode with differently named local/remote profile mapping.
- In two full app windows, prove enabling, registration, explicit open,
requests, close/reopen, hot reload, and disable/unload remain window-local.
- Prove startup, reconnect, profile change, layout restore/reset, update, and
background events never open or focus Relay.
- Drag and dock the pane across native zones, close it, reopen it from all three
labeled actions, and verify no private-hook fallback is needed.
- Exercise Relay running/unreachable, zero/one/multiple devices, pairing,
revocation, bridge activity, media, remote access, and renderer error logging
without exposing credentials, pairing payloads, filesystem paths, or tokens.
---
## Structured desktop hardware capabilities
Structured access and per-host USB policy now ship with typed, serial-bound ADB
@@ -935,7 +956,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
- **Outbound buffering — ✅ relay-side DONE (2026-06-29).** `ProactiveChannel.push()` now queues agent→phone messages in a bounded deque (drop-oldest, 24 h TTL) when no phone is subscribed and returns `{queued: true}` (not 503); `_flush_outbound` delivers FIFO on the next subscribe (stale pruned). Inspect/cancel via `peek_outbound`/`cancel_outbound` + loopback `GET`/`DELETE /phone/outbound`. **UI surfacing of the queued state** (host-side, since the queue exists while the phone is OFFLINE): (a) ✅ **desktop CLI `relay queue` / `relay queue --clear` / `--cancel <id>` DONE (2026-06-29)** over the new endpoints (loopback-only — run on the relay host); a dashboard Relay-tab view is the optional GUI equivalent; (b) **remaining** — in the threaded agent surface, mark messages that arrived-while-away, and show the user's OWN pending replies (the Phase 3 reply queue) with a sending/Cancel affordance — that's where phone-side "queued + cancel" belongs.
- **Threads surface (unified-session model — see ADR 12 + the Refinement above).** Build order, each shippable: **(1)** source tags in the session drawer (`source=phone` → clean **Threads** chip + thread-spool icon, NOT a phone glyph) — also delivers the "source attribution in Chat" goal; **(2)** open a Thread in Chat from its session-store history (reuse the existing message-history path); **(3)** route the live `proactive` push into the session view + notification + unread, demoting `ProactiveInboxStore` to cache/outbox; **(4)** reply from the Chat composer via `proactive.reply` + persist the user turn + local `Sending/Queued/Failed` status — **MVP**; **(5)** a **Threads capability row** in the best-path UI + a pinned **Threads** entry atop the drawer (thread-spool icon, shown only when relay-paired + opted-in) + retire `HermesInboxScreen`, re-point the notification deep-link + Settings "View messages"; **(6)** outbox/retry on reconnect; **(7)** relay `proactive.reply.ack` (honest Delivered) + `proactive.cancel`; **(8)** multi-thread `chat_id` (named/project Threads). **Verify gate before (1):** confirm the app's session-list/history path surfaces a `source=phone` session cleanly (upstream `session.list` returns all sources flat, so it should — but check whether the drawer currently filters it out). Honesty call: do NOT show "Delivered" until (7) lands (can't confirm it client-side before the ack).
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering** (an agent reply lands in the open Thread as an ASSISTANT bubble, suppressing the notification/inbox — `injectIntoThread`); **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`** (deleted; route + nav removed; notification tap + Settings "View messages" re-pointed to Chat; surface renamed "Hermes messages" → **"Threads"**); relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DEFERRED (reasons):** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **exact-Thread deep-link** from the notification (opens Chat today, not the specific thread — needs select-session-on-entry); **remove the now-orphaned `ProactiveInboxStore`** (viewer-less write-only log); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
- **Status (2026-06-29, implemented UNBUILT — verify in Studio):** **CODE-COMPLETE on `dev`:** slice **1** (drawer source tags + `ThreadSpoolGlyph` + Threads filter), **2** (open a Thread from history — free via the existing `loadSessionHistory` path), **3-parse** (carry `reply_to` on `ProactiveMessage`), **4** (composer reply in a `source=phone` session routes over `proactive.reply`; `MessageDeliveryStatus` SENDING→DELIVERED/FAILED on the bubble), **5** (Threads capability row in `SessionPathCard` + `threadsCapabilityActive` drawer wiring), **7** (relay `proactive.reply.ack` + `proactive.cancel` — 25/25 `unittest` green — and client ack handling). **DONE since (2026-06-29, built + on phone):** live **in-thread reply rendering**; **user-created named Threads** ("+ New Thread"); **retire `HermesInboxScreen`**; relay slice-7 ack/cancel **DEPLOYED** to the host so **"Delivered" is live**. **DONE (2026-08-14):** notification taps survive cold start and open the exact `chat_id`; agent-initiated outbound messages appear as connection-scoped provisional Threads backed by the bounded proactive store, then promote to the real `source=phone` session after the first reply. **DEFERRED:** per-session **unread badge**; **outbox/retry** (needs multiplexer connection-state); **agent-initiated** named Threads (upstream `send_message` thread param). On-device verifies for the create-flow: fresh-`chat_id` auto-create, the `…:dm:<chat_id>` id form, `renameSession` on a phone session.
- **User-created Threads (slice 8, Discord-style) — CODE-COMPLETE on `dev` (built + installed 2026-06-29; on-device behavior pending).** "+ New Thread" in the drawer's Threads view → name dialog → `ChatViewModel.startNewThread` mints a fresh `chat_id`; the first composer message opens it over `proactive.reply` (gateway auto-creates the `source=phone` session) → `switchToCreatedThread` polls + switches to the real session + applies the name. Existing-thread replies route by the `chat_id` parsed from the session id (`…:dm:<chat_id>`; opaque id → home fallback). **On-device verifies:** (1) a fresh-`chat_id` no-`reply_to` inbound creates a new `source=phone` session; (2) the phone session id carries the `…:dm:<chat_id>` form the client parses; (3) `renameSession` titles a phone session. **Remaining slice-8:** AGENT-initiated named Threads (the upstream `send_message` thread/chat_id param so the agent can open its own named Threads).
- **`chat_id` not exposed by `/api/sessions` (root cause of the 2026-06-29 on-device create-flow bugs — fixed client-side).** Confirmed on the host: a phone session's `id` is a timestamp (e.g. `20260629_204755_94f391d6`); the real `chat_id` lives in the `session_key` (`agent:main:phone:dm:<chat_id>`) and a `chat_id` column — but `/api/sessions` returns **neither `chat_id` nor `session_key`**, only `source` + the timestamp `id`. So the client could not map a session ↔ its `chat_id`, which broke create-thread switch/rename + reply routing + in-thread injection. **Client workaround shipped:** find a created thread by session-list **diff** (the new `source=phone` session), keep an in-memory `sessionId → chat_id` map (learned at creation + from incoming `phone.message`s) for reply routing, and inject by source (+ learned chat_id) rather than a parsed id. **Limitation:** for a thread the app didn't create *this* session (agent-created, another device, or after an app restart) `chat_id` is unknown until a message arrives while viewing it → its replies fall back to the home channel until then. **RESOLVED via the plugin (2026-06-29, per upstream-or-plugin policy):** the relay now exposes `GET /phone/threads` (`plugin/relay/session_store.py` reads the gateway store read-only → `[{session_id, chat_id, title}]`; `server.py` `handle_phone_threads`, bearer for the app / loopback for diag; 5 unit tests). The app (`RelayHttpClient.fetchPhoneThreads` → `ConnectionViewModel.phoneThreadChatIds` on every `auth.ok` → `ChatViewModel.seedThreadChatIds`, authoritative over the learned map) now routes replies correctly for **any** Thread — incl. ones it didn't create + after restart. Deployed + verified live. **Still-nice-to-have (lower priority): the upstream PR** to add `chat_id`/`session_key` to `/api/sessions` (the standard-path proper fix; the relay route then becomes redundant + the client prefers upstream when present).
- **Threads as named/project conversations (Discord-parity — folds into multi-thread #8).** A stable *named* `chat_id` per project = a persistent, agent-reachable project Thread (Discord named-thread parity for "persist a session for a project"). Enables: the agent **opening** a new named Thread for a background job/topic (a relay/gateway "open thread" affordance + a `send_message`-adjacent tool); cron/job updates landing in their own Thread; and replying to a Thread from any surface (desktop CLI / dashboard) since it is just a gateway session. Also evaluate per-Thread profile binding (a project Thread uses the "work" profile — ties to profile=contact).
@@ -964,7 +985,7 @@ The gateway-platform model is the *correct + sufficient architecture* (the phone
session store; the relay buffer is only the live/offline-delivery layer, not a
parallel history database.
- **Profile = contact mapping (new idea, fold in).** Multiple Hermes **profiles** (distinct agent personas/configs) could each be a distinct thread *source*/"contact" — DMing different agents. Maps cleanly onto the per-thread `chat_id` + source-attribution work; lets the app feel like a contact list of agents.
- **Per-thread notification controls + deep-link (Discord-parity affordances).** Per-thread notification channels, mute/DND/quiet-hours (Phase 3 partially), and a notification that **deep-links into the exact thread** (tap → land in that conversation) so dipping in/out while multitasking is frictionless.
- **Per-thread notification controls (Discord-parity affordances).** Exact-thread notification deep-linking is shipped. Remaining: per-thread notification channels and mute/DND/quiet-hours controls (Phase 3 partially).
- **Agent-initiated rich content.** Agent → phone thread with **images/cards** (relay media infra + `InboundAttachmentCard`/`HermesCardBubble` already exist on the chat side — reuse). Inbound (phone → agent) reply media stays deferred (text-first), but outbound rich content is low-cost parity.
- **In-thread "agent is working" indicator.** A typing/working state in the thread while the agent thinks/runs tools (Discord typing-dots parity) — the chat surface already has thinking indicators to reuse.
@@ -1230,6 +1251,25 @@ When the answer becomes clearer, this section becomes either an ADR in `docs/dec
## Smaller deferred items
- **Certify the preferred CUA Driver backend (ADR 56).** The canonical-runtime
probe, bounded adapter, server-owned control-session envelope, per-session
grant state, local engine/status controls, telemetry-off process environment,
and Hermes snapshot-token primitives now exist. Before graduating the engine,
finish end-to-end enforcement of app/display/folder scopes and sensitive
pixel/accessibility denial or redaction, harden the grant-bridge ACL and nonce
lifecycle, and complete live Windows certification proving the physical cursor and
foreground app stay unchanged, stale or cross-window tokens fail, two remote
control sessions receive isolated animated cursors, and foreground escalation
never happens implicitly. Exercise revoke on grant expiry, disconnect,
re-pair, policy downgrade, emergency stop, Windows-session change, and daemon
shutdown. The explicit local CUA install/update surface now verifies upstream
manifest identity and installer SHA-256; add Windows publisher verification
when upstream signs the installer. Keep raw CUA tools, configuration,
recording, replay, and JavaScript outside the remote agent surface.
Remove the temporary Windows readiness/health split once
[trycua/cua#3103](https://github.com/trycua/cua/issues/3103) ships in the
supported CUA range; restore a mandatory health gate only if the upstream
probe is bounded and cannot leave UI Automation falsely busy.
- **MediaProjection consent flow** — wired in MainActivity (2026-04-12), needs end-to-end test on a real device
- **WorkManager upgrade for auto-disable timer** — currently a coroutine `Job + delay()` in `AutoDisableWorker.kt`; documented at top of file. Upgrade when androidx.work joins the classpath
- **Wave 3 voice-bridge multi-turn confirmation** — currently a 5s TTS countdown with cancel; conversational confirmation is the follow-up
@@ -1 +1 @@
Long sessions now retain complete history beyond Hermes' latest-500 default, keeping edit, retry, sharing, and recovery anchors stable. Gateway submit rejections preserve the server's message without unintended SSE fallback, while event envelopes and edit-and-regenerate requests follow current upstream contracts.
Browse sessions across profiles without losing their owning agent or your selected scope. Reactions now pin to both user and assistant messages, Vanilla Hermes voice stays on the authenticated Gateway, and New Chat in All Profiles respects the default profile. Sessions are ungrouped by default, with project grouping available in Customize Sessions.
+28
View File
@@ -1,5 +1,33 @@
{
"versions": [
{
"version": "1.9.0",
"title": "Better sessions, reactions, and voice",
"date": "2026-08-14",
"sections": [
{
"header": "Sessions keep their identity",
"bullets": [
"Browse one profile or all profiles, customize sorting and filters, and optionally group sessions by project, recency, status, or profile.",
"Cross-profile sessions hydrate, resume, and send with their owning agent without changing the global profile selection; New Chat in All Profiles uses the default profile."
]
},
{
"header": "Conversation controls stay attached",
"bullets": [
"Reactions pin to durable rows on both user and assistant messages.",
"Vanilla Hermes voice stays on the authenticated Gateway instead of requiring the optional API fallback."
]
},
{
"header": "Context without clutter",
"bullets": [
"Session rows show profile, project, branch, and pull-request context when Hermes supplies it, while the default view remains ungrouped.",
"The session drawer restores secondary actions in All Profiles and closes when you tap outside it."
]
}
]
},
{
"version": "1.8.1",
"title": "Complete, reliable transcripts",
+6 -5
View File
@@ -1,6 +1,7 @@
v1.8.1 - Complete, reliable transcripts
v1.9.0 - Better sessions, reactions, and voice
* Keep complete history in long sessions beyond Hermes' latest-500 default.
* Preserve stable edit, retry, sharing, and recovery anchors while paging history.
* Show authoritative Gateway rejection messages without an unintended fallback.
* Reconcile Gateway events and edit-and-regenerate requests with current upstream contracts.
* Browse all profiles without switching away from the selected scope.
* Start new chats with the default profile and hydrate history with the session owner.
* Pin reactions to both user and assistant messages.
* Keep Vanilla Hermes voice on the authenticated Gateway.
* Use an ungrouped session list by default, with project grouping available in Customize Sessions.
@@ -5,6 +5,10 @@ import android.provider.Settings
import android.util.Log
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.BrokerEndpoint
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.replaceHermesReachCredential
import com.hermesandroid.relay.data.sameBrokerAuthority
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
@@ -15,6 +19,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -558,6 +563,12 @@ class AuthManager(
* Either way, we leave the previously-persisted list untouched.
*/
private var pendingEndpoints: List<EndpointCandidate>? = null
private var activeEndpointProvider: () -> EndpointCandidate? = { null }
/** Bind auth.ok route credentials to the transport that actually carried them. */
fun setActiveEndpointProvider(provider: () -> EndpointCandidate?) {
activeEndpointProvider = provider
}
/**
* Server-advertised agent profiles from the `auth.ok` payload's
@@ -1042,6 +1053,7 @@ class AuthManager(
}
if (token != null) {
applyBrokerRouteCredential(payload)
val s = store()
s.putString(KEY_SESSION_TOKEN, token)
val refreshToken = payload["refresh_token"]
@@ -1150,6 +1162,40 @@ class AuthManager(
}
}
private suspend fun applyBrokerRouteCredential(payload: JsonObject) {
val active = activeEndpointProvider()?.takeIf { it.hasHermesReach() } ?: return
val current = active.broker ?: return
// Fresh pairing is scoped by pendingEndpoints; reconnect rotation is
// accepted only by this connection-scoped AuthManager's live session.
if (pendingEndpoints == null && _authState.value !is AuthState.Paired) return
val credential = payload["route_credential"] as? JsonObject ?: return
if (credential["kind"]?.jsonPrimitive?.contentOrNull != "broker_route") return
val brokerUrl = credential["broker_url"]?.jsonPrimitive?.contentOrNull ?: return
val hostId = credential["host_id"]?.jsonPrimitive?.contentOrNull ?: return
if (!sameBrokerAuthority(brokerUrl, current.url) || hostId != current.hostId) {
Log.w(TAG, "Ignoring broker route credential that does not match the active paired route")
return
}
val replacement = BrokerEndpoint(
url = current.url,
protocolVersion = current.protocolVersion,
hostId = current.hostId,
credentialKind = "route",
token = credential["token"]?.jsonPrimitive?.contentOrNull ?: return,
expiresAt = credential["expires_at"]?.jsonPrimitive?.longOrNull,
)
val validated = active.copy(broker = replacement).takeIf { it.hasHermesReach() } ?: return
val deviceId = getDeviceId()
val source = pendingEndpoints
?: PairingPreferences.getDeviceEndpoints(context, deviceId).first()
val updated = replaceHermesReachCredential(source, current, validated)
if (updated == source) return
if (pendingEndpoints != null) pendingEndpoints = updated
else PairingPreferences.setDeviceEndpoints(context, deviceId, updated)
Log.i(TAG, "Accepted a durable Hermes Reach route credential for the active paired route")
}
private fun handleAuthFail(envelope: Envelope) {
try {
val rawReason = envelope.payload["reason"]?.jsonPrimitive?.contentOrNull
@@ -90,12 +90,28 @@ class CertPinStore(private val context: Context) {
if (pins.isEmpty()) return CertificatePinner.DEFAULT
val builder = CertificatePinner.Builder()
for ((hostPort, pin) in pins) {
val host = hostPort.substringBefore(':')
val host = hostPort.substringBeforeLast(':')
builder.add(host, pin)
}
return builder.build()
}
/**
* Build a pinner for one exact URL authority. CertificatePinner keys by
* hostname only, so adding every stored host:port entry to one client
* accidentally lets a pin learned on one port govern another port.
*/
fun buildPinnerSnapshotFor(url: String): CertificatePinner {
val hostPort = hostPortFromUrl(url) ?: return CertificatePinner.DEFAULT
val pin = getPinsBlocking()[hostPort] ?: return CertificatePinner.DEFAULT
val host = runCatching { URI(url.trim()).host }.getOrNull()
?.takeIf { it.isNotBlank() }
?: return CertificatePinner.DEFAULT
return CertificatePinner.Builder()
.add(host, pin)
.build()
}
/**
* Record a pin for a host. Called from the WebSocket listener's `onOpen`
* when we have a successful connection and can read the peer certs from
@@ -141,6 +141,18 @@ data class ChatMessage(
* through `copy`, while [id] remains the authoritative lookup/wire id.
*/
val uiKey: String = id,
/**
* Durable Gateway transcript row identity for rewind/edit-regenerate.
* This is server-owned and can change after a truncating rewrite; it is
* never used as a Compose key or synthesized client-side.
*/
val rowId: Long? = null,
/**
* Durable iOS-style tapbacks attached to this server message. Hermes keeps
* one reaction per author in the message's display metadata; the UI also
* updates this list optimistically while a reaction write is in flight.
*/
val reactions: List<MessageReaction> = emptyList(),
/**
* Mixture-of-Agents advisor responses surfaced during the live turn.
* Unavailable advisors retain only neutral state, never their raw failure
@@ -150,6 +162,29 @@ data class ChatMessage(
val moaReferences: List<MoaReference> = emptyList(),
)
data class MessageReaction(
val emoji: String,
val author: String,
/** Epoch seconds, matching the Gateway/Desktop contract. */
val at: Double,
)
/** Apply Hermes' one-reaction-per-author, re-tap-to-retract semantics. */
internal fun applyMessageReaction(
reactions: List<MessageReaction>,
emoji: String?,
author: String = "user",
at: Double = System.currentTimeMillis() / 1000.0,
): List<MessageReaction> {
val previous = reactions.firstOrNull { it.author == author }
val withoutAuthor = reactions.filterNot { it.author == author }
return if (emoji.isNullOrBlank() || previous?.emoji == emoji) {
withoutAuthor
} else {
withoutAuthor + MessageReaction(emoji = emoji, author = author, at = at)
}
}
data class MoaReference(
val index: Int,
val count: Int?,
@@ -406,6 +441,11 @@ data class ChatSession(
val title: String?,
val model: String?,
val messageCount: Int = 0,
val inputTokens: Int = 0,
val outputTokens: Int = 0,
val actualCostUsd: Double? = null,
val estimatedCostUsd: Double? = null,
val isActive: Boolean = false,
val updatedAt: Long = 0L,
val startedAt: Long = 0L,
val lastActivityAt: Long = 0L,
@@ -430,6 +470,12 @@ data class ChatSession(
val pullRequestState: String? = null,
val pullRequestDraft: Boolean = false,
) {
val totalTokens: Int
get() = inputTokens + outputTokens
val costUsd: Double
get() = actualCostUsd ?: estimatedCostUsd ?: 0.0
val activityTimestamp: Long
get() = firstPositive(lastActivityAt, updatedAt, startedAt)
@@ -14,6 +14,9 @@ data class DashboardConnectionStatus(
val gatewayTicketAvailable: Boolean? = null,
val message: String? = null,
val gatewayMode: String? = null,
/** Profiles positively advertised by the live multiplex gateway. */
val servedProfiles: List<String> = emptyList(),
/** Installed profiles reported by the dashboard; never routing authority. */
val profiles: List<String> = emptyList(),
)
@@ -63,12 +63,8 @@ fun EndpointCandidate?.isEncryptedOverlayRoute(isTailscaleDetected: Boolean): Bo
val hint = security.orEmpty().lowercase()
return r == "tailscale" ||
(isTailscaleDetected && hint.contains("tailscale")) ||
r == "plugin_proxy" ||
r == "plugin-proxy" ||
hasSecureProxy() ||
hint.contains("wireguard") ||
hint.contains("https") ||
hint.contains("tls")
(!hasSecureProxy() && (hint.contains("https") || hint.contains("tls")))
}
/** Human label for the overlay mechanism encrypting a route. */
@@ -78,7 +74,6 @@ fun EndpointCandidate?.overlayMechanism(isTailscaleDetected: Boolean): String {
val hint = security.orEmpty().lowercase()
return when {
r == "tailscale" || (isTailscaleDetected && hint.contains("tailscale")) -> "Tailscale"
r == "plugin_proxy" || r == "plugin-proxy" || hasSecureProxy() -> "Proxy"
hint.contains("wireguard") -> "WireGuard"
hint.contains("https") || hint.contains("tls") -> "TLS"
else -> "Encrypted"
@@ -92,7 +87,10 @@ fun classifySurfaceSecurity(
activeEndpoint: EndpointCandidate?,
isTailscaleDetected: Boolean,
): SurfaceSecurity {
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
val (kind, mechanism) = when {
secureLinkProtected -> SurfaceSecurityKind.Tls to
if (activeEndpoint?.hasHermesReach() == true) "Hermes Reach" else "Hermes Secure Link"
isTlsUrl(url) -> SurfaceSecurityKind.Tls to "TLS"
activeEndpoint.isEncryptedOverlayRoute(isTailscaleDetected) ->
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
@@ -101,6 +99,33 @@ fun classifySurfaceSecurity(
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
}
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
val candidate = this ?: return false
val routes = candidate.proxy?.takeIf { candidate.hasSecureProxy() }
?.let { proxy ->
val base = proxy.url.trim().trimEnd('/')
Triple(
"$base/dashboard",
"$base/api",
"wss://${base.substringAfter("://")}/relay/ws",
)
} ?: return false
val normalized = url.trim().trimEnd('/')
val service = when (label) {
"Chat & Manage" -> "dashboard"
"API / sessions" -> "api"
"Relay tools" -> "relay"
else -> return false
}
if (service !in candidate.secureLinkServices()) return false
val expected = when (service) {
"dashboard" -> routes.first
"api" -> routes.second
else -> routes.third
}
return normalized.equals(expected, ignoreCase = true)
}
/**
* Roll up the per-surface verdicts into one connection-level [ConnectionSecurity].
* Pure + side-effect free so it is unit-testable without Android.
@@ -45,8 +45,13 @@ data class EndpointCandidate(
val relay: RelayEndpoint? = null,
val dashboard: DashboardEndpoint? = null,
val proxy: ProxyEndpoint? = null,
/** Optional outbound rendezvous carrying the pinned [proxy] byte stream. */
val broker: BrokerEndpoint? = null,
val security: String? = null,
val recommended: Boolean = false,
val experimental: Boolean = false,
@SerialName("display_name")
val displayName: String? = null,
)
/**
@@ -110,6 +115,27 @@ data class ProxyEndpoint(
val transportHint: String? = null,
@SerialName("pin_sha256")
val pinSha256: String? = null,
/** Independently authenticated services carried by this pinned origin. */
val surfaces: List<String> = listOf("relay"),
)
/**
* Hermes Reach rendezvous metadata from an operator-reviewed pairing payload.
* The token authenticates only this broker route; Hermes service credentials
* remain inside the QR-pinned Secure Link TLS connection.
*/
@Serializable
data class BrokerEndpoint(
val url: String,
@SerialName("protocol_version")
val protocolVersion: Int = 1,
@SerialName("host_id")
val hostId: String,
@SerialName("credential_kind")
val credentialKind: String,
val token: String,
@SerialName("expires_at")
val expiresAt: Long? = null,
)
/**
@@ -123,7 +149,7 @@ data class ProxyEndpoint(
*/
fun EndpointCandidate.isKnownRole(): Boolean {
return when (role.lowercase()) {
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "https" -> true
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
else -> false
}
}
@@ -146,7 +172,8 @@ fun EndpointCandidate.displayLabel(): String {
"Public"
}
"https" -> "HTTPS"
"plugin_proxy", "plugin-proxy" -> "Plugin proxy"
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
else -> "Custom VPN ($role)"
}
}
@@ -177,7 +204,69 @@ fun EndpointCandidate.routeAuthority(): String? {
}
fun EndpointCandidate.hasSecureProxy(): Boolean =
proxy?.url?.startsWith("https://", ignoreCase = true) == true ||
proxy?.url?.startsWith("wss://", ignoreCase = true) == true ||
role.equals("plugin_proxy", ignoreCase = true) ||
role.equals("plugin-proxy", ignoreCase = true)
proxy?.isValidPinnedProxy() == true
/** Product-facing service inventory; wire identifiers remain unchanged. */
fun EndpointCandidate.secureLinkServices(): List<String> =
if (!hasSecureProxy()) emptyList() else proxy.orEmptySurfaces()
fun EndpointCandidate.secureLinkCoversAllServices(): Boolean =
secureLinkServices().containsAll(listOf("relay", "api", "dashboard"))
fun EndpointCandidate.presentationRouteUrl(): String? =
broker?.url?.takeIf { hasHermesReach() } ?: proxy?.url?.takeIf { hasSecureProxy() } ?: primaryRouteUrl()
fun EndpointCandidate.hasHermesReach(): Boolean =
role.lowercase() in setOf("outbound_broker", "broker", "relay_broker") &&
broker?.isValidHermesReach() == true && hasSecureProxy()
fun BrokerEndpoint.isValidHermesReach(): Boolean {
if (protocolVersion != 1 || !hostId.isCanonicalBase64Url(16) || !token.isCanonicalBase64Url(32)) return false
if (credentialKind !in setOf("bootstrap", "route")) return false
if (credentialKind == "bootstrap" && expiresAt?.let { it <= System.currentTimeMillis() / 1000L } == true) return false
val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
return uri.rawPath.orEmpty().let { it.isEmpty() || it == "/" || it == "/v1/connect" }
}
private fun String.isCanonicalBase64Url(byteCount: Int): Boolean {
if (isBlank() || '=' in this) return false
val decoded = runCatching { java.util.Base64.getUrlDecoder().decode(this) }.getOrNull() ?: return false
return decoded.size == byteCount &&
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == this
}
/** Exact host locator + broker authority replacement; never crosses devices. */
internal fun replaceHermesReachCredential(
source: List<EndpointCandidate>,
expected: BrokerEndpoint,
replacement: EndpointCandidate,
): List<EndpointCandidate> = source.map { candidate ->
if (candidate.broker?.hostId == expected.hostId &&
sameBrokerAuthority(candidate.broker.url, expected.url)
) replacement else candidate
}
internal fun sameBrokerAuthority(left: String, right: String): Boolean = runCatching {
val a = URI(left.trim())
val b = URI(right.trim())
fun port(uri: URI) = if (uri.port > 0) uri.port else 443
a.scheme.equals("wss", true) && b.scheme.equals("wss", true) &&
a.host.equals(b.host, true) && port(a) == port(b) &&
a.rawPath.orEmpty().trimEnd('/') == b.rawPath.orEmpty().trimEnd('/')
}.getOrDefault(false)
private fun ProxyEndpoint?.orEmptySurfaces(): List<String> = this?.surfaces.orEmpty()
.map { it.trim().lowercase() }
.filter { it in setOf("relay", "api", "dashboard") }
.distinct()
fun ProxyEndpoint.isValidPinnedProxy(): Boolean {
val uri = runCatching { URI(url.trim().trimEnd('/')) }.getOrNull() ?: return false
if (!uri.scheme.equals("https", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" }) return false
val pin = pinSha256?.trim()?.removePrefix("sha256/") ?: return false
return runCatching { java.util.Base64.getDecoder().decode(pin).size == 32 }.getOrDefault(false)
}
@@ -34,6 +34,8 @@ data class ProactiveInboxEntry(
* field).
*/
val chatId: String? = null,
/** Owning saved connection. Null only for entries written by older builds. */
val connectionId: String? = null,
)
private val Context.proactiveInboxStore: DataStore<Preferences> by
@@ -49,10 +51,10 @@ private const val MAX_ENTRIES = 100
* newest-first, deduped by id (so a re-delivered message doesn't double up), and
* capped at [MAX_ENTRIES]. Survives app restart.
*
* Demoted (2026-06-29): the agent conversation now lives as a Thread in Chat (the
* gateway session is the durable history), so the in-app inbox view is retired.
* This store is only fed for messages NOT shown in an open Thread; it currently
* has no viewer and is fully retireable — see TODO.
* Demoted (2026-06-29): once a phone gateway session exists, it is the durable
* history. Outbound agent messages arrive before that session exists, so this
* bounded store also backs the provisional Thread until the user's first reply
* promotes it to a real `source=phone` session.
*/
class ProactiveInboxRepository(private val context: Context) {
@@ -136,3 +136,91 @@ data class ProfileMemoryUpdateResponse(
@SerialName("bytes_written")
val bytesWritten: Long,
)
/** Authoritative upstream `profiles.describe` snapshot. */
data class GatewayProfileDescription(
val name: String,
val description: String,
val soul: String,
val provider: String,
val model: String,
val skills: List<GatewayProfileSkill>,
val toolsets: List<GatewayProfileToolset>,
val toolsetsPinned: Boolean,
)
data class GatewayProfileSkill(val name: String, val enabled: Boolean)
data class GatewayProfileToolset(
val name: String,
val description: String,
val toolCount: Int,
val enabled: Boolean,
)
enum class GatewayProfileSection(val wireName: String) {
Description("description"),
Soul("soul"),
Model("model"),
Skills("skills"),
Toolsets("toolsets"),
}
/** Null leaves a section unchanged; empty lists retain upstream replace semantics. */
data class GatewayProfilePatch(
val description: String? = null,
val soul: String? = null,
val provider: String? = null,
val model: String? = null,
val disabledSkills: List<String>? = null,
val enabledToolsets: List<String>? = null,
) {
val requestedSections: Set<GatewayProfileSection>
get() = buildSet {
if (description != null) add(GatewayProfileSection.Description)
if (soul != null) add(GatewayProfileSection.Soul)
if (provider != null && model != null) add(GatewayProfileSection.Model)
if (disabledSkills != null) add(GatewayProfileSection.Skills)
if (enabledToolsets != null) add(GatewayProfileSection.Toolsets)
}
}
data class GatewayProfileConfigureResult(
val requested: Set<GatewayProfileSection>,
val applied: Set<GatewayProfileSection>,
) {
val failed: Set<GatewayProfileSection> get() = requested - applied
}
interface GatewayProfileEditorClient {
suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription>
suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult>
}
class GatewayProfileEditorUnsupportedException : Exception(
"Profile editing is not supported by this gateway",
)
/** Relay fallback retained for older gateways and Relay-only memory files. */
interface LegacyProfileInspectorClient {
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse>
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse>
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse>
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse>
suspend fun updateSoul(profileName: String, content: String): Result<ProfileSoulUpdateResponse>
suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
): Result<ProfileMemoryUpdateResponse>
suspend fun updateSkillToggle(skillName: String, enabled: Boolean): Result<RelaySkillToggleResult>
suspend fun probeSkillToggleSupported(): Boolean
}
sealed interface RelaySkillToggleResult {
data object Ok : RelaySkillToggleResult
data object NotImplemented : RelaySkillToggleResult
}
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
@@ -16,6 +17,8 @@ import kotlinx.serialization.json.Json
data class ProfilePresentation(
val order: List<String> = emptyList(),
val hidden: Set<String> = emptySet(),
/** Local-only named-profile accent overrides, stored as normalized RGB hex. */
val colors: Map<String, String> = emptyMap(),
)
/**
@@ -63,14 +66,17 @@ class ProfilePresentationStore(
private val json = Json { ignoreUnknownKeys = true }
private val listSerializer = ListSerializer(String.serializer())
private val mapSerializer = MapSerializer(String.serializer(), String.serializer())
private fun orderKey(connectionId: String) = stringPreferencesKey("order_$connectionId")
private fun hiddenKey(connectionId: String) = stringPreferencesKey("hidden_$connectionId")
private fun colorsKey(connectionId: String) = stringPreferencesKey("colors_$connectionId")
fun presentationFlow(connectionId: String): Flow<ProfilePresentation> = dataStore.data.map { prefs ->
ProfilePresentation(
order = decode(prefs[orderKey(connectionId)]),
hidden = decode(prefs[hiddenKey(connectionId)]).toSet(),
colors = decodeMap(prefs[colorsKey(connectionId)]),
)
}
@@ -82,10 +88,18 @@ class ProfilePresentationStore(
dataStore.edit { it[hiddenKey(connectionId)] = json.encodeToString(listSerializer, hidden.sorted()) }
}
suspend fun setColors(connectionId: String, colors: Map<String, String>) {
dataStore.edit {
if (colors.isEmpty()) it.remove(colorsKey(connectionId))
else it[colorsKey(connectionId)] = json.encodeToString(mapSerializer, colors.toSortedMap())
}
}
suspend fun clear(connectionId: String) {
dataStore.edit {
it.remove(orderKey(connectionId))
it.remove(hiddenKey(connectionId))
it.remove(colorsKey(connectionId))
}
}
@@ -98,6 +112,12 @@ class ProfilePresentationStore(
} else {
runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())
}
private fun decodeMap(raw: String?): Map<String, String> = if (raw == null) {
emptyMap()
} else {
runCatching { json.decodeFromString(mapSerializer, raw) }.getOrDefault(emptyMap())
}
}
internal val Context.profilePresentationDataStore: DataStore<Preferences>
@@ -12,6 +12,7 @@ import com.hermesandroid.relay.auth.CertPinStore
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
@@ -77,6 +78,9 @@ internal fun buildRelayRequestOrNull(url: String): Request? =
null
}
private fun EndpointCandidate.relayWebSocketUrl(): String? =
pluginProxyRoutesOrNull()?.relayWebSocketUrl ?: relay?.url
class ConnectionManager(
private val multiplexer: ChannelMultiplexer,
/**
@@ -142,6 +146,10 @@ class ConnectionManager(
private val deviceIdProvider: (suspend () -> String?)? = null,
/** Random source for ordinary reconnect full-jitter; exact backoffs never use it. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
/** Exact-authority pinned client for a plugin-proxy WSS URL. */
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
/** Test seam for observing lifecycle teardown without opening a socket. */
private val okHttpClientFactory: (() -> OkHttpClient)? = null,
) {
private val supervisorJob = SupervisorJob()
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
@@ -151,7 +159,8 @@ class ConnectionManager(
encodeDefaults = true
}
private fun buildClient(): OkHttpClient {
private fun buildClient(url: String? = null): OkHttpClient {
okHttpClientFactory?.let { return it() }
val builder = OkHttpClient.Builder()
// OkHttp's 10s default connectTimeout is LAN-tuned; a Tailscale
// DERP-relayed cold-start handshake can exceed it, and a failed
@@ -165,7 +174,9 @@ class ConnectionManager(
// that wipes a pin would still be subject to the pre-wipe rules.
certPinStore?.let { store ->
try {
builder.certificatePinner(store.buildPinnerSnapshot())
builder.certificatePinner(
url?.let(store::buildPinnerSnapshotFor) ?: store.buildPinnerSnapshot(),
)
} catch (e: Exception) {
Log.w(TAG, "CertificatePinner build failed: ${e.message}")
builder.certificatePinner(CertificatePinner.DEFAULT)
@@ -224,10 +235,12 @@ class ConnectionManager(
// Endpoints card in Settings.
private val _activeEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeEndpoint: StateFlow<EndpointCandidate?> = _activeEndpoint.asStateFlow()
private val _activeApiEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeApiEndpoint: StateFlow<EndpointCandidate?> = _activeApiEndpoint.asStateFlow()
/** Relay-only winner, deliberately separate from the standard route. */
@Volatile
private var activeRelayEndpoint: EndpointCandidate? = null
private val _activeRelayEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeRelayEndpoint: StateFlow<EndpointCandidate?> = _activeRelayEndpoint.asStateFlow()
/**
* Manual role override. When non-null, the resolver's output is replaced
@@ -348,11 +361,14 @@ class ConnectionManager(
// behavior for freshly-upgraded installs and for v1/v2 QRs where
// the synthesized list just collapses to the same URL anyway.
scope.launch {
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val resolvedRelayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
activeRelayEndpoint = relayResolved
_activeRelayEndpoint.value = relayResolved
_activeApiEndpoint.value = apiResolved
if (resolved != null) {
_activeEndpoint.value = resolved
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
@@ -379,7 +395,7 @@ class ConnectionManager(
Log.i(
TAG,
"connect: relay resolver picked role=${relayRoute.role} " +
"url=${relayRoute.relay?.url}",
"url=${relayRoute.relayWebSocketUrl()}",
)
}
if (targetUrl != null) {
@@ -534,7 +550,8 @@ class ConnectionManager(
* for any reason we don't block the connect loop forever.
*/
suspend fun resolveBestEndpoint(): EndpointCandidate? =
resolveBestEndpointSafe(EndpointSurface.Standard)
resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
private suspend fun resolveBestEndpointSafe(
surface: EndpointSurface,
@@ -612,7 +629,9 @@ class ConnectionManager(
suspend fun probeAndReconnectNow(): EndpointCandidate? {
endpointResolver?.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
@@ -621,8 +640,9 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
if (relayResolved != null) activeRelayEndpoint = relayResolved
val targetUrl = relayResolved?.relay?.url ?: current ?: return resolved
_activeApiEndpoint.value = apiResolved
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
val normalizedTarget = normalizeRelayUrl(targetUrl)
// Reconnect when the winner changed, and also when the socket is
// stale/disconnected on the same winner. The latter makes the
@@ -659,7 +679,9 @@ class ConnectionManager(
*/
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
if (clearProbeCache) endpointResolver?.clearCache()
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
// (slow resume, mid-handoff blip) — keep publishing the live
@@ -668,6 +690,7 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
return resolved
}
@@ -684,7 +707,7 @@ class ConnectionManager(
fun getManualRoleOverride(): String? = _manualRoleOverride.value
private fun markActiveRelayEndpointUnreachable(reason: String) {
val active = activeRelayEndpoint ?: return
val active = _activeRelayEndpoint.value ?: return
endpointResolver?.markUnreachable(active, EndpointSurface.Relay)
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
}
@@ -710,7 +733,9 @@ class ConnectionManager(
// manages its own cache (clear + markUnreachable) and passes false.
if (wipeCache) endpointResolver.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null) {
// Hysteresis for the AUTOMATIC (network-callback) path. A
// transient cold-route probe miss must NOT null the published
@@ -747,6 +772,7 @@ class ConnectionManager(
}
sustainedLossDeclared = false
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
if (current == null) return@launch
// After an explicit disconnect() the route still publishes above
// (HTTP surfaces keep roaming), but no socket action: without
@@ -756,8 +782,8 @@ class ConnectionManager(
// the swap path never re-checked it.)
if (!shouldReconnect) return@launch
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (relayResolved != null) activeRelayEndpoint = relayResolved
val relayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
?: return@launch
if (isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
@@ -902,7 +928,8 @@ class ConnectionManager(
// the ViewModel on the next connection load.
_manualRoleOverride.value = null
_activeEndpoint.value = null
activeRelayEndpoint = null
_activeApiEndpoint.value = null
_activeRelayEndpoint.value = null
reconnectState.reset()
}
@@ -982,7 +1009,18 @@ class ConnectionManager(
// Every new socket starts unauthenticated — the send-gate stays closed
// (auth frame excepted) until this socket's own auth.ok arrives.
authenticated = false
client = buildClient()
val isPluginProxyUrl = _activeRelayEndpoint.value?.pluginProxyRoutesOrNull()
?.relayWebSocketUrl
?.equals(url, ignoreCase = true) == true
client = if (isPluginProxyUrl) {
proxyClientProvider?.invoke(url) ?: run {
Log.e(TAG, "Pinned plugin proxy client unavailable — refusing generic TLS fallback")
_connectionState.value = ConnectionState.Disconnected
return
}
} else {
buildClient(url)
}
val request = buildRelayRequestOrNull(url)
if (request == null) {
@@ -1240,7 +1278,7 @@ class ConnectionManager(
// during the retry window).
if (shouldReconnect && reconnectGate()) {
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val targetUrl = resolved?.relay?.url
val targetUrl = resolved?.relayWebSocketUrl()
if (resolved != null) {
// Mirror scheduleNetworkReResolve: clear the sustained-loss
// latch on a successful resolve so a later transient miss
@@ -1248,7 +1286,7 @@ class ConnectionManager(
// in onLost's grace job but can be cleared on EITHER success
// edge — network-callback or relay-timer.)
sustainedLossDeclared = false
activeRelayEndpoint = resolved
_activeRelayEndpoint.value = resolved
}
if (targetUrl != null && normalizeRelayUrl(targetUrl) != url) {
Log.i(TAG, "scheduleReconnect: switching $url → ${normalizeRelayUrl(targetUrl)}")
@@ -61,8 +61,8 @@ class ProactiveMessageHandler(
/**
* Show an inbound message inline in the Chat **Thread** it belongs to, when
* that Thread is currently open. Returns true if it was shown there — in
* which case the message is NOT also notified or added to the inbox (you're
* already looking at the conversation). The unified-Threads counterpart of
* which case the message is persisted but not also notified (you're already
* looking at the conversation). The unified-Threads counterpart of
* [toSession]; wired after construction.
*/
var injectIntoThread: ((ProactiveMessage) -> Boolean)? = null,
@@ -94,13 +94,15 @@ class ProactiveMessageHandler(
/** Route a parsed message: into the open Thread if it belongs there, else
* the durable inbox log + the surface its hint selects. */
private fun dispatch(msg: ProactiveMessage) {
// Unified Threads: if this message belongs to the Thread currently open
// in Chat, render it inline there and STOP — no notification, no inbox
// entry (you're already looking at the conversation).
if (injectIntoThread?.invoke(msg) == true) return
// Otherwise the inbox is the durable log of agent-initiated messages and
// the surfacing hint selects the additional surface.
// Persist first even when the currently open Thread consumes the live
// message. Agent-initiated outbound sends do not create a gateway
// session until the phone replies, so this cache is the provisional
// Thread transcript during that gap.
toInbox?.invoke(msg)
// Unified Threads: if this message belongs to the Thread currently open
// in Chat, render it inline there and stop before raising a notification.
if (injectIntoThread?.invoke(msg) == true) return
// The surfacing hint selects the additional surface.
when (msg.surfacing?.lowercase()) {
"inbox" -> { /* inbox only — already recorded above */ }
"session" -> {
@@ -7,6 +7,8 @@ import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerializationException
@@ -48,7 +50,7 @@ class RelayProfileInspectorClient(
private val okHttpClient: OkHttpClient,
private val relayUrlProvider: () -> String?,
private val sessionTokenProvider: suspend () -> String?,
) {
) : LegacyProfileInspectorClient {
companion object {
private const val TAG = "RelayProfileInspector"
@@ -79,19 +81,19 @@ class RelayProfileInspectorClient(
/** Fetch `GET /api/profiles/{name}/config`. */
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
get(profileName, "config", ProfileConfigResponse.serializer())
/** Fetch `GET /api/profiles/{name}/skills`. */
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
override suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
get(profileName, "skills", ProfileSkillsResponse.serializer())
/** Fetch `GET /api/profiles/{name}/soul`. */
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
override suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
get(profileName, "soul", ProfileSoulResponse.serializer())
/** Fetch `GET /api/profiles/{name}/memory`. */
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
override suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
get(profileName, "memory", ProfileMemoryResponse.serializer())
/**
@@ -108,7 +110,7 @@ class RelayProfileInspectorClient(
* would be a protocol violation; we send empty-string for an empty
* SOUL.
*/
suspend fun updateSoul(
override suspend fun updateSoul(
profileName: String,
content: String,
): Result<ProfileSoulUpdateResponse> = withContext(Dispatchers.IO) {
@@ -137,7 +139,7 @@ class RelayProfileInspectorClient(
* Used for both creating a new memory entry (the relay writes the
* file if missing) and updating an existing entry.
*/
suspend fun updateMemoryEntry(
override suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
@@ -270,10 +272,10 @@ class RelayProfileInspectorClient(
* server" snackbar and ghost out the toggle. When the real
* implementation lands server-side, this method needs no change.
*/
suspend fun updateSkillToggle(
override suspend fun updateSkillToggle(
skillName: String,
enabled: Boolean,
): Result<SkillToggleResult> = withContext(Dispatchers.IO) {
): Result<RelaySkillToggleResult> = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) {
return@withContext Result.failure(
@@ -319,8 +321,8 @@ class RelayProfileInspectorClient(
try {
okHttpClient.newCall(request).execute().use { response ->
when (response.code) {
in 200..299 -> Result.success(SkillToggleResult.Ok)
501 -> Result.success(SkillToggleResult.NotImplemented)
in 200..299 -> Result.success(RelaySkillToggleResult.Ok)
501 -> Result.success(RelaySkillToggleResult.NotImplemented)
401, 403 -> Result.failure(
IOException("Unauthorized — re-pair with the relay")
)
@@ -348,7 +350,7 @@ class RelayProfileInspectorClient(
* "not implemented" and any 2xx as "supported". The relay serves
* OPTIONS via aiohttp's CORS handling by default.
*/
suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
override suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) return@withContext false
val sessionToken = sessionTokenProvider() ?: return@withContext false
@@ -402,11 +404,6 @@ class RelayProfileInspectorClient(
* answered 501 — not implemented yet" without inventing magic
* error strings.
*/
sealed class SkillToggleResult {
data object Ok : SkillToggleResult()
data object NotImplemented : SkillToggleResult()
}
/**
* Best-effort pull of a `detail` or `error` string out of a relay
* 400 body. Falls back to the first 120 chars of the payload when
@@ -55,6 +55,8 @@ data class RouteProbeOutcome(
*/
enum class EndpointSurface {
Standard,
Dashboard,
Api,
Relay,
}
@@ -109,6 +111,8 @@ class EndpointResolver(
* expected path for plain JVM tests.
*/
private val context: Context? = null,
/** Route-aware client for pinned plugin proxy probes. */
private val clientForCandidate: ((EndpointCandidate) -> OkHttpClient?)? = null,
) {
/**
@@ -196,8 +200,13 @@ class EndpointResolver(
val authority = when (surface) {
EndpointSurface.Standard ->
candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()
EndpointSurface.Dashboard ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url).orEmpty()
EndpointSurface.Api ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url).orEmpty()
EndpointSurface.Relay ->
routeAuthority(candidate.relay?.url).orEmpty()
candidate.pluginProxyRoutesOrNull()?.authority
?: routeAuthority(candidate.relay?.url).orEmpty()
}
return "${surface.name.lowercase()}|${candidate.role}|$authority"
}
@@ -239,11 +248,16 @@ class EndpointResolver(
val eligible = candidates.filter { probeTarget(it, surface) != null }
if (eligible.isEmpty()) return null
// Strict priority: sort ascending so priority-0 lands first. Grouping
// preserves emitted order within a priority class (DNS SRV parity).
val groups = eligible.groupBy { it.priority }.toSortedMap()
// Supported routes always run before experimental routes. Priority is
// strict inside each stability tier, so Reach remains available as a
// last-resort fallback without displacing Tailscale or direct TLS.
val supported = eligible.filterNot { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val experimental = eligible.filter { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val groups = (supported.groupBy { it.priority }.toSortedMap().values +
experimental.groupBy { it.priority }.toSortedMap().values)
for ((priority, group) in groups) {
for (group in groups) {
val priority = group.first().priority
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
val winner = raceGroup(group, surface)
if (winner != null) {
@@ -356,6 +370,8 @@ class EndpointResolver(
val startedAtMs = clock()
val operation = when (surface) {
EndpointSurface.Standard -> "Dashboard or API route health probe"
EndpointSurface.Dashboard -> "Dashboard route health probe"
EndpointSurface.Api -> "API route health probe"
EndpointSurface.Relay -> "Relay route health probe"
}
val target = probeTarget(candidate, surface)
@@ -375,7 +391,7 @@ class EndpointResolver(
recordOutcome(candidate, surface, reachable = false, detail = "Invalid route URL")
return false
}
val fastClient = httpClient.newBuilder()
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.readTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
@@ -480,6 +496,29 @@ class EndpointResolver(
candidate: EndpointCandidate,
surface: EndpointSurface,
): ProbeTarget? {
if (surface == EndpointSurface.Dashboard) {
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { base ->
return ProbeTarget(base, "$base/api/status", "/dashboard/api/status")
}
candidate.dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }?.let { base ->
return ProbeTarget(base, "$base/api/status", "/api/status")
}
return null
}
if (surface == EndpointSurface.Api) {
candidate.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { base ->
return ProbeTarget(base, "$base/health", "/api/health")
}
candidate.api?.url?.let { base -> return ProbeTarget(base, "$base/health", "/health") }
return null
}
if (surface == EndpointSurface.Relay) candidate.pluginProxyRoutesOrNull()?.let { proxy ->
return ProbeTarget(
baseUrl = proxy.relayHttpUrl,
requestUrl = "${proxy.relayHttpUrl}/health",
path = "/relay/health",
)
}
if (surface == EndpointSurface.Relay) {
return relayProbeTarget(candidate)
}
@@ -529,6 +568,11 @@ class EndpointResolver(
return null
}
internal fun probeRequestUrlForTest(
candidate: EndpointCandidate,
surface: EndpointSurface,
): String? = probeTarget(candidate, surface)?.requestUrl
/**
* Map a probe exception to a short, actionable string for the Routes
* card. The TLS case is the headline: a route saved with `https://`
@@ -546,6 +590,8 @@ class EndpointResolver(
private fun EndpointSurface.diagnosticTarget(): String = when (this) {
EndpointSurface.Standard -> "Dashboard or API server"
EndpointSurface.Dashboard -> "Dashboard"
EndpointSurface.Api -> "API server"
EndpointSurface.Relay -> "Relay"
}
@@ -0,0 +1,402 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.isValidHermesReach
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.net.SocketException
import java.net.URI
import java.security.SecureRandom
import java.util.Base64
import java.util.ArrayDeque
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.net.SocketFactory
private const val REACH_PROTOCOL_VERSION = 1
private const val REACH_MAX_FRAME_BYTES = 1024 * 1024
internal const val REACH_MAX_QUEUED_FRAMES = 32
internal const val REACH_MAX_QUEUED_BYTES = 8 * 1024 * 1024
private const val REACH_MATCH_TIMEOUT_MS = 10_000L
/**
* Connection metadata for Hermes Reach's outer WSS rendezvous.
*
* This is deliberately transport-only. The inner HTTPS/WSS origin and its
* pairing-authenticated SPKI pin continue to be owned by [PluginProxyRoutes],
* so broker reachability can never weaken Secure Link trust.
*/
data class HermesReachRoute(
val brokerUrl: String,
val hostId: String,
val credentialKind: String,
val token: String,
) {
fun tunnelUrlOrNull(): String? {
if (hostId.isBlank() || token.isBlank()) return null
if (credentialKind !in setOf("bootstrap", "route")) return null
val uri = runCatching { URI(brokerUrl.trim()) }.getOrNull() ?: return null
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return null
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" && it != "/v1/connect" }) return null
val authority = buildString {
append(if (':' in uri.host) "[${uri.host}]" else uri.host)
if (uri.port > 0 && uri.port != 443) append(":${uri.port}")
}
return "wss://$authority/v1/connect"
}
}
fun EndpointCandidate.hermesReachRouteOrNull(): HermesReachRoute? {
val metadata = broker?.takeIf { it.isValidHermesReach() } ?: return null
if (pluginProxyRoutesOrNull() == null) return null
return HermesReachRoute(
brokerUrl = metadata.url,
hostId = metadata.hostId,
credentialKind = metadata.credentialKind,
token = metadata.token,
)
}
/** Build the pinned inner Secure Link client over an outer Hermes Reach WSS. */
fun buildHermesReachClient(
baseBuilder: OkHttpClient.Builder,
outerClient: OkHttpClient,
candidate: EndpointCandidate,
sessionTokenProvider: () -> String?,
includeRelaySessionHeader: Boolean = true,
): OkHttpClient? {
val secureLink = candidate.pluginProxyRoutesOrNull() ?: return null
val reach = candidate.hermesReachRouteOrNull() ?: return null
return buildPluginProxyClient(
baseBuilder = baseBuilder,
routes = secureLink,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
rawSocketFactory = HermesReachSocketFactory(outerClient, reach),
)
}
@Serializable
private data class ReachRegistration(
val type: String = "register",
@SerialName("protocol_version") val protocolVersion: Int = REACH_PROTOCOL_VERSION,
val role: String = "client",
@SerialName("host_id") val hostId: String,
@SerialName("connection_id") val connectionId: String,
@SerialName("credential_kind") val credentialKind: String,
val token: String,
)
@Serializable
private data class ReachControl(
val type: String? = null,
@SerialName("protocol_version") val protocolVersion: Int? = null,
@SerialName("stream_id") val streamId: String? = null,
val code: String? = null,
)
internal object HermesReachHandshake {
private val json = Json {
ignoreUnknownKeys = false
encodeDefaults = true
}
fun registration(route: HermesReachRoute, connectionId: String): String = json.encodeToString(
ReachRegistration(
hostId = route.hostId,
connectionId = connectionId,
credentialKind = route.credentialKind,
token = route.token,
),
)
fun validateMatched(payload: String): String? {
val control = runCatching { json.decodeFromString<ReachControl>(payload) }
.getOrElse { return "Hermes Reach returned an invalid match response" }
if (control.type == "error") {
return "Hermes Reach rejected the route (${control.code ?: "unknown"})"
}
val streamIdValid = control.streamId?.let(::isCanonicalId) == true
if (control.type != "matched" ||
control.protocolVersion != REACH_PROTOCOL_VERSION ||
!streamIdValid
) {
return "Hermes Reach returned a mismatched route response"
}
return null
}
private fun isCanonicalId(value: String): Boolean {
if (value.isBlank() || '=' in value) return false
val decoded = runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull() ?: return false
return decoded.size == 16 && Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == value
}
}
/**
* Raw socket factory that carries bytes through Hermes Reach. OkHttp layers
* the normal Secure Link TLS socket factory over the returned socket, so SNI,
* hostname verification, and the QR SPKI pin all apply to the inner endpoint.
*/
class HermesReachSocketFactory(
private val outerClient: OkHttpClient,
private val route: HermesReachRoute,
) : SocketFactory() {
init {
require(route.tunnelUrlOrNull() != null) { "Invalid Hermes Reach route" }
}
override fun createSocket(): Socket = HermesReachSocket(outerClient, route)
override fun createSocket(host: String?, port: Int): Socket =
createSocket().apply { connect(InetSocketAddress(host, port)) }
override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket =
createSocket().apply {
if (localHost != null) bind(InetSocketAddress(localHost, localPort))
connect(InetSocketAddress(host, port))
}
override fun createSocket(host: InetAddress?, port: Int): Socket =
createSocket().apply { connect(InetSocketAddress(host, port)) }
override fun createSocket(
address: InetAddress?,
port: Int,
localAddress: InetAddress?,
localPort: Int,
): Socket = createSocket().apply {
if (localAddress != null) bind(InetSocketAddress(localAddress, localPort))
connect(InetSocketAddress(address, port))
}
}
private class HermesReachSocket(
private val outerClient: OkHttpClient,
private val route: HermesReachRoute,
) : Socket() {
private val inbound = ReachInputStream()
private val matchLatch = CountDownLatch(1)
private val connectionId = randomConnectionId()
@Volatile private var matchError: IOException? = null
@Volatile private var webSocket: WebSocket? = null
@Volatile private var connected = false
@Volatile private var closed = false
@Volatile private var matched = false
@Volatile private var remote: InetSocketAddress? = null
private var readTimeoutMs: Int = 0
private val outbound = object : OutputStream() {
override fun write(value: Int) = write(byteArrayOf(value.toByte()))
override fun write(bytes: ByteArray, offset: Int, length: Int) {
if (length == 0) return
if (!matched || closed) throw SocketException("Hermes Reach tunnel is not open")
var cursor = offset
var remaining = length
while (remaining > 0) {
val count = minOf(remaining, REACH_MAX_FRAME_BYTES)
val accepted = webSocket?.send(ByteString.of(*bytes.copyOfRange(cursor, cursor + count))) == true
if (!accepted) throw SocketException("Hermes Reach could not queue tunnel bytes")
cursor += count
remaining -= count
}
}
}
override fun connect(endpoint: SocketAddress?) = connect(endpoint, REACH_MATCH_TIMEOUT_MS.toInt())
override fun connect(endpoint: SocketAddress?, timeout: Int) {
if (connected) throw SocketException("Socket is already connected")
if (closed) throw SocketException("Socket is closed")
remote = endpoint as? InetSocketAddress
?: throw SocketException("Hermes Reach requires an internet socket target")
val request = Request.Builder().url(requireNotNull(route.tunnelUrlOrNull())).build()
webSocket = outerClient.newWebSocket(request, listener)
val waitMs = minOf(
timeout.takeIf { it > 0 }?.toLong() ?: REACH_MATCH_TIMEOUT_MS,
REACH_MATCH_TIMEOUT_MS,
)
if (!matchLatch.await(waitMs, TimeUnit.MILLISECONDS)) {
closeWithError(IOException("Hermes Reach host match timed out"))
}
matchError?.let { throw it }
if (!matched) throw IOException("Hermes Reach closed before matching the host")
connected = true
}
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
val registration = HermesReachHandshake.registration(route, connectionId)
if (!webSocket.send(registration)) {
closeWithError(IOException("Hermes Reach registration could not be sent"))
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
if (matched) {
closeWithError(IOException("Hermes Reach sent text after matching"))
return
}
HermesReachHandshake.validateMatched(text)?.let { message ->
closeWithError(IOException(message))
return
}
matched = true
matchLatch.countDown()
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
if (!matched) {
closeWithError(IOException("Hermes Reach sent bytes before matching"))
return
}
if (bytes.size > REACH_MAX_FRAME_BYTES) {
closeWithError(IOException("Hermes Reach frame exceeds 1 MiB"))
return
}
if (!inbound.offer(bytes.toByteArray())) {
closeWithError(IOException("Hermes Reach receive queue exceeded its safe limit"))
}
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(code, null)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
if (!matched) matchError = IOException("Hermes Reach closed before matching the host")
closed = true
inbound.close(matchError)
matchLatch.countDown()
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
closeWithError(IOException("Hermes Reach connection failed", t))
}
}
private fun closeWithError(error: IOException) {
matchError = error
closed = true
webSocket?.cancel()
inbound.close(error)
matchLatch.countDown()
}
override fun getInputStream(): InputStream {
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
inbound.readTimeoutMs = readTimeoutMs
return inbound
}
override fun getOutputStream(): OutputStream {
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
return outbound
}
override fun close() {
if (closed) return
closed = true
webSocket?.close(1000, null)
inbound.close(null)
matchLatch.countDown()
}
override fun isConnected(): Boolean = connected
override fun isClosed(): Boolean = closed
override fun getRemoteSocketAddress(): SocketAddress? = remote
override fun getInetAddress(): InetAddress? = remote?.address
override fun getPort(): Int = remote?.port ?: 0
override fun setSoTimeout(timeout: Int) { readTimeoutMs = timeout }
override fun getSoTimeout(): Int = readTimeoutMs
override fun setTcpNoDelay(on: Boolean) = Unit
override fun getTcpNoDelay(): Boolean = true
override fun setKeepAlive(on: Boolean) = Unit
override fun getKeepAlive(): Boolean = true
override fun setReuseAddress(on: Boolean) = Unit
override fun getReuseAddress(): Boolean = false
}
internal class ReachInputStream : InputStream() {
private val chunks = ArrayDeque<ByteArray>()
private var offset = 0
private var queuedBytes = 0
private var terminalError: IOException? = null
private var closed = false
@Volatile var readTimeoutMs: Int = 0
@Synchronized
fun offer(bytes: ByteArray): Boolean {
if (closed) return false
if (chunks.size >= REACH_MAX_QUEUED_FRAMES || queuedBytes + bytes.size > REACH_MAX_QUEUED_BYTES) {
return false
}
chunks.addLast(bytes)
queuedBytes += bytes.size
(this as java.lang.Object).notifyAll()
return true
}
@Synchronized
fun close(error: IOException?) {
if (closed) return
closed = true
terminalError = error
(this as java.lang.Object).notifyAll()
}
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff
}
@Synchronized
override fun read(target: ByteArray, targetOffset: Int, length: Int): Int {
if (length == 0) return 0
val started = System.nanoTime()
while (chunks.isEmpty() && !closed) {
val waitMs = if (readTimeoutMs > 0) {
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)
(readTimeoutMs - elapsed).coerceAtLeast(0)
} else 0L
if (readTimeoutMs > 0 && waitMs == 0L) throw java.net.SocketTimeoutException("Hermes Reach read timed out")
(this as java.lang.Object).wait(if (readTimeoutMs > 0) waitMs else 0L)
}
if (chunks.isEmpty()) {
terminalError?.let { throw it }
return -1
}
val chunk = chunks.first()
val count = minOf(length, chunk.size - offset)
chunk.copyInto(target, targetOffset, offset, offset + count)
offset += count
queuedBytes -= count
if (offset == chunk.size) {
chunks.remove(chunk)
offset = 0
}
return count
}
}
private fun randomConnectionId(): String {
val bytes = ByteArray(16).also(SecureRandom()::nextBytes)
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
}
@@ -0,0 +1,145 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.data.isValidPinnedProxy
import okhttp3.CertificatePinner
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.net.URI
import java.security.KeyStore
import java.security.MessageDigest
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
import javax.net.SocketFactory
/** Runtime endpoints exposed beneath one plugin-owned pinned-TLS origin. */
data class PluginProxyRoutes(
val authority: String,
val host: String,
val port: Int,
val relayHttpUrl: String,
val relayWebSocketUrl: String,
val apiBaseUrl: String?,
val dashboardBaseUrl: String?,
val pinSha256: String,
)
/**
* Resolve and validate the pairing-advertised proxy contract. Invalid or
* incomplete advertisements are never treated as secure routes.
*/
fun ProxyEndpoint.toPluginProxyRoutesOrNull(): PluginProxyRoutes? {
if (!isValidPinnedProxy()) return null
val base = url.trim().trimEnd('/')
val uri = runCatching { URI(base) }.getOrNull() ?: return null
if (!uri.scheme.equals("https", ignoreCase = true)) return null
val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return null
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
val rawPath = uri.rawPath.orEmpty()
if (rawPath.isNotEmpty() && rawPath != "/") return null
val port = if (uri.port > 0) uri.port else 443
val pin = pinSha256!!.trim()
val authority = "$host:$port"
val wsBase = "wss://${formatHost(host)}${if (port == 443) "" else ":$port"}$rawPath"
.trimEnd('/')
val surfaces = surfaces.map(String::lowercase).toSet()
return PluginProxyRoutes(
authority = authority,
host = host,
port = port,
relayHttpUrl = "$base/relay",
relayWebSocketUrl = "$wsBase/relay/ws",
apiBaseUrl = "$base/api".takeIf { "api" in surfaces },
dashboardBaseUrl = "$base/dashboard".takeIf { "dashboard" in surfaces },
pinSha256 = pin,
)
}
fun EndpointCandidate.pluginProxyRoutesOrNull(): PluginProxyRoutes? =
proxy?.toPluginProxyRoutesOrNull()
private fun formatHost(host: String): String = if (':' in host) "[$host]" else host
/**
* Build a client that trusts the system normally, plus exactly the
* pairing-advertised SPKI for this proxy. The authority guard keeps a pin
* scoped to host *and port*; OkHttp's CertificatePinner alone is host-only.
*/
fun buildPluginProxyClient(
baseBuilder: OkHttpClient.Builder,
routes: PluginProxyRoutes,
sessionTokenProvider: () -> String?,
includeRelaySessionHeader: Boolean = true,
rawSocketFactory: SocketFactory? = null,
): OkHttpClient {
val expectedHost = routes.host
val expectedPort = routes.port
val systemTrust = systemTrustManager()
val pinnedTrust = PinnedOrSystemTrustManager(systemTrust, routes.pinSha256)
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, arrayOf(pinnedTrust), SecureRandom())
}
if (rawSocketFactory != null) baseBuilder.socketFactory(rawSocketFactory)
return baseBuilder
.sslSocketFactory(sslContext.socketFactory, pinnedTrust)
.certificatePinner(
CertificatePinner.Builder().add(expectedHost, routes.pinSha256).build(),
)
.addNetworkInterceptor(Interceptor { chain ->
val requestUrl = chain.request().url
if (!requestUrl.host.equals(expectedHost, ignoreCase = true) ||
requestUrl.port != expectedPort
) {
throw java.io.IOException("Pinned proxy redirect left its paired authority")
}
val token = sessionTokenProvider().takeIf { includeRelaySessionHeader }
?.takeIf { it.isNotBlank() }
val request = if (token != null) {
chain.request().newBuilder()
.header("X-Hermes-Relay-Session", token)
.build()
} else {
chain.request()
}
chain.proceed(request)
})
.build()
}
private fun systemTrustManager(): X509TrustManager {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(null as KeyStore?)
return factory.trustManagers.filterIsInstance<X509TrustManager>().single()
}
private class PinnedOrSystemTrustManager(
private val system: X509TrustManager,
private val expectedPin: String,
) : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) =
system.checkClientTrusted(chain, authType)
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
val certificates = chain?.takeIf { it.isNotEmpty() }
?: throw CertificateException("Proxy supplied no certificate chain")
val systemAccepted = runCatching { system.checkServerTrusted(chain, authType) }.isSuccess
if (systemAccepted) return
val leaf = certificates.first()
leaf.checkValidity()
val actual = "sha256/" + java.util.Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-256").digest(leaf.publicKey.encoded),
)
if (!MessageDigest.isEqual(actual.toByteArray(), expectedPin.toByteArray())) {
throw CertificateException("Plugin proxy certificate does not match the paired pin")
}
}
override fun getAcceptedIssuers(): Array<X509Certificate> = system.acceptedIssuers
}
@@ -524,6 +524,29 @@ class ChatHandler {
}
}
/**
* Rebind visible user turns after Gateway rewrites a truncated durable
* prefix. The response is positional in the same user-ordinal space used
* for edit/regenerate. Missing entries clear cached ids so a later rewind
* cannot accidentally send an archived pre-rewrite row id.
*/
fun rebindSurvivorUserRowIds(rowIds: List<Long?>) {
var ordinal = 0
_messages.update { messages ->
messages.map { message ->
if (!message.isGatewayRewindUser()) return@map message
val rebound = rowIds.getOrNull(ordinal)
ordinal += 1
if (message.rowId == rebound) message else message.copy(rowId = rebound)
}
}
}
private fun ChatMessage.isGatewayRewindUser(): Boolean =
role == MessageRole.USER &&
!id.startsWith("voice-intent-") &&
!id.startsWith("steer-")
fun replaceMessageContent(messageId: String, content: String) {
_messages.update { messages ->
messages.map { message ->
@@ -1497,6 +1520,8 @@ class ChatHandler {
// this as the same visible row across the post-turn reload.
prior.copy(
id = messageId,
rowId = item.resolvedRowId,
reactions = item.reactions,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -1527,6 +1552,8 @@ class ChatHandler {
// nothing local to carry).
ChatMessage(
id = messageId,
rowId = item.resolvedRowId,
reactions = item.reactions,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -2025,6 +2052,11 @@ class ChatHandler {
title = resolvedTitle,
model = item.model,
messageCount = item.messageCount ?: 0,
inputTokens = item.inputTokens ?: 0,
outputTokens = item.outputTokens ?: 0,
actualCostUsd = item.actualCostUsd,
estimatedCostUsd = item.estimatedCostUsd,
isActive = item.isActive,
updatedAt = activityAtMs,
startedAt = startedAtMs,
lastActivityAt = lastActivityAtMs,
@@ -75,6 +75,23 @@ data class DashboardGatewayTopology(
@SerialName("served_profiles") val servedProfiles: List<String> = emptyList(),
)
/**
* Return only profiles the launch gateway positively reports as served.
*
* `/api/status.profiles` is the installed-profile inventory. Selective
* multiplex serving can exclude an installed profile, so that list must never
* authorize construction of a `/p/<profile>` API fallback route.
*/
internal fun DashboardStatus.multiplexServedProfiles(): List<String> {
if (!gatewayMode.equals("multiplex", ignoreCase = true)) return emptyList()
return gateways.firstOrNull { it.profile.equals("default", ignoreCase = true) }
?.servedProfiles
.orEmpty()
.map(String::trim)
.filter(String::isNotBlank)
.distinct()
}
@Serializable
data class DashboardComponentHealthRollup(
val supported: Boolean = false,
@@ -1,6 +1,14 @@
package com.hermesandroid.relay.network.upstream
import android.util.Log
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.GatewayProfileSkill
import com.hermesandroid.relay.data.GatewayProfileToolset
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.UsageInfo
import com.hermesandroid.relay.util.AppForegroundTracker
@@ -90,9 +98,11 @@ class GatewayChatClient(
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
/** Random source for ordinary reconnect full-jitter. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
) {
) : GatewayProfileEditorClient {
/** Existing upstream rich-chat vocabulary; do not invent a Relay-only source. */
private val sessionSource = "webui"
@Volatile
private var profileEditorSupported: Boolean? = null
companion object {
private const val TAG = "GatewayChatClient"
@@ -513,6 +523,10 @@ class GatewayChatClient(
* into the session's USER messages (counted from the first user
* message). The server drops that message and everything after it
* before running [text] as a fresh turn.
* @param truncateBeforeRowId durable identity of the same target user row
* when current Gateway history supplied one. Sent alongside the ordinal
* so the server can fail closed if local position and durable identity
* diverge; omitted for older Gateway history without row ids.
* @param queuedFollowUp true only when Android is draining a prompt the
* user explicitly queued behind an active turn. Newer gateways use the
* additive `queued:true` marker to preserve run-after semantics while
@@ -530,7 +544,9 @@ class GatewayChatClient(
callbacks: GatewayTurnCallbacks,
attachments: List<GatewayAttachment> = emptyList(),
truncateBeforeUserOrdinal: Int? = null,
truncateBeforeRowId: Long? = null,
queuedFollowUp: Boolean = false,
onSurvivorUserRowIds: (List<Long?>) -> Unit = { },
onPreflightFailure: (reason: String) -> Unit,
): ActiveTurnHandle {
val turn = GatewayTurn(dispatchOn(callbacks))
@@ -552,25 +568,42 @@ class GatewayChatClient(
turn.tracer.mark("session")
}
if (turn.cancelled) return@launch
attachments.forEach { attachment ->
uploadAttachment(attachment).getOrElse { e ->
val attachmentRefs = attachments.mapNotNull { attachment ->
val upload = uploadAttachment(attachment).getOrElse { e ->
throw GatewayPreflightException("attachment upload failed: ${e.message}")
}
if (attachment.requiresPromptReference()) {
upload.stringField("ref_text")
?: throw GatewayPreflightException(
"attachment upload failed: Hermes returned no readable file reference",
)
} else {
null
}
}
if (turn.cancelled) return@launch
if (!awaitCancelledTurnDrain(turn, storedSessionId)) return@launch
activeTurn = turn
turn.armWatchdog()
// Generic `file.attach` uploads are staged artifacts, not
// session-owned image/PDF attachments. The gateway returns
// the exact workspace/sandbox-safe `@file:` reference that
// must accompany this prompt. Keep the user's prose last,
// matching upstream Desktop's context-reference contract.
val submittedText = (attachmentRefs + text)
.filter(String::isNotBlank)
.joinToString("\n\n")
val submitted = rpc(
"prompt.submit",
buildJsonObject {
put("session_id", liveSessionId ?: error("no live session"))
put("text", text)
put("text", submittedText)
truncateBeforeUserOrdinal?.let { ordinal ->
put("truncate_before_user_ordinal", ordinal)
put("confirm_truncate", true)
if (ordinal == 0) put("confirm_empty_truncate", true)
}
truncateBeforeRowId?.let { put("truncate_before_row_id", it) }
if (queuedFollowUp) put("queued", true)
},
// Long-running RPC, not a generic 15s ack — see the
@@ -613,12 +646,25 @@ class GatewayChatClient(
submitError?.message ?: "prompt.submit failed",
)
}
(submitted.getOrNull()?.get("survivor_user_row_ids") as? JsonArray)?.let { raw ->
val rebound = raw.map { element ->
(element as? JsonPrimitive)?.longOrNull
}
callbackDispatcher { onSurvivorUserRowIds(rebound) }
}
turn.tracer.mark("submit")
// One INFO line per turn so logcat shows which transport
// served a send — the SSE paths log their SSE events, and
// a silent happy path here made on-device verification a
// read-the-absence exercise.
Log.i(TAG, "Gateway turn submitted (session=$storedSessionId)")
} catch (e: GatewayAuthoritativeResumeException) {
if (activeTurn === turn) activeTurn = null
if (!turn.cancelled) {
turn.disarmWatchdog()
turn.tracer.done("resume-rejected")
turn.callbacks.onError(e.message ?: "Hermes could not resume this session")
}
} catch (e: Exception) {
if (activeTurn === turn) activeTurn = null
if (!turn.cancelled) {
@@ -1107,8 +1153,14 @@ class GatewayChatClient(
private fun JsonObject.toGatewayCompressResult(): GatewayCompressResult =
GatewayCompressResult(
status = stringField("status") ?: "completed",
output = stringField("output"),
status = stringField("status") ?: if (
(this["compressed"] as? JsonPrimitive)?.booleanOrNull == false
) {
"noop"
} else {
"completed"
},
output = stringField("output") ?: stringField("message"),
removed = (this["removed"] as? JsonPrimitive)?.intOrNull,
beforeMessages = (this["before_messages"] as? JsonPrimitive)?.intOrNull,
afterMessages = (this["after_messages"] as? JsonPrimitive)?.intOrNull,
@@ -1228,6 +1280,120 @@ class GatewayChatClient(
.onSuccess { commandsCatalogCache = it }
}
/**
* Capability probe and authoritative editor snapshot. A method-not-found
* response is sticky for this client so older Hermes builds keep using the
* existing Relay inspector without repeatedly sending unsupported RPCs.
*/
override suspend fun describeProfile(
profileName: String,
): Result<GatewayProfileDescription> {
if (profileEditorSupported == false) {
return Result.failure(GatewayProfileEditorUnsupportedException())
}
val name = profileName.trim()
if (name.isEmpty()) return Result.failure(IllegalArgumentException("profile name required"))
try {
connectMutex.withLock { ensureConnected() }
} catch (e: Exception) {
return Result.failure(e)
}
val response = rpc(
"profiles.describe",
buildJsonObject { put("name", name) },
)
val error = response.exceptionOrNull()
if (error.isMethodNotFound()) {
profileEditorSupported = false
return Result.failure(GatewayProfileEditorUnsupportedException())
}
return response.mapCatching { payload ->
parseProfileDescription(payload, expectedName = name)
}.onSuccess {
profileEditorSupported = true
}
}
/** Apply only fields explicitly present in [patch]; requires a successful describe first. */
override suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult> {
if (profileEditorSupported != true) {
return Result.failure(GatewayProfileEditorUnsupportedException())
}
val name = profileName.trim()
if (name.isEmpty()) return Result.failure(IllegalArgumentException("profile name required"))
if ((patch.provider == null) != (patch.model == null)) {
return Result.failure(IllegalArgumentException("provider and model must be saved together"))
}
val requested = patch.requestedSections
if (requested.isEmpty()) return Result.success(GatewayProfileConfigureResult(emptySet(), emptySet()))
val params = buildJsonObject {
put("name", name)
patch.description?.let { put("description", it) }
patch.soul?.let { put("soul", it) }
patch.provider?.let { put("provider", it) }
patch.model?.let { put("model", it) }
patch.disabledSkills?.let { names ->
put("disabled_skills", JsonArray(names.map(::JsonPrimitive)))
}
patch.enabledToolsets?.let { names ->
put("enabled_toolsets", JsonArray(names.map(::JsonPrimitive)))
}
}
return rpc("profiles.configure", params).mapCatching { payload ->
val appliedObject = payload["applied"] as? JsonObject
?: throw GatewayRpcException("profiles.configure returned no applied map")
val applied = requested.filterTo(linkedSetOf()) { section ->
(appliedObject[section.wireName] as? JsonPrimitive)?.booleanOrNull == true
}
GatewayProfileConfigureResult(requested = requested, applied = applied)
}
}
private fun parseProfileDescription(
payload: JsonObject,
expectedName: String,
): GatewayProfileDescription {
val name = payload.stringField("name")
?: throw GatewayRpcException("profiles.describe returned no profile name")
if (name != expectedName) {
throw GatewayRpcException("profiles.describe returned a different profile")
}
val model = payload["model"] as? JsonObject ?: JsonObject(emptyMap())
val skills = (payload["skills"] as? JsonArray).orEmpty().mapNotNull { item ->
val obj = item as? JsonObject ?: return@mapNotNull null
val skillName = obj.stringField("name")?.takeIf(String::isNotBlank)
?: return@mapNotNull null
GatewayProfileSkill(
name = skillName,
enabled = (obj["enabled"] as? JsonPrimitive)?.booleanOrNull ?: true,
)
}
val toolsets = (payload["toolsets"] as? JsonArray).orEmpty().mapNotNull { item ->
val obj = item as? JsonObject ?: return@mapNotNull null
val toolsetName = obj.stringField("name")?.takeIf(String::isNotBlank)
?: return@mapNotNull null
GatewayProfileToolset(
name = toolsetName,
description = obj.stringField("description").orEmpty(),
toolCount = (obj["tool_count"] as? JsonPrimitive)?.intOrNull ?: 0,
enabled = (obj["enabled"] as? JsonPrimitive)?.booleanOrNull ?: true,
)
}
return GatewayProfileDescription(
name = name,
description = payload.stringField("description").orEmpty(),
soul = payload.stringField("soul").orEmpty(),
provider = model.stringField("provider").orEmpty(),
model = model.stringField("default").orEmpty(),
skills = skills,
toolsets = toolsets,
toolsetsPinned = (payload["toolsets_pinned"] as? JsonPrimitive)?.booleanOrNull ?: false,
)
}
/**
* Fetch the upstream gateway's cropped preview for a Petdex pet.
*
@@ -1495,7 +1661,7 @@ class GatewayChatClient(
* id. This follows the upstream gateway contract, which resolves the row
* atomically inside the active session. A null emoji removes the reaction.
*/
suspend fun reactToNewest(role: String, emoji: String?): Result<JsonObject> {
suspend fun reactToMessage(rowId: Long?, role: String, emoji: String?): Result<JsonObject> {
require(role == "user" || role == "assistant") { "unsupported reaction role" }
val sid = liveSessionId
?: return Result.failure(GatewayRpcException("no live session"))
@@ -1503,7 +1669,7 @@ class GatewayChatClient(
"message.react",
buildJsonObject {
put("session_id", sid)
put("newest_role", role)
if (rowId != null) put("row_id", rowId) else put("newest_role", role)
if (emoji == null) put("emoji", JsonNull) else put("emoji", emoji)
put("author", "user")
},
@@ -1993,6 +2159,12 @@ class GatewayChatClient(
},
)
val result = resumed.getOrNull()
val resumeError = resumed.exceptionOrNull()
if ((resumeError as? GatewayRpcException)?.code == 4130) {
throw GatewayAuthoritativeResumeException(
resumeError.message ?: "Session transcript exceeds the configured resume limit",
)
}
val live = result?.stringField("session_id")
if (live != null) {
liveSessionId = live
@@ -2683,6 +2855,11 @@ class GatewayChatClient(
}
}
private fun GatewayAttachment.requiresPromptReference(): Boolean {
val mime = contentType.substringBefore(';').trim().lowercase()
return !mime.startsWith("image/") && mime != "application/pdf"
}
/**
* Upload one image. Tries the upstream RPC name first; on method-not-found
* falls back ONCE per socket to the legacy dotted name (older builds
@@ -3161,14 +3338,21 @@ internal class GatewayPreflightException(message: String) : Exception(message)
/** One connect attempt failed; [GatewayChatClient] may retry with a fresh ticket. */
internal class GatewayConnectAttemptException(message: String) : Exception(message)
/** Server intentionally refused a durable resume; never create/fallback into a context-free turn. */
internal class GatewayAuthoritativeResumeException(message: String) : Exception(message)
/** [code] is the JSON-RPC error code when the failure came from the server (e.g. 4018, -32601). */
internal class GatewayRpcException(message: String, val code: Int? = null) : Exception(message)
private const val JSONRPC_METHOD_NOT_FOUND = -32601
private val AUTHORITATIVE_PROMPT_SUBMIT_REJECTIONS = setOf(
4004, // malformed truncation target
4018, // durable/ordinal target is no longer present
4028, // first-turn truncate requires explicit empty-history confirmation
4029, // every destructive truncate requires explicit confirmation
4030, // durable row id and client ordinal disagree
4090, // active-session capacity policy
5008, // durable truncation could not be persisted
5070, // initial session persistence failed: storage full
5071, // other authoritative initial session persistence failure
)
@@ -594,6 +594,12 @@ private fun JsonObject?.approvalChoices(): List<String>? =
(this?.get("choices") as? JsonArray)
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.lowercase() }
?.filter { it in setOf("once", "session", "always", "deny") }
// Scope-denial flags are authoritative. Current upstream protected-
// instruction requests set both flags false, but gateway event builders
// can still include the broader session choice in `choices`.
// Never offer a scope the request explicitly forbids.
?.filterNot { it == "session" && this.boolean("allow_session") == false }
?.filterNot { it == "always" && this.boolean("allow_permanent") == false }
?.distinct()
?.takeIf { it.isNotEmpty() }
@@ -432,10 +432,12 @@ private class RetryingEventSource(
class HermesApiClient(
baseUrl: String,
private val apiKey: String,
httpClient: OkHttpClient? = null,
private val json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
}
},
okHttpClient: OkHttpClient? = null,
) {
@Volatile
private var lastCapabilities: ServerCapabilities? = null
@@ -479,7 +481,7 @@ class HermesApiClient(
private val mainHandler = Handler(Looper.getMainLooper())
private val client: OkHttpClient = OkHttpClient.Builder()
private val client: OkHttpClient = httpClient ?: okHttpClient ?: OkHttpClient.Builder()
.readTimeout(5, TimeUnit.MINUTES)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
@@ -1,21 +1,27 @@
package com.hermesandroid.relay.network.upstream.models
import com.hermesandroid.relay.data.MessageReaction
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import java.time.Instant
/**
@@ -76,6 +82,56 @@ object FlexibleIdNonNullSerializer : KSerializer<String> {
}
}
/** Unknown-safe durable SQLite row id used by current Gateway history. */
@OptIn(ExperimentalSerializationApi::class)
object FlexibleLongSerializer : KSerializer<Long?> {
override val descriptor = PrimitiveSerialDescriptor("FlexibleLong", PrimitiveKind.LONG)
override fun deserialize(decoder: Decoder): Long? {
return try {
val jsonDecoder = decoder as? JsonDecoder
?: return decoder.decodeLong()
(jsonDecoder.decodeJsonElement() as? JsonPrimitive)?.longOrNull
} catch (_: Exception) {
null
}
}
override fun serialize(encoder: Encoder, value: Long?) {
if (value != null) encoder.encodeLong(value) else encoder.encodeNull()
}
}
/**
* Dashboard versions may expose SQLite JSON columns either as an object or as
* their raw JSON string. Normalize both shapes so persisted presentation data
* (notably message reactions) survives a history reload on every supported
* upstream version.
*/
object FlexibleJsonObjectSerializer : KSerializer<JsonObject?> {
override val descriptor = JsonObject.serializer().descriptor
override fun deserialize(decoder: Decoder): JsonObject? {
return try {
val jsonDecoder = decoder as? JsonDecoder ?: return null
when (val element = jsonDecoder.decodeJsonElement()) {
is JsonObject -> element
is JsonPrimitive -> element.content.takeIf { it.isNotBlank() }
?.let { Json.parseToJsonElement(it) as? JsonObject }
else -> null
}
} catch (_: Exception) {
null
}
}
override fun serialize(encoder: Encoder, value: JsonObject?) {
val jsonEncoder = encoder as? JsonEncoder
?: throw SerializationException("FlexibleJsonObjectSerializer requires JSON")
jsonEncoder.encodeJsonElement(value ?: JsonNull)
}
}
/** Timestamp serializer for Hermes session metadata.
*
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
@@ -113,6 +169,32 @@ object FlexibleTimestampSerializer : KSerializer<Double?> {
}
}
/**
* Boolean serializer for session flags backed by SQLite integer columns.
*
* Older Dashboard responses can expose those columns as `0` / `1` instead of
* JSON booleans. Accept the equivalent primitive forms without making arbitrary
* numbers or strings truthy, and always serialize back to a real JSON boolean.
*/
object FlexibleBooleanSerializer : KSerializer<Boolean> {
override val descriptor = PrimitiveSerialDescriptor("FlexibleBoolean", PrimitiveKind.BOOLEAN)
override fun deserialize(decoder: Decoder): Boolean {
val jsonDecoder = decoder as? JsonDecoder ?: return decoder.decodeBoolean()
val element = jsonDecoder.decodeJsonElement()
val value = (element as? JsonPrimitive)?.content?.trim()?.lowercase()
return when (value) {
"true", "1" -> true
"false", "0" -> false
else -> throw SerializationException("Expected a boolean-compatible value, got $element")
}
}
override fun serialize(encoder: Encoder, value: Boolean) {
encoder.encodeBoolean(value)
}
}
// --- Session CRUD responses ---
@Serializable
@@ -166,9 +248,16 @@ data class SessionItem(
@SerialName("tool_call_count") val toolCallCount: Int? = null,
@SerialName("input_tokens") val inputTokens: Int? = null,
@SerialName("output_tokens") val outputTokens: Int? = null,
@SerialName("has_model_config") val hasModelConfig: Boolean = false,
@SerialName("actual_cost_usd") val actualCostUsd: Double? = null,
@SerialName("estimated_cost_usd") val estimatedCostUsd: Double? = null,
@SerialName("is_active") val isActive: Boolean = false,
@SerialName("has_model_config")
@Serializable(with = FlexibleBooleanSerializer::class)
val hasModelConfig: Boolean = false,
/** Durable flags returned by current Dashboard and API-server session resources. */
@Serializable(with = FlexibleBooleanSerializer::class)
val pinned: Boolean = false,
@Serializable(with = FlexibleBooleanSerializer::class)
val archived: Boolean = false,
/** Optional workspace metadata added by newer Dashboard session lists. */
val cwd: String? = null,
@@ -293,6 +382,9 @@ data class MessageItem(
@SerialName("session_id")
@Serializable(with = FlexibleIdSerializer::class)
val sessionId: String? = null,
@SerialName("row_id")
@Serializable(with = FlexibleLongSerializer::class)
val rowId: Long? = null,
val role: String,
val content: JsonElement? = null,
@SerialName("tool_calls") val toolCalls: JsonElement? = null,
@@ -303,7 +395,9 @@ data class MessageItem(
val timestamp: Double? = null,
@SerialName("finish_reason") val finishReason: String? = null,
@SerialName("display_kind") val displayKind: String? = null,
@SerialName("display_metadata") val displayMetadata: JsonObject? = null,
@SerialName("display_metadata")
@Serializable(with = FlexibleJsonObjectSerializer::class)
val displayMetadata: JsonObject? = null,
// Reasoning persisted with the assistant message (upstream serializes
// both names; reasoning is the canonical one). Restored into
// ChatMessage.thinkingContent so the Thought-process block survives a
@@ -311,11 +405,24 @@ data class MessageItem(
val reasoning: String? = null,
@SerialName("reasoning_content") val reasoningContent: String? = null,
) {
/**
* Dashboard history uses the SQLite row id as numeric `id`; Gateway
* history exposes the same value explicitly as `row_id`. Match Desktop by
* accepting either representation so persisted rows remain directly
* reactable after reload.
*/
val resolvedRowId: Long?
get() = rowId ?: id?.toLongOrNull()
/** Reasoning text under whichever field name the server used. */
val resolvedReasoning: String?
get() = reasoning?.takeIf { it.isNotBlank() }
?: reasoningContent?.takeIf { it.isNotBlank() }
/** Persisted tapbacks stored by Hermes in display_metadata.reactions. */
val reactions: List<MessageReaction>
get() = parseMessageReactions(displayMetadata?.get("reactions"))
/** Extract content as plain text string. Handles both string and array-of-parts formats. */
val contentText: String?
get() = when (content) {
@@ -343,6 +450,21 @@ data class MessageItem(
}
}
fun parseMessageReactions(element: JsonElement?): List<MessageReaction> =
(element as? JsonArray).orEmpty().mapNotNull { raw ->
val reaction = raw as? JsonObject ?: return@mapNotNull null
val emoji = (reaction["emoji"] as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() }
?: return@mapNotNull null
val author = (reaction["author"] as? JsonPrimitive)?.content
?.takeIf { it == "user" || it == "agent" }
?: return@mapNotNull null
MessageReaction(
emoji = emoji,
author = author,
at = (reaction["at"] as? JsonPrimitive)?.doubleOrNull ?: 0.0,
)
}
// --- SSE streaming events from /api/sessions/{id}/chat/stream ---
//
// Hermes WebAPI event types (from server source):
@@ -9,6 +9,7 @@ import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.net.Uri
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
@@ -47,10 +48,13 @@ object ProactiveMessageNotifier {
/**
* Tap route — opens Chat, where the message lives as a Thread. Must match
* `Screen.Chat.route()` in RelayApp. Routed via the EXTRA_NAV_ROUTE deep-link
* path (MainActivity → NavRouteRequest → RelayApp collector). Opening the
* exact Thread by chat_id is a follow-up (see TODO).
* path (MainActivity → NavRouteRequest → RelayApp collector), carrying the
* `chat_id` so RelayApp opens the exact real or provisional Thread.
*/
private const val TAP_ROUTE = "chat"
private fun tapRoute(chatId: String?): String =
chatId?.takeIf { it.isNotBlank() }
?.let { "chat?proactiveChatId=${Uri.encode(it)}" }
?: "chat"
/**
* Post (or replace) a proactive-message notification.
@@ -80,7 +84,7 @@ object ProactiveMessageNotifier {
val tapIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(MainActivity.EXTRA_NAV_ROUTE, TAP_ROUTE)
putExtra(MainActivity.EXTRA_NAV_ROUTE, tapRoute(chatId))
}
val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
// Distinct requestCode per slot so each notification gets its own
@@ -176,7 +176,9 @@ internal class HermesRuntimeBinder(
chat.setDisplayProfileProvider { connection.effectiveDisplayProfile.value }
chat.setDisplayAliasProvider { connection.profileDisplayAlias.value }
chat.setProfileSessionLister { connection.listProfileScopedSessions() }
chat.setProfileMessageLoaderWithMode(connection::loadProfileScopedMessages)
chat.setProfileMessageLoaderWithMode { profileName, sessionId, mode ->
connection.loadProfileScopedMessages(profileName, sessionId, mode)
}
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
chat.profileSessionDeleter = connection::deleteProfileScopedSession
chat.profileSessionRenamer = connection::renameProfileScopedSession
@@ -336,17 +336,20 @@ sealed class Screen(
// NavHost, and the NavigationBarItem click must navigate via [route]()
// so no unresolved `{openAgentSheet}` leaks into the destination.
data object Chat : Screen(
"chat?openAgentSheet={openAgentSheet}&sessionId={sessionId}&profile={profile}",
"chat?openAgentSheet={openAgentSheet}&sessionId={sessionId}&profile={profile}" +
"&proactiveChatId={proactiveChatId}",
"Chat",
Icons.AutoMirrored.Filled.Chat,
) {
const val ARG_OPEN_AGENT_SHEET: String = "openAgentSheet"
const val ARG_SESSION_ID: String = "sessionId"
const val ARG_PROFILE: String = "profile"
const val ARG_PROACTIVE_CHAT_ID: String = "proactiveChatId"
fun route(
openAgentSheet: Boolean = false,
sessionId: String? = null,
profile: String? = null,
proactiveChatId: String? = null,
): String {
val params = buildList {
if (openAgentSheet) add("$ARG_OPEN_AGENT_SHEET=true")
@@ -356,6 +359,9 @@ sealed class Screen(
profile?.takeIf { it.isNotBlank() }?.let {
add("$ARG_PROFILE=${android.net.Uri.encode(it)}")
}
proactiveChatId?.takeIf { it.isNotBlank() }?.let {
add("$ARG_PROACTIVE_CHAT_ID=${android.net.Uri.encode(it)}")
}
}
return if (params.isEmpty()) "chat" else "chat?${params.joinToString("&")}"
}
@@ -618,21 +624,11 @@ fun RelayApp() {
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
val relayVoiceReady by connectionViewModel.relayVoiceReady.collectAsState()
// Profile Inspector client. Shares the same lazy relay URL + bearer
// token providers as the voice client so any rotation/re-pair is
// automatically picked up on the next fetch. Process-stable via
// remember {} so the OkHttpClient isn't rebuilt on recomposition.
val profileInspectorClient = remember {
RelayProfileInspectorClient(
okHttpClient = okhttp3.OkHttpClient.Builder()
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build(),
relayUrlProvider = { connectionViewModel.effectiveRelayUrl.value },
sessionTokenProvider = {
(connectionViewModel.authState.value as? AuthState.Paired)?.token
},
)
val profileInspectorHttpClient = remember {
okhttp3.OkHttpClient.Builder()
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
}
// === PHASE3-status: sync granular phone-status settings to chat ===
val appContextEnabled by connectionViewModel.appContextEnabled.collectAsState()
@@ -1695,6 +1691,11 @@ fun RelayApp() {
nullable = true
defaultValue = null
},
navArgument(Screen.Chat.ARG_PROACTIVE_CHAT_ID) {
type = NavType.StringType
nullable = true
defaultValue = null
},
),
) { backStackEntry ->
// Responsive bubble width based on screen width. The "Blend"
@@ -1725,6 +1726,35 @@ fun RelayApp() {
val requestedProfileRoute = backStackEntry.arguments
?.getString(Screen.Chat.ARG_PROFILE)
?.takeIf { it.isNotBlank() }
val requestedProactiveChatId = backStackEntry.arguments
?.getString(Screen.Chat.ARG_PROACTIVE_CHAT_ID)
?.takeIf { it.isNotBlank() }
val proactiveInboxEntries by connectionViewModel.inboxMessages.collectAsState()
val phoneThreadChatIds by connectionViewModel.phoneThreadChatIds.collectAsState()
LaunchedEffect(
requestedProactiveChatId,
proactiveInboxEntries,
phoneThreadChatIds,
) {
val chatId = requestedProactiveChatId ?: return@LaunchedEffect
val realSessionId = phoneThreadChatIds.entries
.firstOrNull { it.value == chatId }
?.key
if (realSessionId != null) {
chatViewModel.switchSession(realSessionId)
} else {
val entries = proactiveInboxEntries.filter {
(it.connectionId == null || it.connectionId == activeConnectionId) &&
(it.chatId ?: "phone") == chatId
}
if (entries.isEmpty()) return@LaunchedEffect
chatViewModel.openProactiveThread(chatId, entries)
}
backStackEntry.arguments?.putString(
Screen.Chat.ARG_PROACTIVE_CHAT_ID,
null,
)
}
LaunchedEffect(
requestedSessionId,
requestedProfileRoute,
@@ -2619,7 +2649,8 @@ fun RelayApp() {
val sectionArg = backStackEntry.arguments
?.getString(Screen.ProfileInspector.ARG_SECTION)
?: Screen.ProfileInspector.SECTION_CONFIG
if (coldStartAuthState !is AuthState.Paired) {
val inspectorGatewayClient = connectionViewModel.activeGatewayChatClient()
if (coldStartAuthState !is AuthState.Paired && inspectorGatewayClient == null) {
PowerFeatureGateScreen(
title = stringResource(R.string.screen_profile_inspector_label),
summary = stringResource(R.string.power_gate_profile_inspector_summary),
@@ -2647,8 +2678,18 @@ fun RelayApp() {
// SavedStateHandle contains our
// `profileName` arg automatically.
val ssh = extras.createSavedStateHandle()
// Freeze both transports to the connection that
// owned this nav entry. A later connection/profile
// switch cannot redirect an open editor's writes.
val relayUrl = connectionViewModel.effectiveRelayUrl.value
val relayToken = (connectionViewModel.authState.value as? AuthState.Paired)?.token
return ProfileInspectorViewModel(
client = profileInspectorClient,
legacyClient = RelayProfileInspectorClient(
okHttpClient = profileInspectorHttpClient,
relayUrlProvider = { relayUrl },
sessionTokenProvider = { relayToken },
),
gatewayClient = inspectorGatewayClient,
savedStateHandle = ssh,
) as T
}
@@ -1739,7 +1739,10 @@ fun ActiveCardRoutesSection(
var routeEditorOriginal by remember(connection.id) {
mutableStateOf<EndpointCandidate?>(null)
}
val hasTailscaleRoute = endpoints.any { it.role.equals("tailscale", ignoreCase = true) }
val hasTailscaleRoute = hasConfiguredTailscaleRoute(
endpoints = endpoints,
primaryEndpointUrl = connection.primaryEndpointUrl,
)
val tailscalePreferred = preferredRole?.equals("tailscale", ignoreCase = true) == true
val routeNeedsAttention = activeEndpoint == null && liveState != RelayUiState.Connected
val showTailscaleUnavailableHint =
@@ -2171,6 +2174,12 @@ fun ActiveCardRoutesSection(
}
}
internal fun hasConfiguredTailscaleRoute(
endpoints: List<EndpointCandidate>,
primaryEndpointUrl: String,
): Boolean = endpoints.any { it.role.equals("tailscale", ignoreCase = true) } ||
Connection.inferRouteRole(primaryEndpointUrl) == "tailscale"
/**
* Numbered step row for the Manual pairing code fallback. Tightly
* coupled to its Card 3 layout — step badge sizing + content shape —
@@ -94,7 +94,7 @@ import kotlinx.coroutines.delay
*/
enum class ChatInputTrailing { SEND, VOICE, STOP, STEER, QUEUE }
private val ChatComposerShape = RoundedCornerShape(18.dp)
private val ChatComposerShape = RoundedCornerShape(26.dp)
private val ChatInputChipShape = RoundedCornerShape(12.dp)
internal const val CHAT_INPUT_FIELD_TEST_TAG = "chat-input-field"
@@ -315,7 +315,7 @@ fun ChatInputBar(
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 6.dp)
.padding(horizontal = 8.dp, vertical = 3.dp)
.then(surfaceModifier),
) {
Column {
@@ -341,15 +341,15 @@ fun ChatInputBar(
}
Column(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
modifier = Modifier.padding(horizontal = 6.dp, vertical = 3.dp),
) {
BasicTextField(
value = value,
onValueChange = { if (it.length <= charLimit) onValueChange(it) },
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 34.dp)
.padding(horizontal = 8.dp, vertical = 4.dp)
.heightIn(min = 30.dp)
.padding(horizontal = 10.dp, vertical = 2.dp)
// Keep directional keys inside the editor. Compose's
// BasicTextField owns normal caret/selection movement;
// cancelling focus traversal prevents a boundary arrow
@@ -408,7 +408,7 @@ fun ChatInputBar(
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp),
.heightIn(min = 44.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
@@ -105,6 +105,11 @@ import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.ConnectionValidation
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.presentationRouteUrl
import com.hermesandroid.relay.data.secureLinkCoversAllServices
import com.hermesandroid.relay.data.secureLinkServices
import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.network.shared.HermesLanDiscovery
import com.hermesandroid.relay.network.shared.HermesLanDiscoveryResult
@@ -3174,7 +3179,7 @@ private fun ConfirmStep(
// app auto-falls back to the secure one, so a blanket "Insecure (dev)"
// badge from endpoint[0] alone would lie to the user.
val anySecure = endpoints.any { c ->
c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.hasSecureProxy() || c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.relay?.transportHint.equals("wss", ignoreCase = true) ||
c.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
}
@@ -3195,7 +3200,7 @@ private fun ConfirmStep(
// Mixed case ("Tailscale is encrypted..." vs "Public is encrypted...").
val firstSecureLabel = endpoints
.firstOrNull { c ->
c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.hasSecureProxy() || c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.relay?.transportHint.equals("wss", ignoreCase = true) ||
c.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
}?.displayLabel()
@@ -3208,6 +3213,7 @@ private fun ConfirmStep(
val distinctRoles = endpoints.map { it.role }.distinct()
var preferRole by remember(payload) { mutableStateOf<String?>(null) }
var preferMenuOpen by remember { mutableStateOf(false) }
val secureLink = endpoints.firstOrNull { it.hasSecureProxy() }
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
@@ -3318,6 +3324,15 @@ private fun ConfirmStep(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
secureLink?.let { route ->
SecureLinkPairingSummary(
services = route.secureLinkServices(),
complete = route.secureLinkCoversAllServices(),
hasFallback = endpoints.size > 1,
usesReach = route.hasHermesReach(),
)
HorizontalDivider()
}
endpoints.forEachIndexed { index, candidate ->
if (index > 0) HorizontalDivider()
EndpointPreviewRow(
@@ -3720,7 +3735,7 @@ private fun EndpointPreviewRow(
) {
// Per-row security derived from the same three signals as the overall
// securityState computation — scheme, tls flag, transportHint.
val isSecure = candidate.relay?.url?.startsWith("wss://") == true ||
val isSecure = candidate.hasSecureProxy() || candidate.relay?.url?.startsWith("wss://") == true ||
candidate.api?.tls == true ||
candidate.relay?.transportHint.equals("wss", ignoreCase = true) ||
candidate.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
@@ -3756,7 +3771,7 @@ private fun EndpointPreviewRow(
}
}
Text(
text = candidate.primaryRouteUrl().orEmpty() +
text = candidate.presentationRouteUrl().orEmpty() +
(candidate.relay?.transportHint?.let { " \u00b7 $it" } ?: ""),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -3772,6 +3787,75 @@ private fun EndpointPreviewRow(
}
}
@Composable
private fun SecureLinkPairingSummary(
services: List<String>,
complete: Boolean,
hasFallback: Boolean,
usesReach: Boolean,
) {
val relayLabel = stringResource(R.string.secure_link_service_relay)
val apiLabel = stringResource(R.string.secure_link_service_api)
val dashboardLabel = stringResource(R.string.secure_link_service_dashboard)
val serviceText = services.map { service ->
when (service) {
"relay" -> relayLabel
"api" -> apiLabel
"dashboard" -> dashboardLabel
else -> service
}
}.joinToString(" · ")
Surface(
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.08f),
shape = RoundedCornerShape(12.dp),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(12.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
stringResource(if (usesReach) R.string.hermes_reach_title else R.string.secure_link_title),
style = MaterialTheme.typography.titleSmall,
)
if (usesReach) {
Text(
stringResource(R.string.hermes_reach_summary),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
stringResource(R.string.secure_link_pinned_tls),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
Text(
if (serviceText.isBlank()) stringResource(R.string.secure_link_no_services)
else stringResource(R.string.secure_link_protects, serviceText),
style = MaterialTheme.typography.bodySmall,
)
if (!complete) {
Text(
stringResource(R.string.secure_link_partial_warning),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Text(
if (hasFallback) stringResource(R.string.secure_link_fallback_ready)
else stringResource(R.string.secure_link_no_fallback),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
stringResource(R.string.secure_link_auth_note),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/**
* Compact pill used by [EndpointPreviewRow] — matches the "Preferred" soft
* chip style so the row reads as a row of related chips rather than a mix
@@ -57,6 +57,9 @@ import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.SurfaceSecurityKind
import com.hermesandroid.relay.data.displayLabel
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
@@ -323,6 +326,9 @@ private fun EndpointRow(
val apiLabel = stringResource(R.string.active_section_api_server)
val relayLabel = stringResource(R.string.active_section_relay)
val surfaceSummary = listOfNotNull(
candidate.proxy?.takeIf { candidate.hasSecureProxy() }?.let {
stringResource(R.string.secure_link_pinned_tls_short)
},
dashboardSurfaceUrl?.let { "$dashboardLabel ${displayPort(it)}" },
candidate.api?.url?.let { "$apiLabel ${displayPort(it)}" },
candidate.relay?.url?.let { "$relayLabel ${displayPort(it)}" },
@@ -357,6 +363,36 @@ private fun EndpointRow(
)
}
}
if (candidate.hasSecureProxy()) {
val secureRelayLabel = stringResource(R.string.secure_link_service_relay)
val secureApiLabel = stringResource(R.string.secure_link_service_api)
val secureDashboardLabel = stringResource(R.string.secure_link_service_dashboard)
val services = candidate.secureLinkServices().map { service ->
when (service) {
"relay" -> secureRelayLabel
"api" -> secureApiLabel
"dashboard" -> secureDashboardLabel
else -> service
}
}.joinToString(" · ")
Text(
text = stringResource(R.string.secure_link_protects, services),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
if (!candidate.secureLinkCoversAllServices()) {
Text(
text = stringResource(R.string.secure_link_partial_warning),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Text(
text = stringResource(R.string.secure_link_auth_note),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
// 3-dot overflow menu — actions per-row so the card stays flat
@@ -680,6 +716,7 @@ private fun roleIcon(role: String): ImageVector = when (role.lowercase()) {
* be classified independently before it's the active route.
*/
private fun EndpointCandidate.routeSecurityKind(): SurfaceSecurityKind = when {
hasSecureProxy() -> SurfaceSecurityKind.Tls
isTlsUrl(primaryRouteUrl().orEmpty()) -> SurfaceSecurityKind.Tls
isEncryptedOverlayRoute(isTailscaleDetected = false) -> SurfaceSecurityKind.Overlay
else -> SurfaceSecurityKind.Plain
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
@@ -43,6 +44,7 @@ import androidx.compose.material.icons.filled.FormatQuote
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
@@ -90,6 +92,7 @@ import java.text.SimpleDateFormat
import java.util.Date
internal const val CHAT_PET_IDENTITY_OBSTACLE_PREFIX = "chat-message-identity:"
private val MESSAGE_REACTIONS = listOf("❤️", "👍", "👎", "😂", "‼️", "❓")
@OptIn(ExperimentalFoundationApi::class)
@Composable
@@ -455,11 +458,51 @@ fun MessageBubble(
val showEditAction = onEditMessage != null && isUser
val showSpeakAction = shouldShowSpeakResponseAction(message, onSpeakMessage != null)
val showStopSpeakingAction = shouldShowStopSpeakingAction(message, onStopSpeaking != null)
val selectedUserReaction = message.reactions.firstOrNull { it.author == "user" }?.emoji
if (onQuoteMessage != null || onReact != null || showEditAction || showSpeakAction || showStopSpeakingAction) {
DropdownMenu(
expanded = showMessageActions,
onDismissRequest = { showMessageActions = false },
shape = RoundedCornerShape(24.dp),
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 3.dp,
shadowElevation = 8.dp,
) {
if (onReact != null) {
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 6.dp),
) {
MESSAGE_REACTIONS.forEach { emoji ->
IconButton(
onClick = {
showMessageActions = false
onReact(emoji)
},
modifier = Modifier.background(
color = if (selectedUserReaction == emoji) {
MaterialTheme.colorScheme.secondaryContainer
} else {
Color.Transparent
},
shape = CircleShape,
),
) {
Text(
text = emoji,
fontSize = 24.sp,
modifier = Modifier.semantics {
contentDescription = "React with $emoji"
},
)
}
}
}
HorizontalDivider()
}
DropdownMenuItem(
text = { Text(stringResource(R.string.msg_bubble_copy)) },
onClick = {
@@ -515,8 +558,22 @@ fun MessageBubble(
},
)
}
if (onReact != null && selectedUserReaction != null) {
DropdownMenuItem(
text = { Text("Remove reaction") },
onClick = {
showMessageActions = false
onReact(null)
},
)
}
}
}
Box(
modifier = Modifier.padding(
bottom = if (message.reactions.isNotEmpty()) 8.dp else 0.dp,
),
) {
Surface(
shape = bubbleShape,
color = backgroundColor,
@@ -558,7 +615,7 @@ fun MessageBubble(
// same tactile confirm every chat app fires.
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
if (
onQuoteMessage != null || showEditAction || showSpeakAction ||
onQuoteMessage != null || onReact != null || showEditAction || showSpeakAction ||
showStopSpeakingAction
) {
showMessageActions = true
@@ -645,25 +702,6 @@ fun MessageBubble(
SelectionContainer { messageTextContent() }
}
}
if (onReact != null) {
listOf("👍", "❤️", "😂").forEach { emoji ->
DropdownMenuItem(
text = { Text("React $emoji") },
onClick = {
showMessageActions = false
onReact(emoji)
},
)
}
DropdownMenuItem(
text = { Text("Remove reaction") },
onClick = {
showMessageActions = false
onReact(null)
},
)
}
if (onSessionReference != null && sessionReferences.isNotEmpty()) {
sessionReferences.forEach { reference ->
TextButton(
@@ -838,6 +876,19 @@ fun MessageBubble(
}
}
}
if (message.reactions.isNotEmpty()) {
MessageReactionBadge(
reactions = message.reactions.map { it.emoji },
onOpen = onReact?.let { { showMessageActions = true } },
modifier = Modifier
.align(if (isUser) Alignment.BottomEnd else Alignment.BottomStart)
.offset(
x = if (isUser) (-10).dp else 10.dp,
y = 9.dp,
),
)
}
}
val inlineActions: @Composable () -> Unit = {
MessageInlineActions(
showQuote = onQuoteMessage != null,
@@ -890,6 +941,41 @@ fun MessageBubble(
} // end CompositionLocalProvider(LocalMediaBlurMode)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MessageReactionBadge(
reactions: List<String>,
onOpen: (() -> Unit)?,
modifier: Modifier = Modifier,
) {
val description = "Reactions: ${reactions.joinToString(" ")}"
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest,
tonalElevation = 2.dp,
shadowElevation = 2.dp,
modifier = modifier
.then(
if (onOpen != null) {
Modifier.combinedClickable(onClick = onOpen, onLongClick = onOpen)
} else {
Modifier
},
)
.semantics { contentDescription = description },
) {
Row(
horizontalArrangement = Arrangement.spacedBy(2.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 7.dp, vertical = 3.dp),
) {
reactions.forEach { emoji ->
Text(text = emoji, fontSize = 14.sp, lineHeight = 16.sp)
}
}
}
}
@Composable
private fun MessageInlineActions(
showQuote: Boolean,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,167 @@
package com.hermesandroid.relay.ui.components
import com.hermesandroid.relay.data.ChatSession
import com.hermesandroid.relay.data.SessionActivityState
import java.util.Locale
internal enum class SessionDrawerGrouping {
None,
Updated,
Project,
Status,
Profile,
}
internal enum class SessionDrawerOrdering {
Updated,
Created,
Title,
Status,
Tokens,
Cost,
}
internal enum class SessionDrawerStatus {
NeedsInput,
Working,
Idle,
}
internal enum class SessionDrawerPrState {
Open,
Draft,
Merged,
Closed,
None,
}
internal data class SessionDrawerViewOptions(
val grouping: SessionDrawerGrouping = SessionDrawerGrouping.None,
val ordering: SessionDrawerOrdering = SessionDrawerOrdering.Updated,
val statuses: Set<SessionDrawerStatus> = emptySet(),
val profiles: Set<String> = emptySet(),
val projects: Set<String> = emptySet(),
val pullRequests: Set<SessionDrawerPrState> = emptySet(),
val showProfile: Boolean = false,
val showUpdated: Boolean = true,
val showTokens: Boolean = false,
val showCost: Boolean = false,
)
internal data class SessionDrawerGroup(
val key: String,
val label: String?,
val rows: List<ProfileSessionRow>,
)
internal fun sessionRowKey(row: ProfileSessionRow): String =
"${row.profile.lowercase(Locale.ROOT)}:${row.session.sessionId}"
internal fun sessionProjectLabel(session: ChatSession): String {
val raw = (session.gitRepoRoot ?: session.workingDirectory)
?.trim()
?.trimEnd('/', '\\')
.orEmpty()
if (raw.isBlank()) return "No project"
return raw.substringAfterLast('/').substringAfterLast('\\').ifBlank { raw }
}
internal fun sessionDrawerStatus(
row: ProfileSessionRow,
activityStates: Map<String, SessionActivityState>,
): SessionDrawerStatus = when (
activityStates[sessionRowKey(row)] ?: activityStates[row.session.sessionId]
) {
SessionActivityState.NeedsInput -> SessionDrawerStatus.NeedsInput
SessionActivityState.Working -> SessionDrawerStatus.Working
null -> if (row.session.isActive) SessionDrawerStatus.Working else SessionDrawerStatus.Idle
}
internal fun sessionDrawerPrState(session: ChatSession): SessionDrawerPrState = when {
session.pullRequestNumber == null -> SessionDrawerPrState.None
session.pullRequestDraft -> SessionDrawerPrState.Draft
session.pullRequestState.equals("merged", ignoreCase = true) -> SessionDrawerPrState.Merged
session.pullRequestState.equals("closed", ignoreCase = true) -> SessionDrawerPrState.Closed
else -> SessionDrawerPrState.Open
}
internal fun filterAndSortSessionRows(
rows: List<ProfileSessionRow>,
options: SessionDrawerViewOptions,
activityStates: Map<String, SessionActivityState> = emptyMap(),
): List<ProfileSessionRow> {
val filtered = rows.asSequence()
.filter { options.statuses.isEmpty() || sessionDrawerStatus(it, activityStates) in options.statuses }
.filter { options.profiles.isEmpty() || it.profile in options.profiles }
.filter { options.projects.isEmpty() || sessionProjectLabel(it.session) in options.projects }
.filter { options.pullRequests.isEmpty() || sessionDrawerPrState(it.session) in options.pullRequests }
.toList()
val statusRank = mapOf(
SessionDrawerStatus.NeedsInput to 0,
SessionDrawerStatus.Working to 1,
SessionDrawerStatus.Idle to 2,
)
val comparator = when (options.ordering) {
SessionDrawerOrdering.Updated -> compareByDescending<ProfileSessionRow> { it.session.activityTimestamp }
SessionDrawerOrdering.Created -> compareByDescending { it.session.startTimestamp }
SessionDrawerOrdering.Title -> compareBy { it.session.title.orEmpty().lowercase(Locale.ROOT) }
SessionDrawerOrdering.Status -> compareBy { statusRank.getValue(sessionDrawerStatus(it, activityStates)) }
SessionDrawerOrdering.Tokens -> compareByDescending { it.session.totalTokens }
SessionDrawerOrdering.Cost -> compareByDescending { it.session.costUsd }
}
return filtered.sortedWith(
compareByDescending<ProfileSessionRow> { it.session.pinned }
.then(comparator)
.thenBy { it.session.title.orEmpty().lowercase(Locale.ROOT) },
)
}
internal fun groupSessionRows(
rows: List<ProfileSessionRow>,
grouping: SessionDrawerGrouping,
activityStates: Map<String, SessionActivityState> = emptyMap(),
nowMillis: Long = System.currentTimeMillis(),
): List<SessionDrawerGroup> {
if (rows.isEmpty()) return emptyList()
val grouped = rows.groupBy { row ->
when (grouping) {
SessionDrawerGrouping.None -> null
SessionDrawerGrouping.Updated -> updatedBucket(row.session.activityTimestamp, nowMillis)
SessionDrawerGrouping.Project -> sessionProjectLabel(row.session)
SessionDrawerGrouping.Status -> sessionDrawerStatus(row, activityStates).displayLabel
SessionDrawerGrouping.Profile -> row.profile
}
}
val groups = grouped.map { (label, groupRows) ->
SessionDrawerGroup(key = "${grouping.name}:$label", label = label, rows = groupRows)
}
return if (grouping == SessionDrawerGrouping.Project) {
groups.sortedWith(
compareBy<SessionDrawerGroup> { it.label != "No project" }
.thenByDescending { group -> group.rows.maxOfOrNull { it.session.activityTimestamp } ?: 0L }
.thenBy { it.label.orEmpty().lowercase(Locale.ROOT) },
)
} else {
groups
}
}
private val SessionDrawerStatus.displayLabel: String
get() = when (this) {
SessionDrawerStatus.NeedsInput -> "Needs input"
SessionDrawerStatus.Working -> "Working"
SessionDrawerStatus.Idle -> "Idle"
}
private fun updatedBucket(timestamp: Long, nowMillis: Long): String {
if (timestamp <= 0L) return "Older"
val age = (nowMillis - timestamp).coerceAtLeast(0L)
return when {
age < DAY_MILLIS -> "Today"
age < 2 * DAY_MILLIS -> "Yesterday"
age < 7 * DAY_MILLIS -> "Last 7 days"
else -> "Older"
}
}
private const val DAY_MILLIS = 24L * 60L * 60L * 1_000L
@@ -173,6 +173,7 @@ import com.hermesandroid.relay.data.HermesCardAction
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.PhysicalKeyboardEnterBehavior
import com.hermesandroid.relay.data.ProfilePresentationPolicy
import com.hermesandroid.relay.data.ProactiveInboxEntry
import com.hermesandroid.relay.data.SessionActivityState
import com.hermesandroid.relay.data.VoicePresentationMode
import com.hermesandroid.relay.data.hermesProcessNotificationOrNull
@@ -232,6 +233,7 @@ import com.hermesandroid.relay.ui.components.ThinkingMatrixColor
import com.hermesandroid.relay.ui.components.ThinkingMatrixPattern
import com.hermesandroid.relay.ui.components.SessionDrawerContent
import com.hermesandroid.relay.ui.components.ProfileSessionRow
import com.hermesandroid.relay.ui.components.ProvisionalThreadRow
import com.hermesandroid.relay.ui.components.ProfileDisplayManagerDialog
import com.hermesandroid.relay.ui.components.ProfileShelf
import com.hermesandroid.relay.ui.components.ProfileSwitcherSheet
@@ -298,14 +300,12 @@ internal fun resolveSessionActivityStates(
internal fun resolveChatHeaderSubtitle(
isStreaming: Boolean,
statusText: String,
projectName: String?,
personalityName: String?,
modelName: String?,
): String = if (isStreaming) {
statusText
} else {
listOfNotNull(
projectName?.takeIf { it.isNotBlank() },
personalityName?.takeIf { it.isNotBlank() },
modelName?.takeIf { it.isNotBlank() },
).joinToString(" \u00B7 ").ifBlank { statusText }
@@ -821,6 +821,27 @@ fun ChatScreen(
// has been made (the /api/config fallback is more useful than the bare
// connection label).
val agentProfiles by connectionViewModel.agentProfiles.collectAsState()
var allProfileSessions by remember { mutableStateOf<List<ProfileSessionRow>>(emptyList()) }
var allProfileSessionsLoading by remember { mutableStateOf(false) }
val openedSessionProfileName by chatViewModel.openedSessionProfileName.collectAsState()
val conversationProfile = openedSessionProfileName?.let { owner ->
agentProfiles.firstOrNull { it.name.equals(owner, ignoreCase = true) }
?: allProfileSessions.firstOrNull {
it.profile.equals(owner, ignoreCase = true) &&
it.session.sessionId == currentSessionId
}?.session?.let { session ->
com.hermesandroid.relay.data.Profile(
name = owner,
model = session.model.orEmpty(),
description = owner,
)
}
?: com.hermesandroid.relay.data.Profile(
name = owner,
model = "",
description = owner,
)
} ?: effectiveProfile
val profileDisplayAlias by connectionViewModel.profileDisplayAlias.collectAsState()
val activeConnection by connectionViewModel.activeConnection.collectAsState()
val serverModelName by chatViewModel.serverModelName.collectAsState()
@@ -832,7 +853,6 @@ fun ChatScreen(
val selectedProviderOverride by chatViewModel.selectedProviderOverride.collectAsState()
val gatewayCurrentModel by chatViewModel.gatewayCurrentModel.collectAsState()
val gatewayCurrentProvider by chatViewModel.gatewayCurrentProvider.collectAsState()
val gatewayProjectName by chatViewModel.gatewayProjectName.collectAsState()
val selectedReasoningEffort by chatViewModel.selectedReasoningEffort.collectAsState()
val currentSession = remember(sessions, currentSessionId) {
sessions.firstOrNull { it.sessionId == currentSessionId }
@@ -844,8 +864,8 @@ fun ChatScreen(
gatewayModel = gatewayCurrentModel,
gatewayProvider = gatewayCurrentProvider,
persistedSessionModel = currentSession?.model,
profileDefaultModel = effectiveProfile?.model,
serverDefaultModel = serverModelName,
profileDefaultModel = conversationProfile?.model,
serverDefaultModel = serverModelName.takeIf { openedSessionProfileName == null },
)
val sessionPickerProvider = sessionModelState.pickerProvider
?: sessionModelState.pickerModel?.let { model ->
@@ -1136,8 +1156,6 @@ fun ChatScreen(
}
val listState = rememberLazyListState()
val drawerState = rememberDrawerState(DrawerValue.Closed)
var allProfileSessions by remember { mutableStateOf<List<ProfileSessionRow>>(emptyList()) }
var allProfileSessionsLoading by remember { mutableStateOf(false) }
PetInteractionLayer(
owner = "chat-interaction-layer",
active = shouldHideChatPet(
@@ -1995,7 +2013,7 @@ fun ChatScreen(
// four keys, which missed updates in some cases (most notably a
// profile switch while the ConnectionInfoSheet was open, where the
// ambient sheet scope appeared to swallow the key comparison).
val agentDisplayName by remember(
val globalSelectedAgentDisplayName by remember(
effectiveProfile,
selectedPersonality,
defaultPersonality,
@@ -2003,13 +2021,31 @@ fun ChatScreen(
activeConnection?.label,
) {
derivedStateOf {
val profile = effectiveProfile
AgentDisplay.agentName(
profile = effectiveProfile,
selectedPersonality = selectedPersonality,
defaultPersonality = defaultPersonality,
connectionLabel = activeConnection?.label,
localDisplayAlias = profileDisplayAlias,
)
}
}
val agentDisplayName by remember(
conversationProfile,
selectedPersonality,
defaultPersonality,
profileDisplayAlias,
openedSessionProfileName,
activeConnection?.label,
) {
derivedStateOf {
val profile = conversationProfile
AgentDisplay.agentName(
profile = profile,
selectedPersonality = selectedPersonality,
defaultPersonality = defaultPersonality,
connectionLabel = activeConnection?.label,
localDisplayAlias = profileDisplayAlias,
localDisplayAlias = profileDisplayAlias.takeIf { openedSessionProfileName == null },
)
}
}
@@ -2038,13 +2074,13 @@ fun ChatScreen(
ModalNavigationDrawer(
drawerState = drawerState,
// Disable the drawer's edge-swipe while voice mode is up so the
// overlay reads as a true modal — the swipe gesture lives on the
// drawer itself, so the overlay's pointer scrim alone can't block it.
gesturesEnabled = !voiceUiState.voiceMode,
// Material routes scrim taps through the drawer's gesture handler.
// Keep it enabled so tapping outside always dismisses the drawer; the
// voice overlay already owns input while voice mode is visible.
gesturesEnabled = true,
drawerContent = {
val drawerTitle = if (effectiveProfile != null) {
stringResource(R.string.chat_profile_sessions, agentDisplayName)
stringResource(R.string.chat_profile_sessions, globalSelectedAgentDisplayName)
} else {
stringResource(R.string.chat_server_default_sessions)
}
@@ -2066,12 +2102,29 @@ fun ChatScreen(
val threadsCapabilityActive = threadsProactiveEnabled &&
threadsAuthState is com.hermesandroid.relay.auth.AuthState.Paired
val hiddenSources by connectionViewModel.hiddenSources.collectAsState()
val proactiveInboxEntries by connectionViewModel.inboxMessages.collectAsState()
val phoneThreadChatIds by connectionViewModel.phoneThreadChatIds.collectAsState()
val provisionalThreadEntries = buildProvisionalThreadRows(
entries = proactiveInboxEntries,
activeConnectionId = activeConnection?.id,
realThreadChatIds = phoneThreadChatIds.values,
)
val provisionalThreads = provisionalThreadEntries.map { (chatId, entries) ->
val latest = entries.maxBy { it.receivedAt }
ProvisionalThreadRow(
chatId = chatId,
title = latest.title.ifBlank { "Hermes" },
messageCount = entries.size,
lastActivityAt = latest.receivedAt,
)
}
SessionDrawerContent(
sessions = sessions,
currentSessionId = currentSessionId,
scopeTitle = drawerTitle,
scopeSubtitle = drawerSubtitle,
activeProfileName = effectiveProfile?.name ?: "default",
isLoading = isLoadingSessions,
isOpen = drawerState.isOpen,
activityStates = sessionActivityStates,
@@ -2083,6 +2136,24 @@ fun ChatScreen(
chatViewModel.createNewChat()
scope.launch { drawerState.close() }
},
onNewDefaultChat = {
val defaultProfile = agentProfiles.firstOrNull {
it.name.equals("default", ignoreCase = true)
} ?: com.hermesandroid.relay.data.Profile(
name = "default",
model = "",
description = "Default",
)
chatViewModel.createProfileChat(
profileName = "default",
profile = defaultProfile,
contextKey = AgentDisplay.profileContextKey(
connectionId = activeConnection?.id,
profileName = "default",
),
)
scope.launch { drawerState.close() }
},
onSelectSession = { sessionId ->
chatViewModel.switchSession(sessionId)
scope.launch { drawerState.close() }
@@ -2112,12 +2183,23 @@ fun ChatScreen(
chatViewModel.startNewThread(name)
scope.launch { drawerState.close() }
},
provisionalThreads = provisionalThreads,
onSelectProvisionalThread = { chatId ->
chatViewModel.openProactiveThread(
chatId,
provisionalThreadEntries[chatId].orEmpty(),
)
scope.launch { drawerState.close() }
},
hiddenSources = hiddenSources,
onToggleSourceHidden = { source, hidden ->
connectionViewModel.setSourceHidden(source, hidden)
},
allProfilesSupported = !activeConnection?.resolvedDashboardUrl.isNullOrBlank(),
allProfileSessions = allProfileSessions,
allProfileSessionsLoading = allProfileSessionsLoading,
profileColors = profilePresentation.colors,
onProfileColorChange = connectionViewModel::setProfileColor,
onRefreshAllProfiles = {
if (!allProfileSessionsLoading) scope.launch {
allProfileSessionsLoading = true
@@ -2134,6 +2216,11 @@ fun ChatScreen(
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,
isActive = item.isActive,
startedAt = ((item.startedAt ?: 0.0) * 1000).toLong(),
lastActivityAt = ((item.resolvedLastActivity ?: 0.0) * 1000).toLong(),
source = item.source,
@@ -2164,9 +2251,29 @@ fun ChatScreen(
it.name.equals(profileName, ignoreCase = true)
}
if (target != null || profileName.equals("default", ignoreCase = true)) {
connectionViewModel.selectProfile(target)
chatViewModel.activateGatewayProfile(target)
chatViewModel.switchSession(sessionId)
val ownerProfile = target ?: allProfileSessions.firstOrNull {
it.profile.equals(profileName, ignoreCase = true) &&
it.session.sessionId == sessionId
}?.session?.let { session ->
com.hermesandroid.relay.data.Profile(
name = profileName,
model = session.model.orEmpty(),
description = profileName,
)
} ?: com.hermesandroid.relay.data.Profile(
name = profileName,
model = "",
description = profileName,
)
chatViewModel.openProfileSession(
profileName = profileName,
profile = ownerProfile,
contextKey = AgentDisplay.profileContextKey(
connectionId = activeConnection?.id,
profileName = profileName,
),
sessionId = sessionId,
)
scope.launch { drawerState.close() }
} else {
scope.launch {
@@ -2174,6 +2281,54 @@ fun ChatScreen(
}
}
},
onDeleteProfileSession = { profileName, sessionId ->
scope.launch {
if (connectionViewModel.deleteSession(profileName, sessionId)) {
allProfileSessions = allProfileSessions.filterNot {
it.profile == profileName && it.session.sessionId == sessionId
}
}
}
},
onRenameProfileSession = { profileName, sessionId, title ->
scope.launch {
if (connectionViewModel.renameSession(profileName, sessionId, title)) {
allProfileSessions = allProfileSessions.map { row ->
if (row.profile == profileName && row.session.sessionId == sessionId) {
row.copy(session = row.session.copy(title = title))
} else {
row
}
}
}
}
},
onSetProfileSessionPinned = { profileName, sessionId, pinned ->
scope.launch {
if (connectionViewModel.setSessionPinned(profileName, sessionId, pinned)) {
allProfileSessions = allProfileSessions.map { row ->
if (row.profile == profileName && row.session.sessionId == sessionId) {
row.copy(session = row.session.copy(pinned = pinned))
} else {
row
}
}
}
}
},
onSetProfileSessionArchived = { profileName, sessionId, archived ->
scope.launch {
if (connectionViewModel.setSessionArchived(profileName, sessionId, archived)) {
allProfileSessions = allProfileSessions.map { row ->
if (row.profile == profileName && row.session.sessionId == sessionId) {
row.copy(session = row.session.copy(archived = archived))
} else {
row
}
}
}
}
},
)
}
) {
@@ -2279,7 +2434,6 @@ fun ChatScreen(
resolveChatHeaderSubtitle(
isStreaming = isStreaming,
statusText = statusText,
projectName = gatewayProjectName,
personalityName = nonDefaultPersonality,
modelName = modelName,
)
@@ -2586,7 +2740,7 @@ fun ChatScreen(
selectedProfile = selectedProfile,
resolvedProfile = effectiveProfile,
presentation = profilePresentation,
activeDisplayName = agentDisplayName,
activeDisplayName = globalSelectedAgentDisplayName,
isProfileLocked = isProfileLocked,
lockedProfileName = lockedProfileName,
switchEnabled = profileSwitchEnabled,
@@ -3112,9 +3266,12 @@ fun ChatScreen(
isGatewayTransport &&
messageReactionsSupported &&
!message.isStreaming &&
message.uiKey in newestReactableMessageKeys
(
message.rowId != null ||
message.uiKey in newestReactableMessageKeys
)
) {
{ emoji -> chatViewModel.reactToNewest(message.role, emoji) }
{ emoji -> chatViewModel.reactToMessage(message, emoji) }
} else {
null
},
@@ -4230,6 +4387,15 @@ fun ChatScreen(
}
}
internal fun buildProvisionalThreadRows(
entries: List<ProactiveInboxEntry>,
activeConnectionId: String?,
realThreadChatIds: Collection<String>,
): Map<String, List<ProactiveInboxEntry>> = entries
.filter { it.connectionId == null || it.connectionId == activeConnectionId }
.groupBy { it.chatId ?: "phone" }
.filterKeys { it !in realThreadChatIds }
// --- Helper functions ---
@Composable
@@ -64,6 +64,8 @@ import com.hermesandroid.relay.R
import com.hermesandroid.relay.auth.PairedDeviceInfo
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.data.secureLinkCoversAllServices
import com.hermesandroid.relay.data.routeAuthority
import com.hermesandroid.relay.ui.components.SessionTtlPickerDialog
import com.hermesandroid.relay.ui.components.TransportSecurityBadge
@@ -939,6 +941,17 @@ private fun EndpointsSubList(
fontFamily = FontFamily.Monospace,
modifier = Modifier.weight(1f),
)
if (candidate.hasSecureProxy()) {
Text(
text = if (candidate.secureLinkCoversAllServices()) {
stringResource(R.string.secure_link_pinned_tls_short)
} else {
stringResource(R.string.secure_link_partial_short)
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
if (isActive) {
Text(
text = stringResource(R.string.paired_devices_active),
@@ -77,10 +77,12 @@ import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryEntry
import com.hermesandroid.relay.data.ProfileSkillEntry
import com.hermesandroid.relay.data.GatewayProfileToolset
import com.hermesandroid.relay.ui.LocalSnackbarHost
import com.hermesandroid.relay.viewmodel.InspectorSection
import com.hermesandroid.relay.viewmodel.LoadState
import com.hermesandroid.relay.viewmodel.ProfileInspectorViewModel
import com.hermesandroid.relay.viewmodel.ProfileInspectorSource
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
@@ -123,6 +125,8 @@ fun ProfileInspectorScreen(
val soulState by viewModel.soulState.collectAsState()
val memoryState by viewModel.memoryState.collectAsState()
val skillsState by viewModel.skillsState.collectAsState()
val source by viewModel.source.collectAsState()
val gatewayDescription by viewModel.gatewayDescription.collectAsState()
// Lazy first-load on screen entry. Keyed on the profile name so a
// re-entry for a different profile (unlikely but possible via deep
@@ -244,6 +248,18 @@ fun ProfileInspectorScreen(
InspectorSection.Config -> ConfigPane(
state = configState,
onRetry = { viewModel.refreshSection(InspectorSection.Config) },
gatewayEditable = source == ProfileInspectorSource.Gateway,
editing = viewModel.configEditing.collectAsState().value,
descriptionDraft = viewModel.configDescriptionDraft.collectAsState().value,
providerDraft = viewModel.configProviderDraft.collectAsState().value,
modelDraft = viewModel.configModelDraft.collectAsState().value,
saving = viewModel.configSaving.collectAsState().value,
onBeginEdit = viewModel::beginConfigEdit,
onDescriptionChange = viewModel::updateConfigDescriptionDraft,
onProviderChange = viewModel::updateConfigProviderDraft,
onModelChange = viewModel::updateConfigModelDraft,
onSave = viewModel::saveConfigEdit,
onCancel = viewModel::cancelConfigEdit,
)
InspectorSection.Soul -> SoulPane(
state = soulState,
@@ -282,6 +298,13 @@ fun ProfileInspectorScreen(
onToggleSkill = { name, enabled ->
viewModel.toggleSkill(name, enabled)
},
gatewayNative = source == ProfileInspectorSource.Gateway,
skillDrafts = viewModel.skillDrafts.collectAsState().value,
toolsets = gatewayDescription?.toolsets.orEmpty(),
toolsetDrafts = viewModel.toolsetDrafts.collectAsState().value,
saving = viewModel.skillsSaving.collectAsState().value,
onToggleToolset = viewModel::toggleToolset,
onSaveDrafts = viewModel::saveSkillEdits,
)
}
}
@@ -291,6 +314,14 @@ fun ProfileInspectorScreen(
private data class InspectorTab(val label: String, val section: InspectorSection)
internal fun profileConfigSaveEnabled(provider: String, model: String, saving: Boolean): Boolean =
provider.isNotBlank() && model.isNotBlank() && !saving
internal fun gatewayDraftSaveVisible(
skillDrafts: Map<String, Boolean>,
toolsetDrafts: Map<String, Boolean>,
): Boolean = skillDrafts.isNotEmpty() || toolsetDrafts.isNotEmpty()
// ---------------------------------------------------------------
// Config pane — JSON tree with collapsible nested objects.
// ---------------------------------------------------------------
@@ -299,6 +330,18 @@ private data class InspectorTab(val label: String, val section: InspectorSection
private fun ConfigPane(
state: LoadState<ProfileConfigResponse>,
onRetry: () -> Unit,
gatewayEditable: Boolean,
editing: Boolean,
descriptionDraft: String,
providerDraft: String,
modelDraft: String,
saving: Boolean,
onBeginEdit: () -> Unit,
onDescriptionChange: (String) -> Unit,
onProviderChange: (String) -> Unit,
onModelChange: (String) -> Unit,
onSave: () -> Unit,
onCancel: () -> Unit,
) {
PaneShell(state = state, onRetry = onRetry) { response ->
var showRawConfig by remember(response.profile, response.config) {
@@ -318,6 +361,21 @@ private fun ConfigPane(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
if (gatewayEditable) {
GatewayConfigEditor(
editing = editing,
description = descriptionDraft,
provider = providerDraft,
model = modelDraft,
saving = saving,
onBeginEdit = onBeginEdit,
onDescriptionChange = onDescriptionChange,
onProviderChange = onProviderChange,
onModelChange = onModelChange,
onSave = onSave,
onCancel = onCancel,
)
}
ConfigSummaryCard(response)
OutlinedButton(
@@ -363,6 +421,75 @@ private fun ConfigPane(
}
}
@Composable
private fun GatewayConfigEditor(
editing: Boolean,
description: String,
provider: String,
model: String,
saving: Boolean,
onBeginEdit: () -> Unit,
onDescriptionChange: (String) -> Unit,
onProviderChange: (String) -> Unit,
onModelChange: (String) -> Unit,
onSave: () -> Unit,
onCancel: () -> Unit,
) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(stringResource(R.string.profile_inspector_gateway_settings), fontWeight = FontWeight.SemiBold)
Text(
stringResource(R.string.profile_inspector_gateway_settings_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (!editing) {
IconButton(onClick = onBeginEdit) {
Icon(Icons.Filled.Edit, stringResource(R.string.profile_inspector_edit_config))
}
}
}
if (editing) {
OutlinedTextField(
value = description,
onValueChange = onDescriptionChange,
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.profile_inspector_description)) },
)
OutlinedTextField(
value = provider,
onValueChange = onProviderChange,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text(stringResource(R.string.profile_inspector_provider)) },
)
OutlinedTextField(
value = model,
onValueChange = onModelChange,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text(stringResource(R.string.profile_inspector_model)) },
)
EditorBottomBar(
saving = saving,
canSave = profileConfigSaveEnabled(provider, model, saving),
onSave = onSave,
onCancel = onCancel,
)
}
}
}
}
@Composable
private fun ConfigSummaryCard(response: ProfileConfigResponse) {
val topLevelCount = response.config.size
@@ -1334,9 +1461,16 @@ private fun SkillsPane(
onRetry: () -> Unit,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
gatewayNative: Boolean,
skillDrafts: Map<String, Boolean>,
toolsets: List<GatewayProfileToolset>,
toolsetDrafts: Map<String, Boolean>,
saving: Boolean,
onToggleToolset: (String, Boolean) -> Unit,
onSaveDrafts: () -> Unit,
) {
PaneShell(state = state, onRetry = onRetry) { response ->
if (response.skills.isEmpty()) {
if (response.skills.isEmpty() && !gatewayNative) {
Column(
modifier = Modifier
.fillMaxSize()
@@ -1391,6 +1525,30 @@ private fun SkillsPane(
visibleCount = visibleSkills.size,
)
}
if (gatewayNative && toolsets.isNotEmpty()) {
item(key = "__toolsets__") {
GatewayToolsetsCard(
toolsets = toolsets,
drafts = toolsetDrafts,
onToggle = onToggleToolset,
)
}
}
if (gatewayNative && gatewayDraftSaveVisible(skillDrafts, toolsetDrafts)) {
item(key = "__save_gateway_drafts__") {
Button(
onClick = onSaveDrafts,
enabled = !saving,
modifier = Modifier.fillMaxWidth(),
) {
if (saving) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
}
Text(stringResource(if (saving) R.string.profile_inspector_saving else R.string.profile_inspector_save_changes))
}
}
}
if (visibleSkills.isEmpty()) {
item(key = "__skills_empty_filter__") {
Card(
@@ -1430,6 +1588,8 @@ private fun SkillsPane(
},
toggleSupported = toggleSupported,
onToggleSkill = onToggleSkill,
gatewayNative = gatewayNative,
skillDrafts = skillDrafts,
)
}
if (toggleSupported == false) {
@@ -1562,6 +1722,8 @@ private fun SkillCategorySection(
onToggleExpanded: () -> Unit,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
gatewayNative: Boolean,
skillDrafts: Map<String, Boolean>,
) {
val categoryStateDescription = stringResource(
if (expanded) {
@@ -1622,6 +1784,7 @@ private fun SkillCategorySection(
skill = skill,
toggleSupported = toggleSupported,
onToggleSkill = onToggleSkill,
controlledEnabled = if (gatewayNative) skillDrafts[skill.name] ?: skill.enabled else null,
)
if (index != skills.lastIndex) {
HorizontalDivider(
@@ -1640,6 +1803,7 @@ private fun SkillRow(
skill: ProfileSkillEntry,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
controlledEnabled: Boolean?,
) {
// Optimistic local toggle state. The VM's emitted events revert us
// on failure; on success the next `/skills` refetch will overwrite
@@ -1652,6 +1816,7 @@ private fun SkillRow(
// null (probe hasn't completed) → leave tappable but the PUT will
// ask authoritatively.
val switchEnabled = toggleSupported != false
val displayedEnabled = controlledEnabled ?: localEnabled
Row(
modifier = Modifier
@@ -1666,7 +1831,7 @@ private fun SkillRow(
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
if (!localEnabled) {
if (!displayedEnabled) {
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(R.string.profile_inspector_disabled),
@@ -1684,7 +1849,7 @@ private fun SkillRow(
}
}
val toggleDescription = stringResource(
if (localEnabled) {
if (displayedEnabled) {
R.string.profile_inspector_disable_skill
} else {
R.string.profile_inspector_enable_skill
@@ -1692,7 +1857,7 @@ private fun SkillRow(
skill.name,
)
androidx.compose.material3.Switch(
checked = localEnabled,
checked = displayedEnabled,
enabled = switchEnabled,
modifier = Modifier.semantics {
contentDescription = toggleDescription
@@ -1705,7 +1870,7 @@ private fun SkillRow(
// the next recomposition sees — when the VM updates
// the flag to false post-call, we reset the switch to
// the prior state on the next pass.
localEnabled = new
if (controlledEnabled == null) localEnabled = new
onToggleSkill(skill.name, new)
},
)
@@ -1720,6 +1885,44 @@ private fun SkillRow(
}
}
@Composable
private fun GatewayToolsetsCard(
toolsets: List<GatewayProfileToolset>,
drafts: Map<String, Boolean>,
onToggle: (String, Boolean) -> Unit,
) {
Card(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(R.string.profile_inspector_toolsets), fontWeight = FontWeight.SemiBold)
Text(
stringResource(R.string.profile_inspector_toolsets_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
toolsets.forEach { toolset ->
val enabled = drafts[toolset.name] ?: toolset.enabled
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(toolset.name, style = MaterialTheme.typography.bodyMedium)
Text(
stringResource(R.string.profile_inspector_tool_count, toolset.toolCount),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
androidx.compose.material3.Switch(
checked = enabled,
onCheckedChange = { onToggle(toolset.name, it) },
)
}
}
}
}
}
// ---------------------------------------------------------------
// Shared UI bits
// ---------------------------------------------------------------
@@ -0,0 +1,51 @@
package com.hermesandroid.relay.ui.theme
import androidx.compose.ui.graphics.Color
import java.util.Locale
import kotlin.math.abs
import kotlin.math.roundToInt
private const val PROFILE_SATURATION = 0.68f
private const val PROFILE_LIGHTNESS = 0.58f
/** The same evenly-spaced 12-hue picker model used by Hermes Desktop. */
val ProfileAccentSwatches: List<String> = (0 until 12).map { index ->
hslColor(index * 30f, PROFILE_SATURATION, PROFILE_LIGHTNESS).toRgbHex()
}
/** Desktop-compatible deterministic profile identity color; default remains neutral. */
fun resolveProfileAccent(name: String?, overrides: Map<String, String>): Color? {
val key = name?.trim().orEmpty()
if (key.isBlank() || key.equals("default", ignoreCase = true)) return null
return accentColor(overrides[key]) ?: deterministicProfileAccent(key)
}
internal fun deterministicProfileAccent(name: String): Color {
var hash = 0u
name.forEach { character -> hash = hash * 31u + character.code.toUInt() }
return hslColor((hash % 360u).toFloat(), PROFILE_SATURATION, PROFILE_LIGHTNESS)
}
private fun hslColor(hue: Float, saturation: Float, lightness: Float): Color {
val chroma = (1f - abs(2f * lightness - 1f)) * saturation
val section = (hue / 60f) % 6f
val x = chroma * (1f - abs(section % 2f - 1f))
val (red, green, blue) = when {
section < 1f -> Triple(chroma, x, 0f)
section < 2f -> Triple(x, chroma, 0f)
section < 3f -> Triple(0f, chroma, x)
section < 4f -> Triple(0f, x, chroma)
section < 5f -> Triple(x, 0f, chroma)
else -> Triple(chroma, 0f, x)
}
val match = lightness - chroma / 2f
return Color(red + match, green + match, blue + match)
}
private fun Color.toRgbHex(): String = String.format(
Locale.ROOT,
"#%02X%02X%02X",
(red * 255f).roundToInt(),
(green * 255f).roundToInt(),
(blue * 255f).roundToInt(),
)
@@ -1,8 +1,8 @@
package com.hermesandroid.relay.util
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
/**
* Cross-layer one-shot navigation requests.
@@ -18,23 +18,21 @@ import kotlinx.coroutines.flow.asSharedFlow
* `BridgeSafetySettingsScreen` instead of dropping the user on `MainActivity`'s
* home screen.
*
* Buffer: `extraBufferCapacity = 4` so back-to-back tryEmit calls during
* `onCreate → setContent` don't drop on the floor before `RelayApp`'s
* collector subscribes. Replay 0 — late subscribers shouldn't replay stale
* navigation intents from prior process lifetimes.
* A buffered [Channel] is intentional here: notification taps are consumed in
* `MainActivity.onCreate` before Compose installs RelayApp's collector. A
* replay-0 SharedFlow drops those cold-start requests when no subscriber exists.
* The channel retains up to four one-shot routes and hands each to the single
* app-root collector exactly once.
*/
object NavRouteRequest {
private val _requests = MutableSharedFlow<String>(
replay = 0,
extraBufferCapacity = 4,
)
private val channel = Channel<String>(capacity = 4)
val requests: SharedFlow<String> = _requests.asSharedFlow()
val requests: Flow<String> = channel.receiveAsFlow()
/** Fire-and-forget emit. Safe to call from any thread, including the main thread. */
fun tryRequest(route: String): Boolean = _requests.tryEmit(route)
fun tryRequest(route: String): Boolean = channel.trySend(route).isSuccess
suspend fun request(route: String) {
_requests.emit(route)
channel.send(route)
}
}
@@ -31,8 +31,10 @@ import com.hermesandroid.relay.data.MediaSettings
import com.hermesandroid.relay.data.MediaSettingsRepository
import com.hermesandroid.relay.data.MessageDeliveryStatus
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.applyMessageReaction
import com.hermesandroid.relay.data.parseChatQuotedPrompt
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.data.ProactiveInboxEntry
import com.hermesandroid.relay.data.RealtimeConversationContextMessage
import com.hermesandroid.relay.data.RealtimeTurnTrace
import com.hermesandroid.relay.data.SessionActivityState
@@ -92,6 +94,7 @@ import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.shared.LocalDispatchResult
import com.hermesandroid.relay.network.upstream.formatPhoneActionResult
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.parseMessageReactions
import com.hermesandroid.relay.network.upstream.SESSION_MESSAGE_PAGE_SIZE
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
import com.hermesandroid.relay.network.upstream.models.SessionItem
@@ -135,6 +138,7 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import okhttp3.sse.EventSource
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
@@ -832,7 +836,7 @@ class ChatViewModel : ViewModel() {
_approvalModeCapability.value = GatewayApprovalModeCapability.Unknown
return
}
val launchProfileOwned = sessionProfileNameProvider() == null
val launchProfileOwned = currentSessionProfileName() == null
_approvalModeWritable.value = launchProfileOwned
_approvalModeReadOnlyForProfile.value = !launchProfileOwned
if (!launchProfileOwned) {
@@ -982,7 +986,7 @@ class ChatViewModel : ViewModel() {
if (pairs.isEmpty()) return
val generation = relayCapabilityGeneration.incrementAndGet()
val profileKey = reasoningCapabilityContextKey()
val profile = sessionProfileNameProvider()
val profile = currentSessionProfileName()
viewModelScope.launch {
val result = relay.fetchModelCapabilities(
models = pairs.map {
@@ -1153,7 +1157,7 @@ class ChatViewModel : ViewModel() {
// here skips the setModel below, leaving the gateway on its true
// server-configured default.
val defaultModel = AgentDisplay.requestModelName(
(effectiveProfileProvider() ?: selectedProfileProvider())?.model
(openedSessionDisplayProfile ?: effectiveProfileProvider() ?: selectedProfileProvider())?.model
?: _serverModelName.value,
)
if (!defaultModel.isNullOrBlank()) {
@@ -1461,7 +1465,8 @@ class ChatViewModel : ViewModel() {
* new profile's agent. SSE turns already carry the profile per-request as
* `profileName`. [profile] = the new pick; null = the default profile.
*/
fun activateGatewayProfile(profile: Profile?) {
fun activateGatewayProfile(profile: Profile?, refreshModelOptions: Boolean = true) {
clearOpenedSessionOwner()
val gateway = gatewayClient ?: return
if (streamingEndpoint != "gateway") return
// A profile switch is a UI/context detach, not a Stop action. Preserve
@@ -1530,11 +1535,13 @@ class ChatViewModel : ViewModel() {
// config.get would read the launch/global profile's effort (wrong
// scope). It's left unknown above and confirmed by session.info on the
// first turn — the same honesty discipline yolo/fast use.
viewModelScope.launch {
gateway.modelOptions().onSuccess {
_modelProviders.value = it.providers
_gatewayCurrentModel.value = it.currentModel
_gatewayCurrentProvider.value = it.currentProvider
if (refreshModelOptions) {
viewModelScope.launch {
gateway.modelOptions().onSuccess {
_modelProviders.value = it.providers
_gatewayCurrentModel.value = it.currentModel
_gatewayCurrentProvider.value = it.currentProvider
}
}
}
refreshActiveAgentName()
@@ -1662,7 +1669,7 @@ class ChatViewModel : ViewModel() {
}
// Bind each gateway session.create/resume to the currently-selected
// profile (pulled live) — the upstream gateway builds the agent from it.
client?.sessionProfileProvider = { sessionProfileNameProvider() }
client?.sessionProfileProvider = { currentSessionProfileName() }
// Bind the in-chat picks onto each fresh session.create so a brand-new
// chat actually runs on the picked model/provider AND the chosen
// reasoning effort / fast tier (not the global default) — and so setting
@@ -2322,15 +2329,33 @@ class ChatViewModel : ViewModel() {
private val _transientNotice = MutableSharedFlow<String>(extraBufferCapacity = 8)
val transientNotice: SharedFlow<String> = _transientNotice.asSharedFlow()
fun reactToNewest(role: MessageRole, emoji: String?) {
fun reactToMessage(message: ChatMessage, emoji: String?) {
val gateway = gatewayClient ?: return
val role = message.role
if (role != MessageRole.USER && role != MessageRole.ASSISTANT) return
val handler = chatHandler ?: return
val snapshot = messages.value.firstOrNull { it.uiKey == message.uiKey }?.reactions
?: message.reactions
handler.mutateMessage(message.uiKey) { current ->
current.copy(reactions = applyMessageReaction(current.reactions, emoji))
}
viewModelScope.launch {
gateway.reactToNewest(role.name.lowercase(), emoji).fold(
onSuccess = {
gateway.reactToMessage(message.rowId, role.name.lowercase(), emoji).fold(
onSuccess = { result ->
val persisted = parseMessageReactions(result["reactions"])
val rowId = (result["row_id"] as? JsonPrimitive)?.longOrNull
handler.mutateMessage(message.uiKey) { current ->
current.copy(
rowId = rowId ?: current.rowId,
reactions = persisted,
)
}
_transientNotice.tryEmit(if (emoji == null) "Reaction removed." else "Reaction added.")
},
onFailure = { error ->
handler.mutateMessage(message.uiKey) { current ->
current.copy(reactions = snapshot)
}
if ((error as? GatewayRpcException)?.code == -32601) {
_messageReactionsSupported.value = false
_transientNotice.tryEmit("Message reactions aren't supported by this gateway.")
@@ -2442,7 +2467,12 @@ class ChatViewModel : ViewModel() {
* [regenerateFromMessage] and consumed by the next [startStream]
* gateway dispatch as `truncate_before_user_ordinal`.
*/
private var pendingTruncateOrdinal: Int? = null
private data class PendingGatewayTruncation(
val ordinal: Int,
val rowId: Long?,
)
private var pendingGatewayTruncation: PendingGatewayTruncation? = null
/**
* Provider for the active agent-profile pick — wired from [RelayApp] at
@@ -2486,6 +2516,22 @@ class ChatViewModel : ViewModel() {
}
private var displayAliasProvider: () -> String? = { null }
private var activeProfileContextKey: String? = null
private val _openedSessionProfileName = MutableStateFlow<String?>(null)
val openedSessionProfileName: StateFlow<String?> = _openedSessionProfileName.asStateFlow()
private var openedSessionDisplayProfile: Profile? = null
/**
* Profile namespace owned by the conversation currently on screen. Opening a
* row from the global All Profiles browser must not mutate the persistent
* profile selector, but resume/history/send still need the row's exact owner.
*/
private fun currentSessionProfileName(): String? =
_openedSessionProfileName.value ?: sessionProfileNameProvider()
private fun clearOpenedSessionOwner() {
_openedSessionProfileName.value = null
openedSessionDisplayProfile = null
}
/** Process ownership is profile+session scoped; stored IDs alone are not globally unique. */
private fun selectBackgroundProcessSession(
@@ -2589,14 +2635,14 @@ class ChatViewModel : ViewModel() {
* read that profile's own DB. Returns `null` off the dashboard surface.
*/
private var profileMessageLoader:
(suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?)? = null
(suspend (String?, String, SessionMessageLoadMode) -> Result<List<MessageItem>>?)? = null
fun setProfileMessageLoader(loader: suspend (String) -> Result<List<MessageItem>>?) {
profileMessageLoader = { sessionId, _ -> loader(sessionId) }
profileMessageLoader = { _, sessionId, _ -> loader(sessionId) }
}
fun setProfileMessageLoaderWithMode(
loader: suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?,
loader: suspend (String?, String, SessionMessageLoadMode) -> Result<List<MessageItem>>?,
) {
profileMessageLoader = loader
}
@@ -2611,9 +2657,10 @@ class ChatViewModel : ViewModel() {
sessionId: String,
requireProfileScope: Boolean = false,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
profileName: String? = currentSessionProfileName(),
): List<MessageItem> {
if (streamingEndpoint == "gateway") {
return loadGatewaySessionHistory(sessionId, requireProfileScope, mode)
return loadGatewaySessionHistory(sessionId, requireProfileScope, mode, profileName)
}
return apiClient?.getMessages(sessionId, mode) ?: emptyList()
}
@@ -2628,8 +2675,9 @@ class ChatViewModel : ViewModel() {
sessionId: String,
requireProfileScope: Boolean = false,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
profileName: String? = currentSessionProfileName(),
): List<MessageItem> {
val scoped = profileMessageLoader?.invoke(sessionId, mode)
val scoped = profileMessageLoader?.invoke(profileName, sessionId, mode)
if (scoped != null) {
// A gateway profile owns a distinct state.db. Never fall through to
// the launch/default API database when its scoped read fails: an
@@ -2786,7 +2834,7 @@ class ChatViewModel : ViewModel() {
approvalModeRevision.incrementAndGet()
_approvalMode.value = mode
_approvalModeCapability.value = GatewayApprovalModeCapability.Supported
val launchProfileOwned = sessionProfileNameProvider() == null
val launchProfileOwned = currentSessionProfileName() == null
_approvalModeWritable.value = launchProfileOwned
_approvalModeReadOnlyForProfile.value = !launchProfileOwned
}
@@ -2927,6 +2975,12 @@ class ChatViewModel : ViewModel() {
fun injectThreadMessage(msg: ProactiveMessage): Boolean {
val handler = chatHandler ?: return false
val msgChatId = msg.chatId?.takeIf { it.isNotBlank() }
pendingThread?.let { pending ->
if (msgChatId == null || msgChatId == pending.chatId) {
handler.addAgentThreadMessage(msg.text, msg.messageId, msg.title)
return true
}
}
// A freshly-created thread whose real session we're still switching to:
// show the agent's first reply in the draft view now (the switch
// reconciles it from history). Covers the gap before currentSessionId is
@@ -3225,7 +3279,7 @@ class ChatViewModel : ViewModel() {
selectedReasoningEffortConfirmedIdentity = null
_reasoningDisplay.value = null
_selectedPersonality.value = "default"
pendingTruncateOrdinal = null
pendingGatewayTruncation = null
chatHandler?.let { handler ->
handler.clearMessages()
handler.clearSessions()
@@ -3240,7 +3294,50 @@ class ChatViewModel : ViewModel() {
}
}
fun openProfileSession(
profileName: String,
profile: Profile?,
contextKey: String,
sessionId: String,
) {
// Detach the old live gateway session without reading launch/global
// model options: session.info for the resumed owner is authoritative.
activateGatewayProfile(profile, refreshModelOptions = false)
_openedSessionProfileName.value = profileName
openedSessionDisplayProfile = profile
refreshActiveAgentName(profile, relabelGenericMessages = true)
switchProfileContextInternal(contextKey, sessionId, persistLastSession = false)
}
/**
* Start a fresh draft owned by an explicit profile without changing the
* persistent profile selector. The All Profiles browser uses this for its
* New chat action, where upstream's literal `default` profile must win over
* the server's sticky active profile.
*/
fun createProfileChat(
profileName: String,
profile: Profile?,
contextKey: String,
) {
activateGatewayProfile(profile, refreshModelOptions = false)
_openedSessionProfileName.value = profileName
openedSessionDisplayProfile = profile
refreshActiveAgentName(profile, relabelGenericMessages = true)
switchProfileContextInternal(contextKey, sessionId = null, persistLastSession = false)
AppAnalytics.onSessionCreated()
}
fun switchProfileContext(contextKey: String, sessionId: String?) {
clearOpenedSessionOwner()
switchProfileContextInternal(contextKey, sessionId)
}
private fun switchProfileContextInternal(
contextKey: String,
sessionId: String?,
persistLastSession: Boolean = true,
) {
val handler = chatHandler ?: return
val isInitialContextBinding = activeProfileContextKey == null
handler.activeAgentName = currentAgentDisplayName()
@@ -3274,6 +3371,7 @@ class ChatViewModel : ViewModel() {
if (!isInitialContextBinding) releaseTurnForNavigation(handler)
cancelAnswerRecovery(settleUi = false)
val loadGeneration = historyLoadGeneration.incrementAndGet()
val sessionProfileName = currentSessionProfileName()
sessionRefreshGeneration.incrementAndGet()
sessionRefreshJob?.cancel()
_isLoadingSessions.value = false
@@ -3318,12 +3416,12 @@ class ChatViewModel : ViewModel() {
// recompute it now that the overlay is cleared so the header/bubbles read
// the new profile's base identity, not the old persona.
handler.activeAgentName = currentAgentDisplayName()
pendingTruncateOrdinal = null
pendingGatewayTruncation = null
handler.clearSessions()
handler.setSessionId(sessionId)
publishQueuedMessages()
selectBackgroundProcessSession(sessionId, contextKey)
if (sessionId != null) {
if (sessionId != null && persistLastSession) {
onSessionChanged?.invoke(sessionId)
}
@@ -3356,7 +3454,7 @@ class ChatViewModel : ViewModel() {
false
}
if (!recovered) {
val messages = loadSessionHistory(sessionId)
val messages = loadSessionHistory(sessionId, profileName = sessionProfileName)
if (stillCurrent()) {
handler.loadMessageHistory(messages)
if (streamingEndpoint == "gateway") gatewayClient?.prewarm(sessionId)
@@ -3545,6 +3643,9 @@ class ChatViewModel : ViewModel() {
fun createNewChat() {
val handler = chatHandler ?: return
clearOpenedSessionOwner()
pendingThread = null
creatingThread = null
// Gateway turns continue as detached siblings; SSE remains exclusive.
releaseTurnForNavigation(handler)
@@ -3661,6 +3762,43 @@ class ChatViewModel : ViewModel() {
onSessionChanged?.invoke(null)
}
/**
* Open an agent-initiated Thread before the gateway has a `source=phone`
* session for it. Outbound platform sends do not create gateway sessions;
* the first phone reply does. Until then the durable proactive inbox is the
* provisional transcript. The existing pending-thread send path promotes
* this draft to the real gateway session after the user's first reply.
*/
fun openProactiveThread(chatId: String, entries: List<ProactiveInboxEntry>) {
val handler = chatHandler ?: return
val normalizedChatId = chatId.ifBlank { "phone" }
val ordered = entries
.filter { (it.chatId ?: "phone") == normalizedChatId }
.sortedBy { it.receivedAt }
if (ordered.isEmpty()) return
releaseTurnForNavigation(handler)
cancelAnswerRecovery(settleUi = false)
historyLoadGeneration.incrementAndGet()
pendingThread = PendingThread(
chatId = normalizedChatId,
name = ordered.last().title.ifBlank { "Hermes" },
)
creatingThread = null
gatewayClient?.clearSession()
handler.setSessionId(null)
selectBackgroundProcessSession(null)
handler.clearMessages()
ordered.forEach { entry ->
handler.addAgentThreadMessage(entry.text, entry.id, entry.title)
}
_contextUsage.value = null
_contextWindow.value = null
dismissPendingAskNotification()
_pendingAsk.value = null
onSessionChanged?.invoke(null)
}
/**
* After a "+ New Thread" first send, poll the session list until the gateway
* has created the new `source=phone` session, then switch to it (loading its
@@ -3705,7 +3843,10 @@ class ChatViewModel : ViewModel() {
fun switchSession(sessionId: String) {
val handler = chatHandler ?: return
clearOpenedSessionOwner()
if (streamingEndpoint != "gateway" && apiClient == null) return
pendingThread = null
creatingThread = null
// Keep a Gateway sibling alive and detach its callbacks. SSE remains a
// single exclusive stream and is interrupted on navigation.
@@ -4501,7 +4642,7 @@ class ChatViewModel : ViewModel() {
.indexOfFirst { it.id == userMessageId }
if (ordinal < 0) return false
handler.truncateMessagesFrom(userMessageId)
pendingTruncateOrdinal = ordinal
pendingGatewayTruncation = PendingGatewayTruncation(ordinal, target.rowId)
sendMessageInternal(apiClient, handler, newText)
return true
}
@@ -4635,7 +4776,7 @@ class ChatViewModel : ViewModel() {
}
val summary = when (result.status.lowercase()) {
"aborted" -> "Compression aborted."
"noop", "no_op" -> "Nothing to compress."
"noop", "no_op" -> result.output ?: "Nothing to compress."
"legacy" -> result.output ?: "Compression command sent through legacy slash support."
else -> result.output ?: compressionSummary(result)
}
@@ -4762,7 +4903,7 @@ class ChatViewModel : ViewModel() {
private fun maybeNotifyInteraction(
sessionId: String,
ask: GatewayAsk,
profile: String? = sessionProfileNameProvider(),
profile: String? = currentSessionProfileName(),
) {
val context = appContext ?: return
InteractionRequestNotifier.notify(
@@ -4778,7 +4919,7 @@ class ChatViewModel : ViewModel() {
private fun cancelInteractionNotification(
sessionId: String,
ask: GatewayAsk,
profile: String? = sessionProfileNameProvider(),
profile: String? = currentSessionProfileName(),
) {
val context = appContext ?: return
InteractionRequestNotifier.cancel(context, sessionId, ask, profile)
@@ -7664,54 +7805,22 @@ class ChatViewModel : ViewModel() {
// Edit-and-regenerate ordinal — armed by regenerateFromMessage for
// exactly the next turn; consumed even when the turn lands on SSE
// (the post-turn reload reconciles divergence in that case).
val truncateOrdinal = pendingTruncateOrdinal
pendingTruncateOrdinal = null
val pendingTruncation = pendingGatewayTruncation
pendingGatewayTruncation = null
val gateway = gatewayClient
_steerableTurn.value = false
// Voice turns must deliver their interface + spoken-output-formatting
// context to the model, but the gateway prompt.submit RPC has NO
// system-message slot (it is bare text — see the else branch). Prepending
// to the user text would persist the instruction into the transcript.
// The SSE endpoints carry it in the non-persisted system_message field
// instead, so force any turn that has a per-turn interface context
// (set only by sendVoiceMessage) onto SSE. resolveSseFallback picks the
// best available SSE route.
// Gateway prompt.submit has no system-message slot, so its voice turn
// cannot carry the optional spoken-output formatting hint. Keep the turn
// on Gateway anyway: the API server is an optional fallback and may not
// be reachable from the phone. A working vanilla Gateway turn is more
// important than silently making standard voice depend on port 8642.
// SSE-selected connections still receive the interface context normally.
//
// Synthetic voice-intent and provider-answered realtime traces have the
// same gateway limitation — prompt.submit can't carry them — but on a
// gateway-primary phone "leave them for the next SSE turn" means *never*.
// Drain those voice-only traces by forcing this one turn onto the sessions
// SSE route, but ONLY when that is strictly safe:
// - an existing session id + the sessions fallback route (a stateless
// completions/runs detour would drop THIS turn from the transcript
// to save a trace — worse than deferring), and
// - the default profile (a non-default profile's gateway session lives
// in that profile's own state.db, which the shared api_server surface
// can't see — the sessions POST would 404 and fail the user's turn).
// Cost when it fires: one turn without live gateway thinking. The synced
// traces persist server-side, so this happens at most once per batch.
//
// Rich-card actions are different: the action itself is the current user
// turn. Keep it on the selected Gateway and defer its optional synthetic
// audit trace until a naturally selected SSE turn. A card must never
// activate or depend on the optional API fallback.
val sseDrainEndpoint = resolveSseFallback(handler)
val forceSseForVoiceTraceDrain =
client != null &&
(hasVoiceIntents || hasRealtimeTurns) &&
streamingEndpoint == "gateway" &&
profileName == null &&
sseDrainEndpoint == "sessions"
val effectiveEndpoint =
if (client != null &&
(interfaceContextPrompt != null || forceSseForVoiceTraceDrain) &&
streamingEndpoint == "gateway"
) {
sseDrainEndpoint
} else {
streamingEndpoint
}
// Synthetic local traces also wait for a naturally selected SSE turn.
// They are supplemental context and must never make a connected Gateway
// turn depend on the optional API server.
val effectiveEndpoint = streamingEndpoint
updateTurnCheckpointTransport(effectiveEndpoint)
// Remember whether this turn runs on the gateway client (vs an SSE
// EventSource) so a mid-turn route handoff doesn't cancel it — only the
@@ -7829,8 +7938,10 @@ class ChatViewModel : ViewModel() {
),
attachments = attachments.orEmpty()
.map { it.toGatewayAttachment() },
truncateBeforeUserOrdinal = truncateOrdinal,
truncateBeforeUserOrdinal = pendingTruncation?.ordinal,
truncateBeforeRowId = pendingTruncation?.rowId,
queuedFollowUp = queuedFollowUp,
onSurvivorUserRowIds = handler::rebindSurvivorUserRowIds,
onPreflightFailure = {
_steerableTurn.value = false
if (intentionallyCancelled) {
@@ -7897,6 +8008,7 @@ class ChatViewModel : ViewModel() {
): String? {
val selectedProfile = selectedProfileProvider()
val effectiveProfile = effectiveProfileOverride
?: openedSessionDisplayProfile
?: displayProfileProvider()
?: effectiveProfileProvider()
?: selectedProfile
@@ -7905,7 +8017,11 @@ class ChatViewModel : ViewModel() {
selectedPersonality = _selectedPersonality.value,
defaultPersonality = _defaultPersonality.value,
connectionLabel = null,
localDisplayAlias = displayAliasProvider(),
localDisplayAlias = if (_openedSessionProfileName.value == null) {
displayAliasProvider()
} else {
null
},
).ifBlank { null }
}
@@ -33,6 +33,7 @@ import com.hermesandroid.relay.data.DemoMode
import com.hermesandroid.relay.data.DashboardEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.MediaSettingsRepository
import com.hermesandroid.relay.data.PairingPreferences
@@ -82,9 +83,14 @@ import com.hermesandroid.relay.network.upstream.mirrorDashboardSessionCookies
import com.hermesandroid.relay.network.upstream.DashboardAuthSession
import com.hermesandroid.relay.network.upstream.DashboardCookieStore
import com.hermesandroid.relay.network.upstream.DashboardStatus
import com.hermesandroid.relay.network.upstream.multiplexServedProfiles
import com.hermesandroid.relay.network.upstream.NativeDashboardAuthClient
import com.hermesandroid.relay.network.upstream.ToolsetInfo
import com.hermesandroid.relay.network.shared.EndpointResolver
import com.hermesandroid.relay.network.shared.buildPluginProxyClient
import com.hermesandroid.relay.network.shared.buildHermesReachClient
import com.hermesandroid.relay.network.shared.hermesReachRouteOrNull
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
import com.hermesandroid.relay.network.upstream.GatewayAvailability
import com.hermesandroid.relay.network.upstream.ActiveTurnKeepAliveRegistry
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
@@ -238,6 +244,7 @@ internal fun resolveEffectiveDashboardUrl(
endpoint: EndpointCandidate?,
): String {
if (connection == null) return ""
endpoint?.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { return it }
endpoint?.dashboard?.url
?.takeIf { it.isNotBlank() }
?.let { return it }
@@ -260,6 +267,7 @@ internal fun resolveEffectiveApiServerUrl(
endpoint: EndpointCandidate?,
): String {
if (savedUrl.isBlank()) return ""
endpoint?.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { return it }
return endpoint?.api?.url?.takeIf { it.isNotBlank() } ?: savedUrl
}
@@ -608,6 +616,25 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
private val endpointResolver = EndpointResolver(
httpClient = endpointProbeClient,
clientForCandidate = { candidate ->
candidate.pluginProxyRoutesOrNull()?.let { proxy ->
val tokenProvider = { (authManager.authState.value as? AuthState.Paired)?.token }
if (candidate.hermesReachRouteOrNull() != null) {
buildHermesReachClient(
baseBuilder = endpointProbeClient.newBuilder(),
outerClient = endpointProbeClient,
candidate = candidate,
sessionTokenProvider = tokenProvider,
)
} else {
buildPluginProxyClient(
baseBuilder = endpointProbeClient.newBuilder(),
routes = proxy,
sessionTokenProvider = tokenProvider,
)
}
}
},
context = application,
)
@@ -618,6 +645,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
context = application,
endpointResolver = endpointResolver,
endpointCandidatesProvider = { activeRouteCandidatesSnapshot() },
proxyClientProvider = { url -> pluginProxyClientForUrl(url) },
// Pull the active device id through AuthManager — it's the same id
// PairingPreferences keys the endpoint list on. Nullable wrapper
// because AuthManager.getOrCreateDeviceId() is suspending.
@@ -713,6 +741,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
tokenStoreKeyProvider = { cid ->
connectionStore.connections.value.firstOrNull { it.id == cid }?.tokenStoreKey
},
pinnedClientProvider = { url, base ->
pluginProxyClientForUrl(url, base, includeRelaySessionHeader = false)
},
)
// Agent-profiles collaborator — owns the merged profile list, the
@@ -784,7 +815,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
*/
val relayRowState: StateFlow<RelayRowState> = combine(
_relayUiState,
connectionManager.activeEndpoint,
connectionManager.activeRelayEndpoint,
) { phase, endpoint ->
RelayRowState(phase = phase, activeEndpointRole = endpoint?.role)
}.stateIn(
@@ -862,11 +893,55 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
private fun effectiveApiServerUrlSnapshot(): String =
resolveEffectiveApiServerUrl(
savedUrl = _apiServerUrl.value,
endpoint = connectionManager.activeEndpoint.value,
endpoint = connectionManager.activeApiEndpoint.value,
)
private fun effectiveRelayUrlSnapshot(): String =
connectionManager.activeEndpoint.value?.relay?.url ?: autoRelayUrlSnapshot()
connectionManager.activeEndpoint.value?.relay?.url
?: autoRelayUrlSnapshot()
private fun effectiveRelayWebSocketUrlSnapshot(): String =
connectionManager.activeRelayEndpoint.value?.pluginProxyRoutesOrNull()?.relayWebSocketUrl
?: connectionManager.activeRelayEndpoint.value?.relay?.url
?: autoRelayUrlSnapshot()
private fun pluginProxyClientForUrl(
url: String,
baseClient: OkHttpClient? = null,
includeRelaySessionHeader: Boolean = true,
): OkHttpClient? {
val requestAuthority = runCatching {
val parsed = java.net.URI(url)
val port = if (parsed.port > 0) parsed.port else 443
"${parsed.host?.lowercase()}:$port"
}.getOrNull() ?: return null
val candidate = activeConnection.value?.routeCandidates.orEmpty()
.firstOrNull { it.pluginProxyRoutesOrNull()?.authority == requestAuthority }
?: return null
val routes = candidate.pluginProxyRoutesOrNull() ?: return null
val configuredBuilder = (baseClient?.newBuilder() ?: OkHttpClient.Builder())
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.pingInterval(30, TimeUnit.SECONDS)
val sessionTokenProvider = {
(authManager.authState.value as? AuthState.Paired)?.token
}
if (candidate.hermesReachRouteOrNull() != null) {
return buildHermesReachClient(
baseBuilder = configuredBuilder,
outerClient = endpointProbeClient,
candidate = candidate,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
)
}
return buildPluginProxyClient(
baseBuilder = configuredBuilder,
routes = routes,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
)
}
private fun autoRelayUrlSnapshot(): String {
val savedRelay = _relayUrl.value
@@ -1127,7 +1202,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
*/
val effectiveApiServerUrl: StateFlow<String> = combine(
_apiServerUrl,
connectionManager.activeEndpoint,
connectionManager.activeApiEndpoint,
) { savedUrl, endpoint ->
resolveEffectiveApiServerUrl(savedUrl, endpoint)
}.stateIn(viewModelScope, SharingStarted.Eagerly, "")
@@ -1496,11 +1571,30 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
suspend fun listAllProfileSessions(limit: Int = 200): Result<List<SessionItem>>? =
profileController.listAllProfileSessions(limit)
suspend fun deleteSession(profileName: String, sessionId: String): Boolean =
profileController.deleteSession(profileName, sessionId)
suspend fun renameSession(profileName: String, sessionId: String, title: String): Boolean =
profileController.renameSession(profileName, sessionId, title)
suspend fun setSessionPinned(profileName: String, sessionId: String, pinned: Boolean): Boolean =
profileController.setSessionPinned(profileName, sessionId, pinned)
suspend fun setSessionArchived(profileName: String, sessionId: String, archived: Boolean): Boolean =
profileController.setSessionArchived(profileName, sessionId, archived)
suspend fun loadProfileScopedMessages(
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
suspend fun loadProfileScopedMessages(
profileName: String?,
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? =
profileController.loadProfileScopedMessages(profileName, sessionId, mode)
/**
* Delete a session scoped to the ACTIVE PROFILE via the dashboard
* `DELETE /api/sessions/{id}?profile=` surface — the write twin of
@@ -1549,6 +1643,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
fun setProfileHidden(profileName: String?, hidden: Boolean) =
profileController.setProfileHidden(profileName, hidden)
fun setProfileColor(profileName: String, colorHex: String?) =
profileController.setProfileColor(profileName, colorHex)
fun resetProfilePresentation() = profileController.resetProfilePresentation()
/**
@@ -1857,6 +1954,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
init {
authManager.setActiveEndpointProvider { connectionManager.activeRelayEndpoint.value }
// Materialize the independent central and floating preferences. Legacy
// users retain the prior visual in both roles until they choose otherwise.
viewModelScope.launch {
@@ -2286,6 +2384,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
text = msg.text,
receivedAt = msg.sentAt ?: System.currentTimeMillis(),
chatId = msg.chatId,
connectionId = connectionStore.activeConnectionId.value,
),
)
}
@@ -2461,6 +2560,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
private fun installAuthManager(am: AuthManager) {
am.setActiveEndpointProvider { connectionManager.activeRelayEndpoint.value }
authManager = am
// Push into the flow so the flatMapLatest chains on authState /
// pairingCode / currentPairedSession repoint to the new manager.
@@ -4559,14 +4659,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
?.dashboardLastStatus
val liveTopology = topologyConnectionId == activeConnectionId
val mode = if (liveTopology) topologyGatewayMode else persisted?.gatewayMode
val profiles = if (liveTopology) topologyProfiles else persisted?.profiles.orEmpty()
val profiles = if (liveTopology) topologyProfiles else persisted?.servedProfiles.orEmpty()
return mode.equals("multiplex", ignoreCase = true) && profile.name in profiles
}
/** Keep chat routing synchronized with the latest public dashboard topology. */
private suspend fun updateDashboardTopology(connectionId: String, status: DashboardStatus?) {
val nextMode = status?.gatewayMode
val nextProfiles = status?.profiles.orEmpty()
val nextProfiles = status?.multiplexServedProfiles().orEmpty()
val changed = topologyConnectionId != connectionId ||
topologyGatewayMode != nextMode ||
topologyProfiles != nextProfiles
@@ -4611,6 +4711,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
previous.authRequired == status?.authRequired &&
previous.authenticated == session?.authenticated &&
previous.gatewayMode == status?.gatewayMode &&
previous.servedProfiles == status?.multiplexServedProfiles().orEmpty() &&
previous.profiles == status?.profiles.orEmpty()
if (!materiallySame) {
recordDashboardStatus(status = status, session = session, reachable = reachable)
@@ -5177,6 +5278,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
gatewayTicketAvailable = gatewayTicketAvailable,
message = message,
gatewayMode = status?.gatewayMode,
servedProfiles = status?.multiplexServedProfiles().orEmpty(),
profiles = status?.profiles.orEmpty(),
),
)
@@ -5211,6 +5313,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
gatewayTicketAvailable = false,
message = "Dashboard session cleared",
gatewayMode = active?.dashboardLastStatus?.gatewayMode,
servedProfiles = active?.dashboardLastStatus?.servedProfiles.orEmpty(),
profiles = active?.dashboardLastStatus?.profiles.orEmpty(),
),
)
@@ -5617,7 +5720,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
profileApiUrl = selectedProfile?.apiServerUrl,
selectedProfileName = selectedProfile?.name,
gatewayMode = if (liveTopology) topologyGatewayMode else topology?.gatewayMode,
servedProfiles = if (liveTopology) topologyProfiles else topology?.profiles.orEmpty(),
servedProfiles = if (liveTopology) topologyProfiles else topology?.servedProfiles.orEmpty(),
)
}
@@ -5742,7 +5845,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
// a coherent in-flight pose instead of flashing the previous
// result through.
_apiServerHealth.value = HealthStatus.Probing
val client = HermesApiClient(baseUrl = url, apiKey = key)
val client = HermesApiClient(
baseUrl = url,
apiKey = key,
httpClient = pluginProxyClientForUrl(
url, includeRelaySessionHeader = false
),
)
_apiClient.value = client
shutdownClientOffMain(oldClient)
val ok = client.checkHealth()
@@ -5774,7 +5883,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
?.dashboardLastStatus
val liveTopology = topologyConnectionId == activeConnectionId
val gatewayMode = if (liveTopology) topologyGatewayMode else topology?.gatewayMode
val servedProfiles = if (liveTopology) topologyProfiles else topology?.profiles.orEmpty()
val servedProfiles = if (liveTopology) topologyProfiles else topology?.servedProfiles.orEmpty()
val usesMultiplexProfileKey = ProfileApiUrlResolver.usesMultiplexProfileKey(
profileApiUrl = selectedProfile?.apiServerUrl,
selectedProfileName = selectedProfile?.name,
@@ -5821,7 +5930,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
return
}
val nextProfileClient = HermesApiClient(baseUrl = profileApiUrl, apiKey = key)
val nextProfileClient = HermesApiClient(
baseUrl = profileApiUrl,
apiKey = key,
httpClient = pluginProxyClientForUrl(
profileApiUrl, includeRelaySessionHeader = false
),
)
profileChatApiClient = nextProfileClient
profileChatApiClientUrl = profileApiUrl
profileChatApiClientKey = key
@@ -5870,7 +5985,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
fun connectRelay() {
connectRelayInternal(effectiveRelayUrlSnapshot())
connectRelayInternal(effectiveRelayWebSocketUrlSnapshot())
}
/**
@@ -6273,6 +6388,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
* is unavailable.
*/
suspend fun lookupEndpointPin(candidate: com.hermesandroid.relay.data.EndpointCandidate): String? {
candidate.proxy?.pinSha256?.takeIf { candidate.hasSecureProxy() }?.let { return it }
val hostPort = candidate.routeAuthority() ?: return null
val pins = PairingPreferences.getTofuPins(getApplication())
return pins[hostPort]
@@ -3,11 +3,21 @@ package com.hermesandroid.relay.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryResponse
import com.hermesandroid.relay.data.ProfileSkillEntry
import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.network.relay.RelayProfileInspectorClient
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
@@ -15,24 +25,12 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
/**
* One of the four sections the inspector screen can display — used by
* [ProfileInspectorViewModel.refreshSection] to target a single pane
* without reloading the whole screen.
*/
enum class InspectorSection { Config, Soul, Memory, Skills }
/**
* Generic load state for each of the four inspector sections. Kept
* separate per section so a slow `/memory` fetch doesn't block the
* already-arrived `/config` tab from rendering.
*
* `Idle` is the pre-first-fetch state (useful for "don't render anything
* yet"); `Loading` is during an active fetch; `Loaded` carries the
* successfully-parsed payload; `Error` carries a human-readable message
* for inline display with a retry button.
*/
sealed class LoadState<out T> {
data object Idle : LoadState<Nothing>()
data object Loading : LoadState<Nothing>()
@@ -40,168 +38,150 @@ sealed class LoadState<out T> {
data class Error(val message: String) : LoadState<Nothing>()
}
enum class ProfileInspectorSource { Unknown, Gateway, Relay }
/**
* ViewModel for the Profile Inspector screen. Owns four load states
* (one per section) plus a one-shot `loadAll()` and per-section
* `refreshSection()` for pull-to-refresh. Lazy: no fetch is kicked off
* until the screen first calls [loadAll].
*
* The inspected profile name comes in via [SavedStateHandle] so it
* survives process death — Android nav graph arg → SavedStateHandle is
* the standard path. If the arg is missing (unexpected), [profileName]
* falls back to an empty string and every fetch short-circuits to an
* error state.
* Owns one immutable profile-name namespace. Gateway-native describe/configure
* is preferred when the active connection exposes it; Relay reads remain the
* compatibility fallback and the sole owner of memory-file editing.
*/
class ProfileInspectorViewModel(
private val client: RelayProfileInspectorClient,
private val legacyClient: LegacyProfileInspectorClient,
private val gatewayClient: GatewayProfileEditorClient?,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
/**
* Key the screen pass on. Read from [SavedStateHandle] so a
* process-death restore brings the same profile back — Android
* nav args are automatically mirrored into savedStateHandle when
* the screen is registered via `composable(route, arguments=...)`.
*/
val profileName: String =
savedStateHandle.get<String>(ARG_PROFILE_NAME).orEmpty()
val profileName: String = savedStateHandle.get<String>(ARG_PROFILE_NAME).orEmpty()
private val _configState =
MutableStateFlow<LoadState<ProfileConfigResponse>>(LoadState.Idle)
val configState: StateFlow<LoadState<ProfileConfigResponse>> =
_configState.asStateFlow()
private val _source = MutableStateFlow(ProfileInspectorSource.Unknown)
val source: StateFlow<ProfileInspectorSource> = _source.asStateFlow()
private val _soulState =
MutableStateFlow<LoadState<ProfileSoulResponse>>(LoadState.Idle)
val soulState: StateFlow<LoadState<ProfileSoulResponse>> =
_soulState.asStateFlow()
private val _gatewayDescription = MutableStateFlow<GatewayProfileDescription?>(null)
val gatewayDescription: StateFlow<GatewayProfileDescription?> = _gatewayDescription.asStateFlow()
private val _memoryState =
MutableStateFlow<LoadState<ProfileMemoryResponse>>(LoadState.Idle)
val memoryState: StateFlow<LoadState<ProfileMemoryResponse>> =
_memoryState.asStateFlow()
private val _configState = MutableStateFlow<LoadState<ProfileConfigResponse>>(LoadState.Idle)
val configState: StateFlow<LoadState<ProfileConfigResponse>> = _configState.asStateFlow()
private val _soulState = MutableStateFlow<LoadState<ProfileSoulResponse>>(LoadState.Idle)
val soulState: StateFlow<LoadState<ProfileSoulResponse>> = _soulState.asStateFlow()
private val _memoryState = MutableStateFlow<LoadState<ProfileMemoryResponse>>(LoadState.Idle)
val memoryState: StateFlow<LoadState<ProfileMemoryResponse>> = _memoryState.asStateFlow()
private val _skillsState = MutableStateFlow<LoadState<ProfileSkillsResponse>>(LoadState.Idle)
val skillsState: StateFlow<LoadState<ProfileSkillsResponse>> = _skillsState.asStateFlow()
private val _skillsState =
MutableStateFlow<LoadState<ProfileSkillsResponse>>(LoadState.Idle)
val skillsState: StateFlow<LoadState<ProfileSkillsResponse>> =
_skillsState.asStateFlow()
// -----------------------------------------------------------------
// UI view-state flags — session-scoped (no DataStore). All of these
// are kept on the VM rather than inside the Composable so they
// survive process-death restore via SavedStateHandle plumbing and
// — more importantly — recomposition-bound state hoists cleanly
// into a single source of truth per pane.
// -----------------------------------------------------------------
/**
* SOUL pane render mode. Defaults to rendered markdown — raw source
* is an explicit opt-in toggle in the top-right of the pane. Kept
* session-scoped because "Bailey wants raw this time" is a transient
* preference, not something worth persisting across app restarts.
*/
private val _soulRawView = MutableStateFlow(false)
val soulRawView: StateFlow<Boolean> = _soulRawView.asStateFlow()
fun toggleSoulRawView() {
_soulRawView.value = !_soulRawView.value
}
// -----------------------------------------------------------------
// Edit-mode state for SOUL + memory panes.
//
// Both panes share the same edit-mode pattern:
// 1. User taps the pencil icon → enters edit mode.
// 2. A monospace BasicTextField lets them type; state is kept in
// [soulDraft] / [memoryDraft]. The currently-saving flag is
// [soulSaving] / [memorySaving] so the Save button disables
// and a progress indicator renders.
// 3. On Save we PUT and, on success, reload the pane (fresh
// content from disk) and emit an [EditEvent.Saved] so the
// screen shows a snackbar. On failure we stay in edit mode so
// the user can retry.
//
// Per-memory-entry edit uses the same triple of flows keyed by
// filename. A separate key-based design (rather than "one memory
// entry at a time") keeps the door open to tabbed edits later
// without rewiring the state model.
// -----------------------------------------------------------------
/** User-facing snackbar events emitted by the edit pipeline. */
sealed class EditEvent {
data class Saved(val message: String) : EditEvent()
data class Error(val message: String) : EditEvent()
}
private val _editEvents = MutableSharedFlow<EditEvent>(
extraBufferCapacity = 8,
)
private val _editEvents = MutableSharedFlow<EditEvent>(extraBufferCapacity = 8)
val editEvents: SharedFlow<EditEvent> = _editEvents.asSharedFlow()
// --- SOUL edit state ---------------------------------------------
private val _soulRawView = MutableStateFlow(false)
val soulRawView: StateFlow<Boolean> = _soulRawView.asStateFlow()
fun toggleSoulRawView() { _soulRawView.value = !_soulRawView.value }
private val _configEditing = MutableStateFlow(false)
val configEditing: StateFlow<Boolean> = _configEditing.asStateFlow()
private val _configDescriptionDraft = MutableStateFlow("")
val configDescriptionDraft: StateFlow<String> = _configDescriptionDraft.asStateFlow()
private val _configProviderDraft = MutableStateFlow("")
val configProviderDraft: StateFlow<String> = _configProviderDraft.asStateFlow()
private val _configModelDraft = MutableStateFlow("")
val configModelDraft: StateFlow<String> = _configModelDraft.asStateFlow()
private val _configSaving = MutableStateFlow(false)
val configSaving: StateFlow<Boolean> = _configSaving.asStateFlow()
fun beginConfigEdit() {
val description = _gatewayDescription.value ?: return
_configDescriptionDraft.value = description.description
_configProviderDraft.value = description.provider
_configModelDraft.value = description.model
_configEditing.value = true
}
fun updateConfigDescriptionDraft(value: String) { _configDescriptionDraft.value = value }
fun updateConfigProviderDraft(value: String) { _configProviderDraft.value = value }
fun updateConfigModelDraft(value: String) { _configModelDraft.value = value }
fun cancelConfigEdit() { _configEditing.value = false }
fun saveConfigEdit() {
val baseline = _gatewayDescription.value ?: return
if (_configSaving.value) return
val descriptionChanged = _configDescriptionDraft.value != baseline.description
val modelChanged = _configProviderDraft.value != baseline.provider ||
_configModelDraft.value != baseline.model
if (modelChanged && (_configProviderDraft.value.isBlank() || _configModelDraft.value.isBlank())) {
_editEvents.tryEmit(EditEvent.Error("Provider and model are both required"))
return
}
val patch = GatewayProfilePatch(
description = _configDescriptionDraft.value.takeIf { descriptionChanged },
provider = _configProviderDraft.value.takeIf { modelChanged },
model = _configModelDraft.value.takeIf { modelChanged },
)
if (patch.requestedSections.isEmpty()) {
_configEditing.value = false
return
}
_configSaving.value = true
saveGatewayPatch(patch) { result, refreshed ->
if (GatewayProfileSection.Description in result.applied) {
_configDescriptionDraft.value = refreshed.description
}
if (GatewayProfileSection.Model in result.applied) {
_configProviderDraft.value = refreshed.provider
_configModelDraft.value = refreshed.model
}
_configEditing.value = result.failed.isNotEmpty()
_configSaving.value = false
}
}
private val _soulEditing = MutableStateFlow(false)
val soulEditing: StateFlow<Boolean> = _soulEditing.asStateFlow()
private val _soulDraft = MutableStateFlow("")
val soulDraft: StateFlow<String> = _soulDraft.asStateFlow()
private val _soulSaving = MutableStateFlow(false)
val soulSaving: StateFlow<Boolean> = _soulSaving.asStateFlow()
fun beginSoulEdit() {
val current = (soulState.value as? LoadState.Loaded)?.value?.content ?: ""
_soulDraft.value = current
_soulDraft.value = (soulState.value as? LoadState.Loaded)?.value?.content.orEmpty()
_soulEditing.value = true
}
fun updateSoulDraft(content: String) {
_soulDraft.value = content
}
fun cancelSoulEdit() {
_soulEditing.value = false
_soulDraft.value = ""
}
fun updateSoulDraft(content: String) { _soulDraft.value = content }
fun cancelSoulEdit() { _soulEditing.value = false }
fun saveSoulEdit() {
if (profileName.isBlank() || _soulSaving.value) return
val content = _soulDraft.value
_soulSaving.value = true
if (_source.value == ProfileInspectorSource.Gateway) {
saveGatewayPatch(GatewayProfilePatch(soul = _soulDraft.value)) { result, refreshed ->
if (GatewayProfileSection.Soul in result.applied) {
_soulDraft.value = refreshed.soul
_soulEditing.value = false
}
_soulSaving.value = false
}
return
}
viewModelScope.launch {
val result = client.updateSoul(profileName, content)
val result = legacyClient.updateSoul(profileName, _soulDraft.value)
_soulSaving.value = false
result.fold(
onSuccess = {
_soulEditing.value = false
_soulDraft.value = ""
_editEvents.tryEmit(EditEvent.Saved("SOUL saved"))
// Re-fetch the pane so the user sees freshly-loaded
// content (byte counts, truncation flags etc.).
refreshSection(InspectorSection.Soul)
},
onFailure = { err ->
_editEvents.tryEmit(
EditEvent.Error(err.message ?: "Save failed")
)
refreshLegacySection(InspectorSection.Soul)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Save failed")) },
)
}
}
// --- Memory edit state (keyed by filename) ------------------------
/**
* Filename of the memory entry currently being edited, or `null`
* when no memory entry is in edit mode. A single active edit at a
* time — matches the card-expansion model already in the pane.
*/
private val _memoryEditingFilename = MutableStateFlow<String?>(null)
val memoryEditingFilename: StateFlow<String?> = _memoryEditingFilename.asStateFlow()
private val _memoryDraft = MutableStateFlow("")
val memoryDraft: StateFlow<String> = _memoryDraft.asStateFlow()
private val _memorySaving = MutableStateFlow(false)
val memorySaving: StateFlow<Boolean> = _memorySaving.asStateFlow()
@@ -209,206 +189,290 @@ class ProfileInspectorViewModel(
_memoryEditingFilename.value = filename
_memoryDraft.value = initialContent
}
fun updateMemoryDraft(content: String) {
_memoryDraft.value = content
}
fun cancelMemoryEdit() {
_memoryEditingFilename.value = null
_memoryDraft.value = ""
}
fun updateMemoryDraft(content: String) { _memoryDraft.value = content }
fun cancelMemoryEdit() { _memoryEditingFilename.value = null }
fun saveMemoryEdit() {
val filename = _memoryEditingFilename.value ?: return
if (profileName.isBlank() || _memorySaving.value) return
val content = _memoryDraft.value
// Client-side filename sanity so we don't round-trip an obvious
// bad name and eat a 400. Server validates authoritatively.
val err = validateMemoryFilename(filename)
if (err != null) {
_editEvents.tryEmit(EditEvent.Error(err))
validateMemoryFilename(filename)?.let {
_editEvents.tryEmit(EditEvent.Error(it))
return
}
_memorySaving.value = true
viewModelScope.launch {
val result = client.updateMemoryEntry(profileName, filename, content)
val result = legacyClient.updateMemoryEntry(profileName, filename, _memoryDraft.value)
_memorySaving.value = false
result.fold(
onSuccess = {
_memoryEditingFilename.value = null
_memoryDraft.value = ""
_editEvents.tryEmit(EditEvent.Saved("Memory entry saved"))
refreshSection(InspectorSection.Memory)
},
onFailure = { e ->
_editEvents.tryEmit(
EditEvent.Error(e.message ?: "Save failed")
)
refreshLegacySection(InspectorSection.Memory)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Save failed")) },
)
}
}
// -----------------------------------------------------------------
// Skill toggle — server stubs this out as HTTP 501 today. We expose
// the probe result so the Skills pane can disable the Switch until
// the relay implements the endpoint, and we emit the 501 response
// as an EditEvent.Error on optimistic tap so the UI can revert
// the Switch visual state.
// -----------------------------------------------------------------
/**
* Capability flag. `null` = probe hasn't run yet (Switch renders
* enabled-but-pending); `true` = server claimed support on the
* capability probe; `false` = 501 / 404 / 405 — definitively not
* supported, Switch renders ghosted.
*/
private val _skillToggleSupported = MutableStateFlow<Boolean?>(null)
val skillToggleSupported: StateFlow<Boolean?> = _skillToggleSupported.asStateFlow()
private val _skillDrafts = MutableStateFlow<Map<String, Boolean>>(emptyMap())
val skillDrafts: StateFlow<Map<String, Boolean>> = _skillDrafts.asStateFlow()
private val _toolsetDrafts = MutableStateFlow<Map<String, Boolean>>(emptyMap())
val toolsetDrafts: StateFlow<Map<String, Boolean>> = _toolsetDrafts.asStateFlow()
private val _skillsSaving = MutableStateFlow(false)
val skillsSaving: StateFlow<Boolean> = _skillsSaving.asStateFlow()
/**
* One-shot capability probe. Fires at screen-open time from the
* Composable; idempotent — extra calls during the screen's lifetime
* reprobe but leave a positive result in place on failure.
*/
fun probeSkillToggleSupport() {
if (_source.value == ProfileInspectorSource.Gateway) {
_skillToggleSupported.value = true
return
}
viewModelScope.launch {
val supported = client.probeSkillToggleSupported()
_skillToggleSupported.value = supported
val supported = legacyClient.probeSkillToggleSupported()
if (_source.value != ProfileInspectorSource.Gateway) {
_skillToggleSupported.value = supported
}
}
}
/**
* Optimistic toggle — UI flips the switch immediately, then we PUT.
* On a 501 we emit an error event so the screen can revert the
* local visual state and cache "not supported" so subsequent taps
* are short-circuited.
*/
fun toggleSkill(skillName: String, enabled: Boolean) {
if (_source.value == ProfileInspectorSource.Gateway) {
val baseline = _gatewayDescription.value?.skills?.firstOrNull { it.name == skillName }
?.enabled ?: return
_skillDrafts.value = _skillDrafts.value.toMutableMap().apply {
if (enabled == baseline) remove(skillName) else put(skillName, enabled)
}
return
}
viewModelScope.launch {
val result = client.updateSkillToggle(skillName, enabled)
result.fold(
onSuccess = { outcome ->
when (outcome) {
is RelayProfileInspectorClient.SkillToggleResult.Ok ->
_editEvents.tryEmit(
EditEvent.Saved(
if (enabled) "Enabled $skillName" else "Disabled $skillName"
)
)
is RelayProfileInspectorClient.SkillToggleResult.NotImplemented -> {
legacyClient.updateSkillToggle(skillName, enabled).fold(
onSuccess = {
when (it) {
RelaySkillToggleResult.Ok -> {
_editEvents.tryEmit(EditEvent.Saved(if (enabled) "Enabled $skillName" else "Disabled $skillName"))
refreshLegacySection(InspectorSection.Skills)
}
RelaySkillToggleResult.NotImplemented -> {
_skillToggleSupported.value = false
_editEvents.tryEmit(
EditEvent.Error("Skill toggle not yet supported on this server")
)
_editEvents.tryEmit(EditEvent.Error("Skill toggle not yet supported on this server"))
}
}
},
onFailure = { err ->
_editEvents.tryEmit(
EditEvent.Error(err.message ?: "Skill toggle failed")
)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Skill toggle failed")) },
)
}
}
/**
* Local filename sanity for new/updated memory entries. Mirrors
* the rules the server worker enforces:
* - Must end in `.md`.
* - No path-traversal components (`..`).
* - No slashes/backslashes.
* - No leading `.` (dotfiles).
*
* Returns the error string to show, or null when the name passes.
* Running this client-side saves a server round-trip for the
* common typo cases and produces a tighter error ("filename must
* end in .md") than the server's generic 400.
*/
fun toggleToolset(toolsetName: String, enabled: Boolean) {
val baseline = _gatewayDescription.value?.toolsets?.firstOrNull { it.name == toolsetName }
?.enabled ?: return
_toolsetDrafts.value = _toolsetDrafts.value.toMutableMap().apply {
if (enabled == baseline) remove(toolsetName) else put(toolsetName, enabled)
}
}
fun saveSkillEdits() {
val description = _gatewayDescription.value ?: return
if (_source.value != ProfileInspectorSource.Gateway || _skillsSaving.value) return
val skillDrafts = _skillDrafts.value
val toolsetDrafts = _toolsetDrafts.value
val disabledSkills = if (skillDrafts.isNotEmpty()) {
description.skills.filter { !(skillDrafts[it.name] ?: it.enabled) }.map { it.name }
} else null
val enabledToolsets = if (toolsetDrafts.isNotEmpty()) {
description.toolsets.filter { toolsetDrafts[it.name] ?: it.enabled }.map { it.name }
.takeUnless { it.size == description.toolsets.size } ?: emptyList()
} else null
val patch = GatewayProfilePatch(
disabledSkills = disabledSkills,
enabledToolsets = enabledToolsets,
)
if (patch.requestedSections.isEmpty()) return
_skillsSaving.value = true
saveGatewayPatch(patch) { result, _ ->
if (GatewayProfileSection.Skills in result.applied) _skillDrafts.value = emptyMap()
if (GatewayProfileSection.Toolsets in result.applied) _toolsetDrafts.value = emptyMap()
_skillsSaving.value = false
}
}
fun validateMemoryFilename(name: String): String? {
val trimmed = name.trim()
if (trimmed.isEmpty()) return "Filename required"
if (!trimmed.endsWith(".md", ignoreCase = false)) {
return "Filename must end in .md"
}
if (!trimmed.endsWith(".md")) return "Filename must end in .md"
if (trimmed.startsWith(".")) return "Filename cannot start with '.'"
if (trimmed.contains("/") || trimmed.contains("\\")) {
return "Filename cannot contain slashes"
}
if (trimmed.contains("/") || trimmed.contains("\\")) return "Filename cannot contain slashes"
if (trimmed.contains("..")) return "Filename cannot contain '..'"
return null
}
/**
* Kick off all four fetches in parallel. Safe to call more than once
* — re-invoking replaces the load state from scratch (reverts any
* previous Error to Loading and re-tries).
*/
fun loadAll() {
if (profileName.isBlank()) {
val msg = "No profile name supplied"
_configState.value = LoadState.Error(msg)
_soulState.value = LoadState.Error(msg)
_memoryState.value = LoadState.Error(msg)
_skillsState.value = LoadState.Error(msg)
val error = LoadState.Error("No profile name supplied")
_configState.value = error
_soulState.value = error
_memoryState.value = error
_skillsState.value = error
return
}
refreshSection(InspectorSection.Config)
refreshSection(InspectorSection.Soul)
refreshSection(InspectorSection.Memory)
refreshSection(InspectorSection.Skills)
refreshEditorSections()
refreshLegacySection(InspectorSection.Memory)
}
/**
* Refresh a single section (pull-to-refresh on one pane). Transitions
* state to [LoadState.Loading] immediately so the UI can show a
* progress indicator; then fires the coroutine and updates the state
* with either [LoadState.Loaded] or [LoadState.Error].
*/
fun refreshSection(section: InspectorSection) {
if (profileName.isBlank()) return
if (section == InspectorSection.Memory) refreshLegacySection(section) else refreshEditorSections()
}
private fun refreshEditorSections() {
_configState.value = LoadState.Loading
_soulState.value = LoadState.Loading
_skillsState.value = LoadState.Loading
viewModelScope.launch {
val gatewayResult = gatewayClient?.describeProfile(profileName)
val gatewayDescription = gatewayResult?.getOrNull()
if (gatewayDescription != null) {
_source.value = ProfileInspectorSource.Gateway
applyGatewayDescription(gatewayDescription)
return@launch
}
loadLegacyEditorSections(gatewayResult?.exceptionOrNull())
}
}
private suspend fun loadLegacyEditorSections(gatewayError: Throwable?) = coroutineScope {
val config = async { legacyClient.fetchConfig(profileName) }
val soul = async { legacyClient.fetchSoul(profileName) }
val skills = async { legacyClient.fetchSkills(profileName) }
val configResult = config.await()
val soulResult = soul.await()
val skillsResult = skills.await()
if (configResult.isSuccess || soulResult.isSuccess || skillsResult.isSuccess) {
_source.value = ProfileInspectorSource.Relay
_gatewayDescription.value = null
}
val fallbackMessage = gatewayError
?.takeUnless { it is GatewayProfileEditorUnsupportedException }
?.message
_configState.value = configResult.toLoadState(fallbackMessage)
_soulState.value = soulResult.toLoadState(fallbackMessage)
_skillsState.value = skillsResult.toLoadState(fallbackMessage)
}
private fun refreshLegacySection(section: InspectorSection) {
when (section) {
InspectorSection.Config -> {
_configState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchConfig(profileName)
_configState.value = result.toLoadState()
}
}
InspectorSection.Soul -> {
_soulState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchSoul(profileName)
_soulState.value = result.toLoadState()
}
}
InspectorSection.Config, InspectorSection.Soul, InspectorSection.Skills -> refreshEditorSections()
InspectorSection.Memory -> {
_memoryState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchMemory(profileName)
_memoryState.value = result.toLoadState()
}
}
InspectorSection.Skills -> {
_skillsState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchSkills(profileName)
_skillsState.value = result.toLoadState()
_memoryState.value = legacyClient.fetchMemory(profileName).toLoadState()
}
}
}
}
private fun <T> Result<T>.toLoadState(): LoadState<T> = fold(
private fun applyGatewayDescription(description: GatewayProfileDescription) {
if (description.name != profileName) return
_gatewayDescription.value = description
_skillToggleSupported.value = true
_configState.value = LoadState.Loaded(description.toConfigResponse())
_soulState.value = LoadState.Loaded(description.toSoulResponse())
_skillsState.value = LoadState.Loaded(description.toSkillsResponse())
}
private fun saveGatewayPatch(
patch: GatewayProfilePatch,
afterAuthoritativeRefresh: (GatewayProfileConfigureResult, GatewayProfileDescription) -> Unit,
) {
val client = gatewayClient
if (client == null) {
_editEvents.tryEmit(EditEvent.Error("Gateway profile editor unavailable"))
return
}
viewModelScope.launch {
val configured = client.configureProfile(profileName, patch)
if (configured.isFailure) {
clearSavingFlags()
_editEvents.tryEmit(EditEvent.Error(configured.exceptionOrNull()?.message ?: "Save failed"))
return@launch
}
val result = configured.getOrThrow()
val refreshed = client.describeProfile(profileName)
if (refreshed.isFailure) {
clearSavingFlags()
_editEvents.tryEmit(EditEvent.Error(saveSummary(result) + "; authoritative refresh failed"))
return@launch
}
val description = refreshed.getOrThrow()
applyGatewayDescription(description)
afterAuthoritativeRefresh(result, description)
val summary = saveSummary(result)
if (result.applied.isEmpty()) _editEvents.tryEmit(EditEvent.Error(summary))
else _editEvents.tryEmit(EditEvent.Saved(summary))
}
}
private fun clearSavingFlags() {
_configSaving.value = false
_soulSaving.value = false
_skillsSaving.value = false
}
private fun saveSummary(result: GatewayProfileConfigureResult): String {
val applied = result.applied.joinToString { it.wireName }.ifBlank { "none" }
val failed = result.failed.joinToString { it.wireName }.ifBlank { "none" }
return "Applied: $applied; failed: $failed"
}
private fun GatewayProfileDescription.toConfigResponse(): ProfileConfigResponse =
ProfileConfigResponse(
profile = name,
path = "profiles.describe",
readonly = false,
config = buildJsonObject {
put("description", description)
put("model", buildJsonObject {
put("provider", provider)
put("default", model)
})
put("tools", buildJsonObject {
put("toolsets_pinned", toolsetsPinned)
put("enabled_toolsets", JsonArray(toolsets.filter { it.enabled }.map { kotlinx.serialization.json.JsonPrimitive(it.name) }))
})
},
)
private fun GatewayProfileDescription.toSoulResponse(): ProfileSoulResponse =
ProfileSoulResponse(
profile = name,
path = "profiles.describe",
content = soul,
exists = soul.isNotEmpty(),
sizeBytes = soul.toByteArray(Charsets.UTF_8).size.toLong(),
)
private fun GatewayProfileDescription.toSkillsResponse(): ProfileSkillsResponse =
ProfileSkillsResponse(
profile = name,
skills = skills.map {
ProfileSkillEntry(
name = it.name,
category = "Gateway",
description = "",
path = "",
enabled = it.enabled,
)
},
total = skills.size,
)
private fun <T> Result<T>.toLoadState(fallbackMessage: String? = null): LoadState<T> = fold(
onSuccess = { LoadState.Loaded(it) },
onFailure = { LoadState.Error(it.message ?: "Unknown error") },
onFailure = { LoadState.Error(it.message ?: fallbackMessage ?: "Unknown error") },
)
companion object {
/** Nav-arg key for the profile-name path segment. Matches the
* declaration in `Screen.ProfileInspector`. */
const val ARG_PROFILE_NAME: String = "profileName"
}
}
@@ -350,6 +350,38 @@ class ProfileController(
return dashboardClientFactory(connectionId, dashboardUrl).listAllProfileSessions(limit)
}
suspend fun deleteSession(profileName: String, sessionId: String): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.deleteSession(sessionId, profileName)
.isSuccess
}
suspend fun renameSession(profileName: String, sessionId: String, title: String): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.renameSession(sessionId, title, profileName)
.isSuccess
}
suspend fun setSessionPinned(profileName: String, sessionId: String, pinned: Boolean): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.setSessionPinned(sessionId, pinned, profileName)
.isSuccess
}
suspend fun setSessionArchived(profileName: String, sessionId: String, archived: Boolean): Boolean {
val connectionId = activeConnectionId.value ?: return false
val dashboardUrl = activeDashboardUrlProvider() ?: return false
return dashboardClientFactory(connectionId, dashboardUrl)
.setSessionArchived(sessionId, archived, profileName)
.isSuccess
}
/**
* A session's transcript, scoped to the active profile via the dashboard
* `/api/sessions/{id}/messages?profile=`. Returns `null` off the dashboard
@@ -358,10 +390,19 @@ class ProfileController(
suspend fun loadProfileScopedMessages(
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? = loadProfileScopedMessages(
profileName = resolveSessionProfileName(),
sessionId = sessionId,
mode = mode,
)
suspend fun loadProfileScopedMessages(
profileName: String?,
sessionId: String,
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
): Result<List<MessageItem>>? {
val connectionId = activeConnectionId.value ?: return null
val dashboardUrl = activeDashboardUrlProvider() ?: return null
val profileName = resolveSessionProfileName()
return dashboardClientFactory(connectionId, dashboardUrl)
.getSessionMessages(sessionId, profileName, mode)
}
@@ -583,6 +624,24 @@ class ProfileController(
}
}
/** Persist or clear a local cosmetic accent for a named profile. */
fun setProfileColor(profileName: String, colorHex: String?) {
val connectionId = activeConnectionId.value ?: return
val key = profileName.trim()
if (key.isBlank() || key.equals("default", ignoreCase = true)) return
scope.launch {
profilePresentationWriteMutex.withLock {
val updated = profilePresentationStore
.presentationFlow(connectionId)
.first()
.colors
.toMutableMap()
.apply { if (colorHex == null) remove(key) else put(key, colorHex) }
profilePresentationStore.setColors(connectionId, updated)
}
}
}
fun resetProfilePresentation() {
val connectionId = activeConnectionId.value ?: return
scope.launch {
@@ -16,6 +16,7 @@ import com.hermesandroid.relay.network.upstream.isNativeDashboardTransportEligib
import com.hermesandroid.relay.network.upstream.ServerCapabilities
import com.hermesandroid.relay.network.upstream.resolveStreamingEndpointPreference
import com.hermesandroid.relay.network.upstream.trustedDashboardBearerAuthOrNull
import com.hermesandroid.relay.network.shutdownOffMainThread
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -77,6 +78,13 @@ class UpstreamTransportController(
* `hermes_dashboard_<id>` file (original behavior).
*/
private val tokenStoreKeyProvider: (String) -> String? = { null },
/** Applies pairing-bound TLS to a standard authenticated client when needed. */
private val pinnedClientProvider: (String, okhttp3.OkHttpClient) -> okhttp3.OkHttpClient? =
{ _, _ -> null },
private val dashboardHttpClientFactory:
(DashboardCookieStore, DashboardBearerAuth?) -> okhttp3.OkHttpClient = { cookieStore, bearerAuth ->
DashboardApiClient.defaultClient(cookieStore, bearerAuth)
},
) {
// --- Per-connection dashboard cookie stores ----------------------------
@@ -147,30 +155,34 @@ class UpstreamTransportController(
* factory the dashboard-surface callers (profile lists, session/message
* scoping, the gateway client, standard-API setup probe) route through.
*/
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient =
DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = DashboardApiClient.defaultClient(
cookieStore = dashboardCookieStoreFor(connectionId),
bearerAuth = bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
),
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient {
val base = dashboardHttpClientFactory(
dashboardCookieStoreFor(connectionId),
bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
)
return DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
/**
* Build a [DashboardApiClient] for the active connection against
* [dashboardUrl], falling back to an in-memory cookie store when there is
* no active connection (the standard-voice probe path).
*/
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient =
DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let {
bearerAuthForTrustedDashboard(it, dashboardUrl)
},
),
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient {
val base = dashboardHttpClientFactory(
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
activeConnectionIdProvider()?.let {
bearerAuthForTrustedDashboard(it, dashboardUrl)
},
)
return DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
/**
* Native PKCE client for the active connection's exact trusted dashboard
@@ -190,9 +202,16 @@ class UpstreamTransportController(
) {
return null
}
val base = okhttp3.OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
return NativeDashboardAuthClient(
baseUrl = dashboardUrl,
tokenStore = dashboardTokenStoreFor(connectionId),
client = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
@@ -205,12 +224,14 @@ class UpstreamTransportController(
disposeDashboardHttpClient(client)
dashboardHttpClientCache = null
}
return DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let { activeId ->
val base = dashboardHttpClientFactory(
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
activeConnectionIdProvider()?.let { activeId ->
bearerAuthForTrustedDashboard(activeId, dashboardUrl)
},
).also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
)
return (pinnedClientProvider(dashboardUrl, base) ?: base)
.also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
}
@Synchronized
@@ -234,10 +255,12 @@ class UpstreamTransportController(
}
private fun disposeDashboardHttpClient(client: okhttp3.OkHttpClient) {
client.dispatcher.cancelAll()
client.connectionPool.evictAll()
runCatching { client.cache?.close() }
client.dispatcher.executorService.shutdown()
shutdownOffMainThread("DashboardHttpClient-shutdown") {
client.dispatcher.cancelAll()
client.connectionPool.evictAll()
runCatching { client.cache?.close() }
client.dispatcher.executorService.shutdown()
}
}
// --- Gateway availability ----------------------------------------------
@@ -3884,5 +3884,59 @@
<string name="dashboard_whatsapp_saved">WhatsApp ativado; o Hermes iniciou a reinicialização do gateway.</string>
<string name="drawer_all_profiles">Todos os perfis</string>
<string name="drawer_no_profile_sessions">Nenhuma sessão de perfil correspondente.</string>
<string name="drawer_customize_sessions">Personalizar sessões</string>
<string name="drawer_group_by">Agrupar por</string>
<string name="drawer_order_by">Ordenar por</string>
<string name="drawer_show_metadata">Mostrar nas linhas</string>
<string name="drawer_show_details">Mostrar detalhes</string>
<string name="drawer_filters">Filtros</string>
<string name="drawer_project_home">Início</string>
<string name="drawer_expand_project">Expandir %1$s</string>
<string name="drawer_collapse_project">Recolher %1$s</string>
<plurals name="drawer_project_session_count">
<item quantity="one">%1$d sessão</item>
<item quantity="other">%1$d sessões</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="one">%1$d perfil</item>
<item quantity="other">%1$d perfis</item>
</plurals>
<string name="drawer_filter_status">Status</string>
<string name="drawer_filter_profile">Perfil</string>
<string name="drawer_filter_project">Projeto</string>
<string name="drawer_filter_pull_request">Pull request</string>
<string name="drawer_option_updated">Atualizado</string>
<string name="drawer_option_profile">Perfil</string>
<string name="drawer_option_tokens">Tokens</string>
<string name="drawer_option_cost">Custo</string>
<string name="drawer_reset_filters">Redefinir</string>
<string name="drawer_profile_colors">Cores dos perfis</string>
<string name="drawer_profile_color_auto">Automática</string>
<string name="drawer_profile_color_set">Definir a cor do perfil %1$s como %2$s</string>
<string name="drawer_close">Fechar</string>
<string name="profile_inspector_gateway_settings">Configurações do perfil do Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Salvo diretamente pelo Hermes para este perfil selecionado.</string>
<string name="profile_inspector_edit_config">Editar configurações do perfil</string>
<string name="profile_inspector_description">Descrição</string>
<string name="profile_inspector_provider">Provedor</string>
<string name="profile_inspector_model">Modelo</string>
<string name="profile_inspector_save_changes">Salvar alterações</string>
<string name="profile_inspector_toolsets">Conjuntos de ferramentas</string>
<string name="profile_inspector_toolsets_hint">Escolha quais grupos de ferramentas do Hermes este perfil pode usar.</string>
<string name="profile_inspector_tool_count">%1$d ferramentas</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Rota de broker experimental para redes onde o acesso direto e o Tailscale não estão disponíveis. Ela ainda não é recomendada para a configuração normal; o TLS do Secure Link continua protegido de ponta a ponta.</string>
<string name="secure_link_pinned_tls">TLS fixado · identidade verificada por este pareamento</string>
<string name="secure_link_pinned_tls_short">Secure Link · TLS fixado</string>
<string name="secure_link_protects">Serviços protegidos: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Painel</string>
<string name="secure_link_no_services">Nenhum serviço protegido foi anunciado. O Secure Link não será usado.</string>
<string name="secure_link_partial_warning">Proteção parcial: os serviços não listados aqui usam sua própria rota e segurança configuradas.</string>
<string name="secure_link_partial_short">Secure Link · parcial</string>
<string name="secure_link_fallback_ready">Se o Secure Link não estiver disponível, o Hermes poderá tentar as rotas alternativas aprovadas abaixo.</string>
<string name="secure_link_no_fallback">Nenhuma rota alternativa está incluída. Os serviços protegidos permanecerão offline se o Secure Link não estiver disponível.</string>
<string name="secure_link_auth_note">A proteção do transporte não ignora a autenticação. O pareamento do Relay, as credenciais da API e o login no Painel continuam sendo exigidos por serviço.</string>
</resources>
@@ -3972,5 +3972,57 @@
<string name="dashboard_whatsapp_saved">WhatsApp 已启用;Hermes 已开始重启网关。</string>
<string name="drawer_all_profiles">所有配置文件</string>
<string name="drawer_no_profile_sessions">没有匹配的配置文件会话。</string>
<string name="drawer_customize_sessions">自定义会话</string>
<string name="drawer_group_by">分组方式</string>
<string name="drawer_order_by">排序方式</string>
<string name="drawer_show_metadata">在行中显示</string>
<string name="drawer_show_details">显示详细信息</string>
<string name="drawer_filters">筛选器</string>
<string name="drawer_project_home">主页</string>
<string name="drawer_expand_project">展开%1$s</string>
<string name="drawer_collapse_project">折叠%1$s</string>
<plurals name="drawer_project_session_count">
<item quantity="other">%1$d 个会话</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="other">%1$d 个配置文件</item>
</plurals>
<string name="drawer_filter_status">状态</string>
<string name="drawer_filter_profile">配置文件</string>
<string name="drawer_filter_project">项目</string>
<string name="drawer_filter_pull_request">拉取请求</string>
<string name="drawer_option_updated">更新时间</string>
<string name="drawer_option_profile">配置文件</string>
<string name="drawer_option_tokens">令牌</string>
<string name="drawer_option_cost">费用</string>
<string name="drawer_reset_filters">重置</string>
<string name="drawer_profile_colors">配置文件颜色</string>
<string name="drawer_profile_color_auto">自动</string>
<string name="drawer_profile_color_set">将 %1$s 配置文件颜色设为 %2$s</string>
<string name="drawer_close">关闭</string>
<string name="profile_inspector_gateway_settings">Gateway 配置文件设置</string>
<string name="profile_inspector_gateway_settings_hint">通过 Hermes 直接保存到当前所选配置文件。</string>
<string name="profile_inspector_edit_config">编辑配置文件设置</string>
<string name="profile_inspector_description">说明</string>
<string name="profile_inspector_provider">提供商</string>
<string name="profile_inspector_model">模型</string>
<string name="profile_inspector_save_changes">保存更改</string>
<string name="profile_inspector_toolsets">工具集</string>
<string name="profile_inspector_toolsets_hint">选择此配置文件可以使用的 Hermes 工具组。</string>
<string name="profile_inspector_tool_count">%1$d 个工具</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · 实验性</string>
<string name="hermes_reach_summary">用于无法直接访问且无法使用 Tailscale 的网络的实验性代理路由。目前不建议用于常规设置;Secure Link TLS 仍保持端到端保护。</string>
<string name="secure_link_pinned_tls">固定 TLS · 已通过此次配对验证身份</string>
<string name="secure_link_pinned_tls_short">Secure Link · 固定 TLS</string>
<string name="secure_link_protects">受保护的服务:%1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">控制面板</string>
<string name="secure_link_no_services">未公布任何受保护的服务。不会使用 Secure Link。</string>
<string name="secure_link_partial_warning">部分保护:未在此列出的服务将使用各自配置的路由和安全设置。</string>
<string name="secure_link_partial_short">Secure Link · 部分</string>
<string name="secure_link_fallback_ready">如果 Secure Link 不可用,Hermes 可以尝试下面已批准的备用路由。</string>
<string name="secure_link_no_fallback">未包含备用路由。如果 Secure Link 不可用,受保护的服务将保持离线。</string>
<string name="secure_link_auth_note">传输保护不会绕过身份验证。Relay 配对、API 凭据和控制面板登录仍会按服务分别强制执行。</string>
</resources>
+54
View File
@@ -4044,5 +4044,59 @@
<string name="dashboard_whatsapp_saved">WhatsApp aktiviert; Hermes hat einen Gateway-Neustart gestartet.</string>
<string name="drawer_all_profiles">Alle Profile</string>
<string name="drawer_no_profile_sessions">Keine passenden Profilsitzungen.</string>
<string name="drawer_customize_sessions">Sitzungen anpassen</string>
<string name="drawer_group_by">Gruppieren nach</string>
<string name="drawer_order_by">Sortieren nach</string>
<string name="drawer_show_metadata">In Zeilen anzeigen</string>
<string name="drawer_show_details">Details anzeigen</string>
<string name="drawer_filters">Filter</string>
<string name="drawer_project_home">Startseite</string>
<string name="drawer_expand_project">%1$s erweitern</string>
<string name="drawer_collapse_project">%1$s reduzieren</string>
<plurals name="drawer_project_session_count">
<item quantity="one">%1$d Sitzung</item>
<item quantity="other">%1$d Sitzungen</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="one">%1$d Profil</item>
<item quantity="other">%1$d Profile</item>
</plurals>
<string name="drawer_filter_status">Status</string>
<string name="drawer_filter_profile">Profil</string>
<string name="drawer_filter_project">Projekt</string>
<string name="drawer_filter_pull_request">Pull Request</string>
<string name="drawer_option_updated">Aktualisiert</string>
<string name="drawer_option_profile">Profil</string>
<string name="drawer_option_tokens">Tokens</string>
<string name="drawer_option_cost">Kosten</string>
<string name="drawer_reset_filters">Zurücksetzen</string>
<string name="drawer_profile_colors">Profilfarben</string>
<string name="drawer_profile_color_auto">Automatisch</string>
<string name="drawer_profile_color_set">Profilfarbe von %1$s auf %2$s setzen</string>
<string name="drawer_close">Schließen</string>
<string name="profile_inspector_gateway_settings">Gateway-Profileinstellungen</string>
<string name="profile_inspector_gateway_settings_hint">Wird für dieses ausgewählte Profil direkt über Hermes gespeichert.</string>
<string name="profile_inspector_edit_config">Profileinstellungen bearbeiten</string>
<string name="profile_inspector_description">Beschreibung</string>
<string name="profile_inspector_provider">Anbieter</string>
<string name="profile_inspector_model">Modell</string>
<string name="profile_inspector_save_changes">Änderungen speichern</string>
<string name="profile_inspector_toolsets">Toolsets</string>
<string name="profile_inspector_toolsets_hint">Wähle aus, welche Hermes-Werkzeuggruppen dieses Profil verwenden darf.</string>
<string name="profile_inspector_tool_count">%1$d Werkzeuge</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimentell</string>
<string name="hermes_reach_summary">Experimentelle Broker-Route für Netzwerke, in denen direkter Zugriff und Tailscale nicht verfügbar sind. Für die normale Einrichtung wird sie noch nicht empfohlen; Secure-Link-TLS bleibt Ende-zu-Ende geschützt.</string>
<string name="secure_link_pinned_tls">Angeheftetes TLS · Identität aus dieser Kopplung bestätigt</string>
<string name="secure_link_pinned_tls_short">Secure Link · angeheftetes TLS</string>
<string name="secure_link_protects">Geschützte Dienste: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Dashboard</string>
<string name="secure_link_no_services">Es wurden keine geschützten Dienste angekündigt. Secure Link wird nicht verwendet.</string>
<string name="secure_link_partial_warning">Teilweiser Schutz: Nicht aufgeführte Dienste verwenden ihre eigene konfigurierte Route und Sicherheit.</string>
<string name="secure_link_partial_short">Secure Link · teilweise</string>
<string name="secure_link_fallback_ready">Wenn Secure Link nicht verfügbar ist, kann Hermes die genehmigten Ausweichrouten unten versuchen.</string>
<string name="secure_link_no_fallback">Keine Ausweichroute enthalten. Geschützte Dienste bleiben offline, wenn Secure Link nicht verfügbar ist.</string>
<string name="secure_link_auth_note">Transportschutz umgeht keine Authentifizierung. Relay-Kopplung, API-Zugangsdaten und Dashboard-Anmeldung werden weiterhin pro Dienst erzwungen.</string>
</resources>
+54
View File
@@ -3729,5 +3729,59 @@
<string name="dashboard_whatsapp_saved">WhatsApp activado; Hermes inició un reinicio del gateway.</string>
<string name="drawer_all_profiles">Todos los perfiles</string>
<string name="drawer_no_profile_sessions">No hay sesiones de perfil coincidentes.</string>
<string name="drawer_customize_sessions">Personalizar sesiones</string>
<string name="drawer_group_by">Agrupar por</string>
<string name="drawer_order_by">Ordenar por</string>
<string name="drawer_show_metadata">Mostrar en las filas</string>
<string name="drawer_show_details">Mostrar detalles</string>
<string name="drawer_filters">Filtros</string>
<string name="drawer_project_home">Inicio</string>
<string name="drawer_expand_project">Expandir %1$s</string>
<string name="drawer_collapse_project">Contraer %1$s</string>
<plurals name="drawer_project_session_count">
<item quantity="one">%1$d sesión</item>
<item quantity="other">%1$d sesiones</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="one">%1$d perfil</item>
<item quantity="other">%1$d perfiles</item>
</plurals>
<string name="drawer_filter_status">Estado</string>
<string name="drawer_filter_profile">Perfil</string>
<string name="drawer_filter_project">Proyecto</string>
<string name="drawer_filter_pull_request">Solicitud de incorporación</string>
<string name="drawer_option_updated">Actualizado</string>
<string name="drawer_option_profile">Perfil</string>
<string name="drawer_option_tokens">Tokens</string>
<string name="drawer_option_cost">Coste</string>
<string name="drawer_reset_filters">Restablecer</string>
<string name="drawer_profile_colors">Colores de perfil</string>
<string name="drawer_profile_color_auto">Automático</string>
<string name="drawer_profile_color_set">Establecer el color del perfil %1$s en %2$s</string>
<string name="drawer_close">Cerrar</string>
<string name="profile_inspector_gateway_settings">Ajustes del perfil de Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Se guarda directamente mediante Hermes para este perfil seleccionado.</string>
<string name="profile_inspector_edit_config">Editar ajustes del perfil</string>
<string name="profile_inspector_description">Descripción</string>
<string name="profile_inspector_provider">Proveedor</string>
<string name="profile_inspector_model">Modelo</string>
<string name="profile_inspector_save_changes">Guardar cambios</string>
<string name="profile_inspector_toolsets">Conjuntos de herramientas</string>
<string name="profile_inspector_toolsets_hint">Elige qué grupos de herramientas de Hermes puede usar este perfil.</string>
<string name="profile_inspector_tool_count">%1$d herramientas</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Ruta de intermediario experimental para redes donde no están disponibles el acceso directo ni Tailscale. Aún no se recomienda para la configuración normal; el TLS de Secure Link sigue protegido de extremo a extremo.</string>
<string name="secure_link_pinned_tls">TLS fijado · identidad verificada desde este emparejamiento</string>
<string name="secure_link_pinned_tls_short">Secure Link · TLS fijado</string>
<string name="secure_link_protects">Servicios protegidos: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Panel</string>
<string name="secure_link_no_services">No se anunciaron servicios protegidos. Secure Link no se utilizará.</string>
<string name="secure_link_partial_warning">Protección parcial: los servicios no incluidos aquí usan su propia ruta y seguridad configuradas.</string>
<string name="secure_link_partial_short">Secure Link · parcial</string>
<string name="secure_link_fallback_ready">Si Secure Link no está disponible, Hermes puede probar las rutas alternativas aprobadas que aparecen abajo.</string>
<string name="secure_link_no_fallback">No se incluye ninguna ruta alternativa. Los servicios protegidos permanecerán sin conexión si Secure Link no está disponible.</string>
<string name="secure_link_auth_note">La protección del transporte no omite la autenticación. El emparejamiento de Relay, las credenciales de API y el inicio de sesión del Panel se siguen aplicando por servicio.</string>
</resources>
+54
View File
@@ -4043,5 +4043,59 @@
<string name="dashboard_whatsapp_saved">WhatsApp を有効にしました。Hermes がゲートウェイの再起動を開始しました。</string>
<string name="drawer_all_profiles">すべてのプロファイル</string>
<string name="drawer_no_profile_sessions">一致するプロファイルセッションはありません。</string>
<string name="drawer_customize_sessions">セッションをカスタマイズ</string>
<string name="drawer_group_by">グループ化</string>
<string name="drawer_order_by">並び順</string>
<string name="drawer_show_metadata">行に表示</string>
<string name="drawer_show_details">詳細を表示</string>
<string name="drawer_filters">フィルター</string>
<string name="drawer_project_home">ホーム</string>
<string name="drawer_expand_project">%1$sを展開</string>
<string name="drawer_collapse_project">%1$sを折りたたむ</string>
<plurals name="drawer_project_session_count">
<item quantity="one">%1$d件のセッション</item>
<item quantity="other">%1$d件のセッション</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="one">%1$d件のプロファイル</item>
<item quantity="other">%1$d件のプロファイル</item>
</plurals>
<string name="drawer_filter_status">ステータス</string>
<string name="drawer_filter_profile">プロフィール</string>
<string name="drawer_filter_project">プロジェクト</string>
<string name="drawer_filter_pull_request">プルリクエスト</string>
<string name="drawer_option_updated">更新日時</string>
<string name="drawer_option_profile">プロフィール</string>
<string name="drawer_option_tokens">トークン</string>
<string name="drawer_option_cost">コスト</string>
<string name="drawer_reset_filters">リセット</string>
<string name="drawer_profile_colors">プロフィールの色</string>
<string name="drawer_profile_color_auto">自動</string>
<string name="drawer_profile_color_set">%1$s のプロフィール色を %2$s に設定</string>
<string name="drawer_close">閉じる</string>
<string name="profile_inspector_gateway_settings">Gateway プロファイル設定</string>
<string name="profile_inspector_gateway_settings_hint">選択中のプロファイルに Hermes 経由で直接保存します。</string>
<string name="profile_inspector_edit_config">プロファイル設定を編集</string>
<string name="profile_inspector_description">説明</string>
<string name="profile_inspector_provider">プロバイダー</string>
<string name="profile_inspector_model">モデル</string>
<string name="profile_inspector_save_changes">変更を保存</string>
<string name="profile_inspector_toolsets">ツールセット</string>
<string name="profile_inspector_toolsets_hint">このプロファイルで使用できる Hermes のツールグループを選択します。</string>
<string name="profile_inspector_tool_count">%1$d 個のツール</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · 試験機能</string>
<string name="hermes_reach_summary">直接アクセスと Tailscale を利用できないネットワーク向けの試験的なブローカールートです。通常の設定にはまだ推奨されません。Secure Link TLS は引き続きエンドツーエンドで保護されます。</string>
<string name="secure_link_pinned_tls">ピン留め TLS · このペアリングから ID を確認済み</string>
<string name="secure_link_pinned_tls_short">Secure Link · ピン留め TLS</string>
<string name="secure_link_protects">保護されるサービス: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">ダッシュボード</string>
<string name="secure_link_no_services">保護対象のサービスが通知されていません。Secure Link は使用されません。</string>
<string name="secure_link_partial_warning">一部のみ保護: ここにないサービスは、それぞれ設定されたルートとセキュリティを使用します。</string>
<string name="secure_link_partial_short">Secure Link · 一部</string>
<string name="secure_link_fallback_ready">Secure Link を利用できない場合、Hermes は以下の承認済み代替ルートを試行できます。</string>
<string name="secure_link_no_fallback">代替ルートは含まれていません。Secure Link を利用できない場合、保護対象サービスはオフラインのままです。</string>
<string name="secure_link_auth_note">トランスポート保護によって認証が省略されることはありません。Relay のペアリング、API 資格情報、ダッシュボードへのログインはサービスごとに引き続き適用されます。</string>
</resources>
+58
View File
@@ -3765,5 +3765,63 @@
<string name="dashboard_whatsapp_saved">WhatsApp включён; Hermes начал перезапуск шлюза.</string>
<string name="drawer_all_profiles">Все профили</string>
<string name="drawer_no_profile_sessions">Нет подходящих сеансов профиля.</string>
<string name="drawer_customize_sessions">Настроить сеансы</string>
<string name="drawer_group_by">Группировать по</string>
<string name="drawer_order_by">Сортировать по</string>
<string name="drawer_show_metadata">Показывать в строках</string>
<string name="drawer_show_details">Показывать подробности</string>
<string name="drawer_filters">Фильтры</string>
<string name="drawer_project_home">Главная</string>
<string name="drawer_expand_project">Развернуть %1$s</string>
<string name="drawer_collapse_project">Свернуть %1$s</string>
<plurals name="drawer_project_session_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>
<plurals name="drawer_profile_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="drawer_filter_status">Статус</string>
<string name="drawer_filter_profile">Профиль</string>
<string name="drawer_filter_project">Проект</string>
<string name="drawer_filter_pull_request">Запрос на слияние</string>
<string name="drawer_option_updated">Обновлено</string>
<string name="drawer_option_profile">Профиль</string>
<string name="drawer_option_tokens">Токены</string>
<string name="drawer_option_cost">Стоимость</string>
<string name="drawer_reset_filters">Сбросить</string>
<string name="drawer_profile_colors">Цвета профилей</string>
<string name="drawer_profile_color_auto">Автоматически</string>
<string name="drawer_profile_color_set">Установить цвет профиля %1$s: %2$s</string>
<string name="drawer_close">Закрыть</string>
<string name="profile_inspector_gateway_settings">Настройки профиля Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Сохраняются напрямую через Hermes для выбранного профиля.</string>
<string name="profile_inspector_edit_config">Изменить настройки профиля</string>
<string name="profile_inspector_description">Описание</string>
<string name="profile_inspector_provider">Провайдер</string>
<string name="profile_inspector_model">Модель</string>
<string name="profile_inspector_save_changes">Сохранить изменения</string>
<string name="profile_inspector_toolsets">Наборы инструментов</string>
<string name="profile_inspector_toolsets_hint">Выберите группы инструментов Hermes, доступные этому профилю.</string>
<string name="profile_inspector_tool_count">Инструментов: %1$d</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Экспериментально</string>
<string name="hermes_reach_summary">Экспериментальный маршрут через брокер для сетей, где недоступны прямое подключение и Tailscale. Он пока не рекомендуется для обычной настройки; TLS Secure Link остаётся защищённым из конца в конец.</string>
<string name="secure_link_pinned_tls">Закреплённый TLS · подлинность подтверждена этим сопряжением</string>
<string name="secure_link_pinned_tls_short">Secure Link · закреплённый TLS</string>
<string name="secure_link_protects">Защищённые сервисы: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Панель</string>
<string name="secure_link_no_services">Защищённые сервисы не объявлены. Secure Link использоваться не будет.</string>
<string name="secure_link_partial_warning">Частичная защита: не указанные здесь сервисы используют собственные настроенные маршруты и параметры безопасности.</string>
<string name="secure_link_partial_short">Secure Link · частично</string>
<string name="secure_link_fallback_ready">Если Secure Link недоступен, Hermes может попробовать одобренные резервные маршруты ниже.</string>
<string name="secure_link_no_fallback">Резервный маршрут не указан. Защищённые сервисы останутся офлайн, если Secure Link недоступен.</string>
<string name="secure_link_auth_note">Защита транспорта не отменяет аутентификацию. Сопряжение Relay, учётные данные API и вход в Панель по-прежнему проверяются отдельно для каждого сервиса.</string>
</resources>
+55 -1
View File
@@ -455,6 +455,21 @@
<string name="cw_step_connect">3. Then come back and tap Connect</string>
<string name="cw_routes_count">Routes (%1$d)</string>
<string name="cw_routes_desc">Your phone tries these routes in order and uses the first one it can reach. It switches automatically as you change networks.</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Experimental broker route for networks where direct access and Tailscale are unavailable. It is not recommended for normal setup yet; Secure Link TLS remains end to end.</string>
<string name="secure_link_pinned_tls">Pinned TLS · identity verified from this pairing</string>
<string name="secure_link_pinned_tls_short">Secure Link · pinned TLS</string>
<string name="secure_link_protects">Protected services: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Dashboard</string>
<string name="secure_link_no_services">No protected services were advertised. Secure Link will not be used.</string>
<string name="secure_link_partial_warning">Partial protection: services not listed here use their own configured route and security.</string>
<string name="secure_link_partial_short">Secure Link · partial</string>
<string name="secure_link_fallback_ready">If Secure Link is unavailable, Hermes can try the approved fallback routes below.</string>
<string name="secure_link_no_fallback">No fallback route is included. Protected services will remain offline if Secure Link is unavailable.</string>
<string name="secure_link_auth_note">Transport protection does not bypass authentication. Relay pairing, API credentials, and Dashboard sign-in are still enforced per service.</string>
<string name="cw_prefer_label">Prefer:</string>
<string name="cw_natural_order">Natural order</string>
<string name="cw_keep_pairing_for">Keep this pairing for…</string>
@@ -4048,7 +4063,46 @@
<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>
<string name="drawer_all_profiles">All profiles</string>
<string name="drawer_all_profiles">All Profiles</string>
<string name="drawer_no_profile_sessions">No matching profile sessions.</string>
<string name="drawer_customize_sessions">Customize sessions</string>
<string name="drawer_group_by">Group by</string>
<string name="drawer_order_by">Order by</string>
<string name="drawer_show_metadata">Show on rows</string>
<string name="drawer_show_details">Show details</string>
<string name="drawer_filters">Filters</string>
<string name="drawer_project_home">Home</string>
<string name="drawer_expand_project">Expand %1$s</string>
<string name="drawer_collapse_project">Collapse %1$s</string>
<plurals name="drawer_project_session_count">
<item quantity="one">%1$d session</item>
<item quantity="other">%1$d sessions</item>
</plurals>
<plurals name="drawer_profile_count">
<item quantity="one">%1$d profile</item>
<item quantity="other">%1$d profiles</item>
</plurals>
<string name="drawer_filter_status">Status</string>
<string name="drawer_filter_profile">Profile</string>
<string name="drawer_filter_project">Project</string>
<string name="drawer_filter_pull_request">Pull request</string>
<string name="drawer_option_updated">Updated</string>
<string name="drawer_option_profile">Profile</string>
<string name="drawer_option_tokens">Tokens</string>
<string name="drawer_option_cost">Cost</string>
<string name="drawer_reset_filters">Reset</string>
<string name="drawer_profile_colors">Profile colors</string>
<string name="drawer_profile_color_auto">Auto</string>
<string name="drawer_profile_color_set">Set %1$s profile color to %2$s</string>
<string name="drawer_close">Close</string>
<string name="profile_inspector_gateway_settings">Gateway profile settings</string>
<string name="profile_inspector_gateway_settings_hint">Saved directly through upstream Hermes for this selected profile.</string>
<string name="profile_inspector_edit_config">Edit profile settings</string>
<string name="profile_inspector_description">Description</string>
<string name="profile_inspector_provider">Provider</string>
<string name="profile_inspector_model">Model</string>
<string name="profile_inspector_save_changes">Save changes</string>
<string name="profile_inspector_toolsets">Toolsets</string>
<string name="profile_inspector_toolsets_hint">Choose which upstream tool groups this profile can use.</string>
<string name="profile_inspector_tool_count">%1$d tools</string>
</resources>
@@ -12,6 +12,18 @@ import org.junit.Test
*/
class ChatMessageTest {
@Test
fun messageReaction_replacesAndRetractsTheUsersTapback() {
val agent = MessageReaction("🔥", "agent", 1.0)
val heart = applyMessageReaction(listOf(agent), "❤️", at = 2.0)
assertEquals(listOf(agent, MessageReaction("❤️", "user", 2.0)), heart)
val replaced = applyMessageReaction(heart, "😂", at = 3.0)
assertEquals(listOf(agent, MessageReaction("😂", "user", 3.0)), replaced)
assertEquals(listOf(agent), applyMessageReaction(replaced, "😂", at = 4.0))
}
// --- ChatMessage creation with defaults ---
@Test
@@ -117,4 +117,54 @@ class ConnectionSecurityTest {
assertEquals(ConnectionSecurityLevel.Overlay, result.level)
assertEquals("Tailscale", result.mechanism)
}
@Test
fun relayOnlySecureLink_withPlainStandardServices_isMixed() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val secureLink = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay"),
),
security = "pinned_tls",
)
val result = computeConnectionSecurity(
apiUrl = "http://192.168.1.10:8642",
dashboardUrl = "http://192.168.1.10:9119",
relayUrl = "wss://relay.example:9443/relay/ws",
relayConfigured = true,
activeEndpoint = secureLink,
isTailscaleDetected = false,
)
assertEquals(ConnectionSecurityLevel.Mixed, result.level)
assertEquals(false, result.isEncrypted)
assertEquals(listOf("Plain", "Plain", "Hermes Secure Link"), result.surfaces.map { it.mechanism })
}
@Test
fun completeSecureLink_classifiesEachExactProxyNamespace() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val secureLink = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
security = "pinned_tls",
)
val result = computeConnectionSecurity(
apiUrl = "https://relay.example:9443/api",
dashboardUrl = "https://relay.example:9443/dashboard",
relayUrl = "wss://relay.example:9443/relay/ws",
relayConfigured = true,
activeEndpoint = secureLink,
isTailscaleDetected = false,
)
assertEquals(ConnectionSecurityLevel.Tls, result.level)
assertEquals(true, result.isEncrypted)
assertEquals(setOf("Hermes Secure Link"), result.surfaces.map { it.mechanism }.toSet())
}
}
@@ -0,0 +1,34 @@
package com.hermesandroid.relay.data
import org.junit.Assert.assertEquals
import org.junit.Test
class GatewayProfileEditorModelsTest {
@Test
fun `patch distinguishes omitted sections from empty replace lists`() {
val patch = GatewayProfilePatch(
soul = "",
disabledSkills = emptyList(),
enabledToolsets = emptyList(),
)
assertEquals(
setOf(
GatewayProfileSection.Soul,
GatewayProfileSection.Skills,
GatewayProfileSection.Toolsets,
),
patch.requestedSections,
)
}
@Test
fun `configure result treats every requested non-applied section as failed`() {
val result = GatewayProfileConfigureResult(
requested = setOf(GatewayProfileSection.Description, GatewayProfileSection.Model),
applied = setOf(GatewayProfileSection.Description),
)
assertEquals(setOf(GatewayProfileSection.Model), result.failed)
}
}
@@ -25,9 +25,14 @@ class ProfilePresentationStoreTest {
fun orderAndHiddenProfilesRoundTripPerConnection() = runBlocking {
store.setOrder("one", listOf("beta", "alpha"))
store.setHidden("one", setOf("gamma"))
store.setColors("one", mapOf("alpha" to "#356CFF"))
assertEquals(
ProfilePresentation(order = listOf("beta", "alpha"), hidden = setOf("gamma")),
ProfilePresentation(
order = listOf("beta", "alpha"),
hidden = setOf("gamma"),
colors = mapOf("alpha" to "#356CFF"),
),
store.presentationFlow("one").first(),
)
assertEquals(ProfilePresentation(), store.presentationFlow("two").first())
@@ -104,6 +109,7 @@ class ProfilePresentationStoreTest {
fun clearRemovesOnlyOneConnectionsPreferences() = runBlocking {
store.setOrder("one", listOf("beta"))
store.setHidden("one", setOf("alpha"))
store.setColors("one", mapOf("beta" to "#ED4E8B"))
store.setOrder("two", listOf("gamma"))
store.clear("one")
@@ -0,0 +1,52 @@
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 SecureLinkPresentationTest {
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun `wire role is presented as Hermes Secure Link`() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint("https://relay.example:9443", pinSha256 = pin),
security = "pinned_tls",
)
assertEquals("plugin_proxy", candidate.role)
assertEquals("pinned_tls", candidate.security)
assertEquals("Hermes Secure Link", candidate.displayLabel())
assertEquals("https://relay.example:9443", candidate.presentationRouteUrl())
}
@Test
fun `service inventory is normalized and identifies partial protection`() {
val partial = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
"https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("Relay", "api", "relay", "unknown"),
),
)
assertEquals(listOf("relay", "api"), partial.secureLinkServices())
assertFalse(partial.secureLinkCoversAllServices())
val complete = partial.copy(
proxy = partial.proxy?.copy(surfaces = listOf("relay", "api", "dashboard")),
)
assertTrue(complete.secureLinkCoversAllServices())
}
@Test
fun `invalid pin cannot claim Secure Link protection`() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint("https://relay.example:9443", pinSha256 = "sha256/bad"),
)
assertFalse(candidate.hasSecureProxy())
assertTrue(candidate.secureLinkServices().isEmpty())
}
}
@@ -0,0 +1,130 @@
package com.hermesandroid.relay.network
import android.content.Context
import android.os.Looper
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
import com.hermesandroid.relay.network.relay.ConnectionManager
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.HermesApiClient
import com.hermesandroid.relay.viewmodel.connection.UpstreamTransportController
import io.mockk.mockk
import java.util.concurrent.AbstractExecutorService
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Owner-level coverage for every production ConnectionPool.evictAll() teardown. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class NetworkShutdownOwnerTest {
@Test
fun hermesApiClient_shutdownLeavesMainThread() {
val teardown = TrackingExecutorService()
val client = HermesApiClient(
baseUrl = "https://hermes.example.test",
apiKey = "test-key",
okHttpClient = clientWith(teardown),
)
client.shutdown()
teardown.assertShutdownOffMainThread()
}
@Test
fun dashboardApiClient_shutdownLeavesMainThread() {
val teardown = TrackingExecutorService()
val client = DashboardApiClient(
baseUrl = "https://hermes.example.test",
okHttpClient = clientWith(teardown),
)
client.shutdown()
teardown.assertShutdownOffMainThread()
}
@Test
fun connectionManager_shutdownLeavesMainThread() {
val teardown = TrackingExecutorService()
val manager = ConnectionManager(
multiplexer = ChannelMultiplexer(),
okHttpClientFactory = { clientWith(teardown) },
)
manager.shutdown()
teardown.assertShutdownOffMainThread()
}
@Test
fun upstreamTransportController_connectionSwitchResetLeavesMainThread() {
val dashboardUrl = "https://hermes.example.test"
val teardown = TrackingExecutorService()
val controller = UpstreamTransportController(
context = mockk<Context>(relaxed = true),
activeConnectionIdProvider = { null },
dashboardUrlProvider = { dashboardUrl },
gatewayKeepAliveProvider = { false },
dashboardHttpClientFactory = { _, _ -> clientWith(teardown) },
)
controller.dashboardHttpClientForActive(dashboardUrl)
controller.resetGatewayForConnectionSwitch()
teardown.assertShutdownOffMainThread()
}
private fun clientWith(executor: ExecutorService): OkHttpClient =
OkHttpClient.Builder()
.dispatcher(Dispatcher(executor))
.build()
private class TrackingExecutorService : AbstractExecutorService() {
private val shutdown = AtomicBoolean(false)
private val shutdownLatch = CountDownLatch(1)
private val shutdownThread = AtomicReference<Thread>()
override fun shutdown() {
shutdownThread.compareAndSet(null, Thread.currentThread())
shutdown.set(true)
shutdownLatch.countDown()
}
override fun shutdownNow(): MutableList<Runnable> {
shutdown()
return mutableListOf()
}
override fun isShutdown(): Boolean = shutdown.get()
override fun isTerminated(): Boolean = shutdown.get()
override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean =
shutdownLatch.await(timeout, unit)
override fun execute(command: Runnable) = command.run()
fun assertShutdownOffMainThread() {
assertSame(Looper.myLooper(), Looper.getMainLooper())
assertTrue("owner did not shut its OkHttp dispatcher down", shutdownLatch.await(5, TimeUnit.SECONDS))
assertNotSame(
"owner performed OkHttp teardown on the main thread",
Looper.getMainLooper().thread,
shutdownThread.get(),
)
}
}
}
@@ -4,6 +4,7 @@ import com.hermesandroid.relay.data.ApiEndpoint
import com.hermesandroid.relay.data.DashboardEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.RelayEndpoint
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import kotlinx.coroutines.test.runTest
@@ -83,6 +84,18 @@ class EndpointResolverTest {
assertEquals("lan", winner!!.role)
}
@Test
fun supportedRouteWins_overHigherPriorityExperimentalReach() = runTest {
val resolver = EndpointResolver(fastClient, clock = { clockMillis.get() })
val reach = candidate("outbound_broker", priority = 0, server = reachableServer)
.copy(experimental = true)
val tailscale = candidate("tailscale", priority = 1, server = secondReachableServer)
val winner = resolver.resolve(listOf(reach, tailscale))
assertEquals("tailscale", winner?.role)
}
// ---------------------------------------------------------------
// Test 2 — priority-0 unreachable → falls through to priority-1
// ---------------------------------------------------------------
@@ -431,6 +444,50 @@ class EndpointResolverTest {
assertEquals("/health", secondReachableServer.takeRequest(1, TimeUnit.SECONDS)?.path)
}
@Test
fun secureLinkStandardSurfacesProbeIndependently() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
)
val resolver = EndpointResolver(fastClient)
assertEquals(
"https://relay.example:9443/dashboard/api/status",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Dashboard),
)
assertEquals(
"https://relay.example:9443/api/health",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Api),
)
assertEquals(
"https://relay.example:9443/relay/health",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Relay),
)
}
@Test
fun secureLinkDoesNotProbeUnadvertisedStandardService() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
surfaces = listOf("relay"),
),
)
val resolver = EndpointResolver(fastClient)
assertNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Dashboard))
assertNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Api))
assertNotNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Relay))
}
@Test
fun apiHealthProbe_usesGetWhenServerRejectsHead() = runTest {
reachableServer.dispatcher = object : Dispatcher() {
@@ -0,0 +1,169 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.BrokerEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.isValidHermesReach
import com.hermesandroid.relay.data.replaceHermesReachCredential
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Base64
import java.io.IOException
class HermesReachTransportTest {
private val hostId = canonicalId(1)
private val streamId = canonicalId(2)
private val routeToken = canonicalToken(4)
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun routeRequiresWssKnownCredentialAndPinnedInnerSecureLink() {
val broker = BrokerEndpoint(
url = "wss://broker.example/v1/connect",
hostId = hostId,
credentialKind = "bootstrap",
token = routeToken,
)
assertTrue(broker.isValidHermesReach())
assertFalse(broker.copy(url = "ws://broker.example/v1/connect").isValidHermesReach())
assertFalse(broker.copy(credentialKind = "unknown").isValidHermesReach())
val missingInnerTrust = EndpointCandidate(role = "plugin_proxy", broker = broker)
assertFalse(missingInnerTrust.hasHermesReach())
assertNull(missingInnerTrust.hermesReachRouteOrNull())
}
@Test
fun registrationUsesCanonicalV1ShapeAndDoesNotExposeHermesCredentials() {
val route = HermesReachRoute(
brokerUrl = "wss://broker.example",
hostId = hostId,
credentialKind = "route",
token = routeToken,
)
val connectionId = canonicalId(3)
val payload = Json.parseToJsonElement(
HermesReachHandshake.registration(route, connectionId),
).jsonObject
assertEquals("register", payload.getValue("type").jsonPrimitive.content)
assertEquals("1", payload.getValue("protocol_version").jsonPrimitive.content)
assertEquals("client", payload.getValue("role").jsonPrimitive.content)
assertEquals(hostId, payload.getValue("host_id").jsonPrimitive.content)
assertEquals(connectionId, payload.getValue("connection_id").jsonPrimitive.content)
assertEquals("route", payload.getValue("credential_kind").jsonPrimitive.content)
assertEquals(routeToken, payload.getValue("token").jsonPrimitive.content)
assertEquals(setOf("type", "protocol_version", "role", "host_id", "connection_id", "credential_kind", "token"), payload.keys)
}
@Test
fun matchedResponseRequiresV1AndCanonical128BitStreamId() {
assertNull(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":1,"stream_id":"$streamId"}""",
))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":1,"stream_id":"short"}""",
)!!.contains("mismatched"))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":2,"stream_id":"$streamId"}""",
)!!.contains("mismatched"))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"error","code":"host_offline"}""",
)!!.contains("host_offline"))
}
@Test
fun reachPresentationStillRequiresPinnedSecureLink() {
val candidate = EndpointCandidate(
role = "outbound_broker",
proxy = ProxyEndpoint(
url = "https://paired-host.example:9443",
transportHint = "brokered_tls",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
broker = BrokerEndpoint(
url = "wss://broker.example/v1/connect",
hostId = hostId,
credentialKind = "bootstrap",
token = routeToken,
),
)
assertTrue(candidate.hasHermesReach())
assertEquals("Hermes Reach", candidate.displayLabel())
assertEquals("wss://broker.example/v1/connect", candidate.hermesReachRouteOrNull()?.tunnelUrlOrNull())
}
@Test
fun receiveQueueRejectsFrameFloodAndTracksPartialConsumption() {
val input = ReachInputStream()
repeat(REACH_MAX_QUEUED_FRAMES) {
assertTrue(input.offer(byteArrayOf(1, 2, 3)))
}
assertFalse(input.offer(byteArrayOf(4)))
val target = ByteArray(2)
assertEquals(2, input.read(target, 0, target.size))
// The first frame still occupies one frame slot until fully consumed.
assertFalse(input.offer(byteArrayOf(4)))
assertEquals(3, input.read())
assertTrue(input.offer(byteArrayOf(4)))
input.close(IOException("done"))
}
@Test
fun receiveQueueEnforcesAggregateByteLimit() {
val input = ReachInputStream()
repeat(REACH_MAX_QUEUED_BYTES / (1024 * 1024)) {
assertTrue(input.offer(ByteArray(1024 * 1024)))
}
assertFalse(input.offer(byteArrayOf(1)))
input.close(null)
}
@Test
fun durableCredentialRotationOnlyReplacesExactAuthorityAndHostLocator() {
fun candidate(host: String, hostId: String, token: String) = EndpointCandidate(
role = "outbound_broker",
security = "e2ee_pinned_tls",
proxy = ProxyEndpoint(
url = "https://paired-host.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
broker = BrokerEndpoint(
url = "wss://$host/v1/connect",
hostId = hostId,
credentialKind = "route",
token = token,
),
)
val expected = candidate("broker.example", hostId, routeToken)
val otherHost = candidate("broker.example", canonicalId(9), canonicalToken(9))
val otherAuthority = candidate("other.example", hostId, canonicalToken(8))
val replacement = expected.copy(
broker = expected.broker!!.copy(token = canonicalToken(7)),
)
val updated = replaceHermesReachCredential(
listOf(expected, otherHost, otherAuthority),
expected.broker!!,
replacement,
)
assertEquals(canonicalToken(7), updated[0].broker?.token)
assertEquals(otherHost, updated[1])
assertEquals(otherAuthority, updated[2])
}
private fun canonicalId(seed: Int): String = Base64.getUrlEncoder().withoutPadding()
.encodeToString(ByteArray(16) { (it + seed).toByte() })
private fun canonicalToken(seed: Int): String = Base64.getUrlEncoder().withoutPadding()
.encodeToString(ByteArray(32) { (it + seed).toByte() })
}
@@ -0,0 +1,51 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.ProxyEndpoint
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PluginProxyTransportTest {
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun `derives all proxy surfaces from one authority`() {
val routes = ProxyEndpoint(
"https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
)
.toPluginProxyRoutesOrNull()!!
assertEquals("relay.example:9443", routes.authority)
assertEquals("https://relay.example:9443/relay", routes.relayHttpUrl)
assertEquals("wss://relay.example:9443/relay/ws", routes.relayWebSocketUrl)
assertEquals("https://relay.example:9443/api", routes.apiBaseUrl)
assertEquals("https://relay.example:9443/dashboard", routes.dashboardBaseUrl)
}
@Test
fun `rejects incomplete or unsafe proxy advertisements`() {
val invalid = listOf(
ProxyEndpoint("http://relay.example:9443", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443", pinSha256 = null),
ProxyEndpoint("https://relay.example:9443", pinSha256 = "sha256/not-base64"),
ProxyEndpoint("https://user@relay.example:9443", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443?route=x", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a/../b", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a/%2e%2e/b", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a%2fb", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/secure", pinSha256 = pin),
)
assertTrue(invalid.all { it.toPluginProxyRoutesOrNull() == null })
}
@Test
fun `proxy pin remains scoped to advertised host and port`() {
val routes = ProxyEndpoint("https://relay.example:9443", pinSha256 = pin)
.toPluginProxyRoutesOrNull()!!
assertEquals("relay.example:9443", routes.authority)
assertNull(ProxyEndpoint("https://relay.example", pinSha256 = "sha256/")
.toPluginProxyRoutesOrNull())
}
}
@@ -950,6 +950,93 @@ class ChatHandlerTest {
assertEquals("Continued after an interrupted turn", msg.content)
}
@Test
fun loadMessageHistory_retainsDurableRowIdsWithoutUsingThemAsUiKeys() {
handler.loadMessageHistory(
listOf(
MessageItem(
id = "user-1",
rowId = 41L,
role = "user",
content = JsonPrimitive("First"),
),
MessageItem(
id = "assistant-1",
rowId = 42L,
role = "assistant",
content = JsonPrimitive("Reply"),
),
),
)
val user = handler.messages.value.first()
assertEquals(41L, user.rowId)
assertEquals("user-1", user.uiKey)
assertEquals(42L, handler.messages.value.last().rowId)
}
@Test
fun loadMessageHistory_hydratesPersistedReactionsAndLetsServerWin() {
fun metadata(emoji: String) = buildJsonObject {
put("reactions", buildJsonArray {
add(buildJsonObject {
put("emoji", emoji)
put("author", "user")
put("at", 1_700_000_000.0)
})
})
}
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-1",
rowId = 42L,
role = "assistant",
content = JsonPrimitive("Reply"),
displayMetadata = metadata("❤️"),
),
),
)
assertEquals("❤️", handler.messages.value.single().reactions.single().emoji)
handler.mutateMessage("assistant-1") { message ->
message.copy(reactions = listOf(com.hermesandroid.relay.data.MessageReaction("👍", "user", 2.0)))
}
handler.loadMessageHistory(
listOf(
MessageItem(
id = "assistant-1",
rowId = 42L,
role = "assistant",
content = JsonPrimitive("Reply"),
displayMetadata = metadata("😂"),
),
),
)
assertEquals("😂", handler.messages.value.single().reactions.single().emoji)
}
@Test
fun rebindSurvivorUserRowIds_replacesPrefixAndClearsUnboundTurns() {
handler.loadMessageHistory(
listOf(
MessageItem(id = "user-1", rowId = 41L, role = "user", content = JsonPrimitive("First")),
MessageItem(id = "assistant-1", rowId = 42L, role = "assistant", content = JsonPrimitive("Reply")),
MessageItem(id = "user-2", rowId = 43L, role = "user", content = JsonPrimitive("Second")),
),
)
handler.rebindSurvivorUserRowIds(listOf(101L))
val messages = handler.messages.value
assertEquals(101L, messages[0].rowId)
assertEquals(42L, messages[1].rowId)
assertNull(messages[2].rowId)
assertEquals(listOf("user-1", "assistant-1", "user-2"), messages.map { it.uiKey })
}
@Test
fun reconcileInterimMessage_collapsesProvisionalFinalBubble() {
handler.addPlaceholderMessage(
@@ -24,6 +24,36 @@ import java.io.IOException
class DashboardApiClientTest {
@Test
fun `multiplex API routing uses served profiles instead of installed inventory`() {
val status = DashboardStatus(
authRequired = true,
profiles = listOf("default", "research", "excluded"),
gatewayMode = "multiplex",
gateways = listOf(
DashboardGatewayTopology(
profile = "default",
servedProfiles = listOf("default", "research", "research", " "),
),
),
)
assertEquals(listOf("default", "research"), status.multiplexServedProfiles())
assertFalse("excluded" in status.multiplexServedProfiles())
}
@Test
fun `multiplex API routing fails closed without launch gateway served profiles`() {
val status = DashboardStatus(
authRequired = true,
profiles = listOf("default", "research"),
gatewayMode = "multiplex",
gateways = emptyList(),
)
assertTrue(status.multiplexServedProfiles().isEmpty())
}
private lateinit var server: MockWebServer
@Before
@@ -10,12 +10,15 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import okhttp3.OkHttpClient
import okhttp3.WebSocket
@@ -38,6 +41,7 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
/**
* [GatewayChatClient] wire tests against a scripted fake tui_gateway:
@@ -92,6 +96,9 @@ class GatewayClientHarness(
put("after_messages", 4)
}
@Volatile
var promptSubmitPayload: JsonObject = buildJsonObject { put("ok", true) }
@Volatile
var reasoningEffort = "medium"
@@ -117,6 +124,12 @@ class GatewayClientHarness(
put("dataUri", "data:image/png;base64,iVBORw0KGgo=")
}
@Volatile
var fileAttachPayload: JsonObject = buildJsonObject {
put("attached", true)
put("ref_text", "@file:notes.txt")
}
/** Methods answered with JSON-RPC -32601 — exercises the legacy-name fallback. */
val methodNotFound: MutableSet<String> = ConcurrentHashMap.newKeySet()
@@ -206,7 +219,7 @@ class GatewayClientHarness(
"session.activate" -> recoveryPayload(
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "live-activated",
)
"prompt.submit" -> buildJsonObject { put("ok", true) }
"prompt.submit" -> promptSubmitPayload
"session.interrupt" -> buildJsonObject { put("ok", true) }
"process.list" -> buildJsonObject {
put(
@@ -265,10 +278,7 @@ class GatewayClientHarness(
put("attached", true)
put("pages", 1)
}
"file.attach" -> buildJsonObject {
put("attached", true)
put("ref_text", "@file:notes.txt")
}
"file.attach" -> fileAttachPayload
"clarify.respond", "sudo.respond", "secret.respond" ->
buildJsonObject { put("status", askResponseStatus) }
"approval.respond" -> buildJsonObject { put("resolved", approvalResolved) }
@@ -278,6 +288,35 @@ class GatewayClientHarness(
json.parseToJsonElement("""[["/help","Show help"],["/model","Pick model"]]"""),
)
}
"profiles.describe" -> buildJsonObject {
put("name", (params["name"] as? JsonPrimitive)?.contentOrNull ?: "")
put("description", "Android operator")
put("soul", "# Operator")
put("model", buildJsonObject {
put("provider", "openai")
put("default", "gpt-5.6")
})
put("skills", JsonArray(listOf(buildJsonObject {
put("name", "weather")
put("enabled", false)
})))
put("toolsets", JsonArray(listOf(buildJsonObject {
put("name", "terminal")
put("description", "Run commands")
put("tool_count", 4)
put("enabled", true)
})))
put("toolsets_pinned", true)
}
"profiles.configure" -> buildJsonObject {
put("ok", false)
put("applied", buildJsonObject {
if (params.containsKey("description")) put("description", true)
if (params.containsKey("provider")) put("model", false)
if (params.containsKey("disabled_skills")) put("skills", true)
if (params.containsKey("enabled_toolsets")) put("toolsets", true)
})
}
"pet.thumb" -> petThumbPayload
"model.options" -> buildJsonObject {
put("model", "gpt-5.5")
@@ -627,6 +666,50 @@ class GatewayChatClientTest {
harness.shutdown()
}
@Test
fun `profile editor describes exact profile and maps upstream shape`() = runBlocking {
val description = client.describeProfile("operator").getOrThrow()
assertEquals("operator", description.name)
assertEquals("openai", description.provider)
assertEquals("gpt-5.6", description.model)
assertFalse(description.skills.single().enabled)
assertEquals(4, description.toolsets.single().toolCount)
assertTrue(description.toolsetsPinned)
assertEquals(
"operator",
(harness.awaitRpc("profiles.describe")["name"] as? JsonPrimitive)?.contentOrNull,
)
}
@Test
fun `profile configure is gated by describe and reports every requested section`() = runBlocking {
assertTrue(client.configureProfile("operator", com.hermesandroid.relay.data.GatewayProfilePatch(description = "x")).isFailure)
client.describeProfile("operator").getOrThrow()
val result = client.configureProfile(
"operator",
com.hermesandroid.relay.data.GatewayProfilePatch(
description = "Updated",
provider = "openai",
model = "gpt-5.6-sol",
),
).getOrThrow()
assertEquals(setOf(com.hermesandroid.relay.data.GatewayProfileSection.Description), result.applied)
assertEquals(setOf(com.hermesandroid.relay.data.GatewayProfileSection.Model), result.failed)
}
@Test
fun `profile describe method not found becomes sticky unsupported capability`() = runBlocking {
harness.methodNotFound += "profiles.describe"
assertTrue(client.describeProfile("operator").exceptionOrNull() is com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException)
harness.rpcLog.clear()
assertTrue(client.describeProfile("operator").exceptionOrNull() is com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException)
assertTrue(harness.rpcLog.none { it.first == "profiles.describe" })
}
@Test
fun `happy path - ticket, ready, create, submit, stream, complete`() {
val r = Recorder()
@@ -1418,6 +1501,27 @@ class GatewayChatClientTest {
assertEquals("legacy", result.status)
}
@Test
fun `compress session preserves authoritative lock contention message`() {
val r = Recorder()
client.sendTurn(null, "long job", null, r.callbacks) { r.preflightFailures += it }
harness.awaitServerSocket()
harness.awaitRpc("prompt.submit")
harness.compressPayload = buildJsonObject {
put("compressed", false)
put("lock_held", true)
put("message", "Compression skipped because another request holds the lock.")
}
val result = runBlocking { client.compressSession().getOrThrow() }
assertEquals("noop", result.status)
assertEquals(
"Compression skipped because another request holds the lock.",
result.output,
)
}
// --- Profile-bound sessions (upstream tui_gateway: session.create/resume
// take a `profile` arg; a session's agent is built from it) ---
@@ -1706,7 +1810,7 @@ class GatewayChatClientTest {
),
onPreflightFailure = { r.preflightFailures += it },
)
harness.awaitRpc("prompt.submit")
val submit = harness.awaitRpc("prompt.submit")
val attach = harness.awaitRpc("file.attach")
assertEquals("live-1", (attach["session_id"] as? JsonPrimitive)?.contentOrNull)
@@ -1715,11 +1819,67 @@ class GatewayChatClientTest {
(attach["data_url"] as? JsonPrimitive)?.contentOrNull,
)
assertEquals("notes.txt", (attach["name"] as? JsonPrimitive)?.contentOrNull)
assertEquals(
"@file:notes.txt\n\nread this",
(submit["text"] as? JsonPrimitive)?.contentOrNull,
)
assertTrue(harness.rpcLog.none { it.first == "image.attach_bytes" })
assertTrue(harness.rpcLog.none { it.first == "pdf.attach" })
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `queued document follow-up keeps its returned file reference on the queued prompt`() {
val r = Recorder()
client.sendTurn(
sessionId = null,
text = "compare the totals",
newSessionTitle = null,
callbacks = r.callbacks,
attachments = listOf(
GatewayAttachment(
name = "quarterly report.ods",
base64 = "UEsDBA==",
ext = "ods",
contentType = "application/vnd.oasis.opendocument.spreadsheet",
),
),
queuedFollowUp = true,
onPreflightFailure = { r.preflightFailures += it },
)
val submit = harness.awaitRpc("prompt.submit")
assertEquals(true, (submit["queued"] as? JsonPrimitive)?.booleanOrNull)
assertEquals(
"@file:notes.txt\n\ncompare the totals",
(submit["text"] as? JsonPrimitive)?.contentOrNull,
)
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `document upload without a readable reference fails before prompt submit`() {
harness.fileAttachPayload = buildJsonObject { put("attached", true) }
val r = Recorder()
client.sendTurn(
sessionId = null,
text = "read this",
newSessionTitle = null,
callbacks = r.callbacks,
attachments = listOf(
GatewayAttachment("notes.txt", "aGk=", "txt", "text/plain"),
),
onPreflightFailure = {
r.preflightFailures += it
r.completeLatch.countDown()
},
)
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
assertTrue(r.preflightFailures.single().contains("no readable file reference"))
assertTrue(harness.rpcLog.none { it.first == "prompt.submit" })
}
// --- Ask responders ---
@Test
@@ -1826,7 +1986,7 @@ class GatewayChatClientTest {
harness.awaitRpc("session.resume")
harness.awaitRpc("prompt.submit")
val result = runBlocking { client.reactToNewest("assistant", "👍") }
val result = runBlocking { client.reactToMessage(null, "assistant", "👍") }
assertTrue(result.isSuccess)
val params = harness.awaitRpc("message.react")
@@ -1837,6 +1997,20 @@ class GatewayChatClientTest {
assertFalse("row_id" in params)
}
@Test
fun `message reaction targets durable row when history provides it`() {
client.sendTurn("stored-1", "hi", null, Recorder().callbacks) {}
harness.awaitRpc("session.resume")
harness.awaitRpc("prompt.submit")
val result = runBlocking { client.reactToMessage(42L, "assistant", "❤️") }
assertTrue(result.isSuccess)
val params = harness.awaitRpc("message.react")
assertEquals(42L, (params["row_id"] as? JsonPrimitive)?.longOrNull)
assertFalse("newest_role" in params)
}
@Test
fun `pet thumbnail connects on demand and sends upstream params`() {
client.sessionProfileProvider = { "work" }
@@ -2199,6 +2373,41 @@ class GatewayChatClientTest {
assertFalse(submit.containsKey("confirm_empty_truncate"))
}
@Test
fun `durable rewind target and survivor row ids round trip`() {
harness.promptSubmitPayload = buildJsonObject {
put("ok", true)
put("survivor_user_row_ids", buildJsonArray {
add(JsonPrimitive(101L))
add(JsonNull)
add(JsonPrimitive("malformed"))
})
}
val r = Recorder()
val rebound = AtomicReference<List<Long?>>()
val reboundLatch = CountDownLatch(1)
client.sendTurn(
sessionId = "stored-1",
text = "edited message",
newSessionTitle = null,
callbacks = r.callbacks,
truncateBeforeUserOrdinal = 2,
truncateBeforeRowId = 73L,
onSurvivorUserRowIds = {
rebound.set(it)
reboundLatch.countDown()
},
onPreflightFailure = { r.preflightFailures += it },
)
val submit = harness.awaitRpc("prompt.submit")
assertEquals(2, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
assertEquals(73L, (submit["truncate_before_row_id"] as? JsonPrimitive)?.longOrNull)
assertTrue(reboundLatch.await(5, TimeUnit.SECONDS))
assertEquals(listOf(101L, null, null), rebound.get())
}
@Test
fun `first user truncate carries empty-history confirmation`() {
val r = Recorder()
@@ -2262,9 +2471,13 @@ class GatewayChatClientTest {
@Test
fun `authoritative prompt rejections surface server message without preflight fallback`() {
val cases = listOf(
4004 to "Truncation target must be an integer",
4018 to "Target user message is no longer in session history",
4028 to "Empty-history truncate confirmation required",
4029 to "Truncate confirmation required",
4030 to "Row id and ordinal identify different user turns",
4090 to "Active session limit reached; close the session held by another client",
5008 to "Failed to persist history truncation",
5070 to "Session storage is full; free disk space and retry",
5071 to "Initial session persistence failed",
)
@@ -2282,6 +2495,25 @@ class GatewayChatClientTest {
}
}
@Test
fun `bounded transcript resume rejection stays visible and never creates a replacement session`() {
val message =
"Session has 20,001 active messages, above sessions.max_resume_messages; export or raise the limit"
harness.rpcErrors["session.resume"] = 4130 to message
val r = Recorder()
client.sendTurn("oversized-session", "continue", null, r.callbacks) {
r.preflightFailures += it
}
harness.awaitRpc("session.resume")
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
assertEquals(listOf(message), r.errors.toList())
assertTrue(r.preflightFailures.isEmpty())
assertEquals(0, harness.rpcLog.count { it.first == "session.create" })
assertEquals(0, harness.rpcLog.count { it.first == "prompt.submit" })
}
// --- HRUI-016: long / fire-and-forget prompt.submit ack semantics.
// Upstream treats prompt.submit as a long-running RPC (desktop passes a
// 30-min PROMPT_SUBMIT_REQUEST_TIMEOUT_MS at every call site) because the
@@ -794,6 +794,32 @@ class GatewayEventMapperTest {
assertTrue(ask.smartDenied)
}
@Test
fun `approval request removes explicitly forbidden persistent scopes`() {
val r = Recorder()
mapperWith(r).onEvent(
"approval.request",
obj(
"""{"command":"<write to AGENTS.md>","choices":["once","session","always","deny"],"allow_session":false,"allow_permanent":false}""",
),
)
assertEquals(listOf("once", "deny"), r.interactions.single().choices)
}
@Test
fun `approval request retains session while permanent scope is forbidden`() {
val r = Recorder()
mapperWith(r).onEvent(
"approval.request",
obj(
"""{"command":"guarded command","choices":["once","session","always","deny"],"allow_session":true,"allow_permanent":false}""",
),
)
assertEquals(listOf("once", "session", "deny"), r.interactions.single().choices)
}
@Test
fun `tool output risk maps deterministic non-low metadata only`() {
val r = Recorder()
@@ -1,14 +1,17 @@
package com.hermesandroid.relay.network.upstream.models
import kotlinx.serialization.encodeToString
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
@@ -71,7 +74,10 @@ class SessionModelsTest {
"message_count": 5,
"tool_call_count": 2,
"input_tokens": 100,
"output_tokens": 200
"output_tokens": 200,
"actual_cost_usd": 1.25,
"estimated_cost_usd": 1.50,
"is_active": true
}
""".trimIndent()
@@ -82,6 +88,11 @@ class SessionModelsTest {
assertEquals(1700000900.0, item.resolvedLastActivity!!, 0.001)
assertEquals(5, item.messageCount)
assertEquals(2, item.toolCallCount)
assertEquals(100, item.inputTokens)
assertEquals(200, item.outputTokens)
assertEquals(1.25, item.actualCostUsd!!, 0.001)
assertEquals(1.50, item.estimatedCostUsd!!, 0.001)
assertTrue(item.isActive)
}
@Test
@@ -94,6 +105,42 @@ class SessionModelsTest {
assertTrue(item.archived)
}
@Test
fun sessionItem_deserializesNumericSessionFlags() {
val item = json.decodeFromString<SessionItem>(
"""{"id":"s1","has_model_config":1,"pinned":0,"archived":1}""",
)
assertTrue(item.hasModelConfig)
assertFalse(item.pinned)
assertTrue(item.archived)
}
@Test
fun sessionItem_deserializesStringBooleanSessionFlags() {
val item = json.decodeFromString<SessionItem>(
"""{"id":"s1","has_model_config":"false","pinned":"1","archived":"0"}""",
)
assertFalse(item.hasModelConfig)
assertTrue(item.pinned)
assertFalse(item.archived)
}
@Test
fun sessionItem_rejectsNonBooleanSessionFlagValues() {
assertThrows(SerializationException::class.java) {
json.decodeFromString<SessionItem>(
"""{"id":"s1","pinned":2}""",
)
}
assertThrows(SerializationException::class.java) {
json.decodeFromString<SessionItem>(
"""{"id":"s1","archived":"yes"}""",
)
}
}
@Test
fun sessionItem_deserializesOptionalWorkspaceMetadata() {
val item = json.decodeFromString<SessionItem>(
@@ -301,6 +348,46 @@ class SessionModelsTest {
assertNull(item.finishReason)
}
@Test
fun messageItem_rowIdIsMixedVersionSafe() {
assertEquals(
73L,
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":73}""",
).rowId,
)
assertEquals(
74L,
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":"74"}""",
).rowId,
)
assertNull(
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":{"unexpected":true}}""",
).rowId,
)
assertEquals(
75L,
json.decodeFromString<MessageItem>(
"""{"id":75,"role":"assistant"}""",
).resolvedRowId,
)
}
@Test
fun messageItem_readsReactionsFromObjectOrRawJsonMetadata() {
val objectBacked = json.decodeFromString<MessageItem>(
"""{"role":"assistant","display_metadata":{"reactions":[{"emoji":"👍","author":"user","at":1.0}]}}""",
)
val stringBacked = json.decodeFromString<MessageItem>(
"""{"role":"assistant","display_metadata":"{\"reactions\":[{\"emoji\":\"❤️\",\"author\":\"user\",\"at\":2.0}]}"}""",
)
assertEquals("👍", objectBacked.reactions.single().emoji)
assertEquals("❤️", stringBacked.reactions.single().emoji)
}
@Test
fun messageItem_roundTrip() {
val original = MessageItem(
@@ -17,6 +17,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.ChatMessage
import com.hermesandroid.relay.data.ChatQuoteReference
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.MessageReaction
import com.hermesandroid.relay.data.buildChatQuotedPrompt
import org.junit.Assert.assertEquals
import org.junit.Rule
@@ -117,6 +118,65 @@ class MessageBubbleInteractionTest {
compose.onNodeWithText("Quote in reply").assertIsDisplayed().assertHasClickAction()
}
@Test
fun reactionsStayOutsideBubbleAndOpenAsFloatingTapbacks() {
val reactions = mutableListOf<String?>()
val message = ChatMessage(
id = "assistant-reactions",
role = MessageRole.ASSISTANT,
content = "React to this response.",
timestamp = 1_700_000_000_000L,
)
compose.setContent {
MaterialTheme {
MessageBubble(
message = message,
onReact = { reactions += it },
)
}
}
compose.onNodeWithContentDescription("React with 👍").assertDoesNotExist()
compose.onNodeWithText("Remove reaction").assertDoesNotExist()
compose.onNodeWithContentDescription("assistant message: ${message.content}")
.performTouchInput { longClick() }
compose.onNodeWithContentDescription("React with 👍")
.assertIsDisplayed()
.assertHasClickAction()
.performClick()
compose.runOnIdle { assertEquals(listOf("👍"), reactions) }
compose.onNodeWithContentDescription("React with 👍").assertDoesNotExist()
}
@Test
fun landedReactionStaysPinnedToTheBubbleAndReopensPicker() {
val message = ChatMessage(
id = "assistant-landed-reaction",
role = MessageRole.ASSISTANT,
content = "A reacted response.",
timestamp = 1_700_000_000_000L,
reactions = listOf(MessageReaction("❤️", "user", 1_700_000_000.0)),
)
compose.setContent {
MaterialTheme {
MessageBubble(message = message, onReact = {})
}
}
compose.onNodeWithContentDescription("Reactions: ❤️")
.assertIsDisplayed()
.assertHasClickAction()
.performClick()
compose.onNodeWithContentDescription("React with ❤️").assertIsDisplayed()
compose.onNodeWithText("Remove reaction").assertIsDisplayed()
}
@Test
fun quotedReplyRendersStructuredReferenceAndKeepsMarkupOutOfActions() {
var quotedContent: String? = null
@@ -0,0 +1,135 @@
package com.hermesandroid.relay.ui.components
import com.hermesandroid.relay.data.ChatSession
import com.hermesandroid.relay.data.SessionActivityState
import org.junit.Assert.assertEquals
import org.junit.Test
class SessionDrawerPolicyTest {
@Test
fun `sessions are ungrouped by default`() {
assertEquals(SessionDrawerGrouping.None, SessionDrawerViewOptions().grouping)
}
@Test
fun `cross profile rows retain composite identity`() {
val alpha = row("alpha", "same")
val beta = row("beta", "same")
assertEquals("alpha:same", sessionRowKey(alpha))
assertEquals("beta:same", sessionRowKey(beta))
}
@Test
fun `profile project status and pull request filters compose`() {
val wanted = row(
profile = "work",
id = "wanted",
repo = "/src/hermes-relay",
prNumber = 347,
prState = "open",
)
val wrongProfile = row("personal", "other", repo = "/src/hermes-relay", prNumber = 22)
val wrongProject = row("work", "notes", repo = "/src/notes", prNumber = 23)
val states = mapOf(sessionRowKey(wanted) to SessionActivityState.NeedsInput)
val filtered = filterAndSortSessionRows(
rows = listOf(wrongProfile, wrongProject, wanted),
options = SessionDrawerViewOptions(
profiles = setOf("work"),
projects = setOf("hermes-relay"),
statuses = setOf(SessionDrawerStatus.NeedsInput),
pullRequests = setOf(SessionDrawerPrState.Open),
),
activityStates = states,
)
assertEquals(listOf("wanted"), filtered.map { it.session.sessionId })
}
@Test
fun `token and cost ordering use authoritative session metrics`() {
val small = row("default", "small", inputTokens = 10, outputTokens = 20, cost = 3.0)
val large = row("default", "large", inputTokens = 500, outputTokens = 600, cost = 1.0)
assertEquals(
listOf("large", "small"),
filterAndSortSessionRows(
listOf(small, large),
SessionDrawerViewOptions(ordering = SessionDrawerOrdering.Tokens),
).map { it.session.sessionId },
)
assertEquals(
listOf("small", "large"),
filterAndSortSessionRows(
listOf(small, large),
SessionDrawerViewOptions(ordering = SessionDrawerOrdering.Cost),
).map { it.session.sessionId },
)
}
@Test
fun `desktop style grouping supports project profile status and updated buckets`() {
val now = 10 * DAY
val working = row("work", "working", repo = "/src/hermes-relay", updatedAt = now - 1_000)
val idle = row("personal", "idle", repo = "/src/notes", updatedAt = now - 3 * DAY)
val states = mapOf(sessionRowKey(working) to SessionActivityState.Working)
assertEquals(
listOf("hermes-relay", "notes"),
groupSessionRows(listOf(working, idle), SessionDrawerGrouping.Project, states, now)
.mapNotNull { it.label },
)
assertEquals(
listOf("work", "personal"),
groupSessionRows(listOf(working, idle), SessionDrawerGrouping.Profile, states, now)
.mapNotNull { it.label },
)
assertEquals(
listOf("Working", "Idle"),
groupSessionRows(listOf(working, idle), SessionDrawerGrouping.Status, states, now)
.mapNotNull { it.label },
)
assertEquals(
listOf("Today", "Last 7 days"),
groupSessionRows(listOf(working, idle), SessionDrawerGrouping.Updated, states, now)
.mapNotNull { it.label },
)
assertEquals(
listOf(null),
groupSessionRows(listOf(working, idle), SessionDrawerGrouping.None, states, now)
.map { it.label },
)
}
private fun row(
profile: String,
id: String,
repo: String? = null,
prNumber: Int? = null,
prState: String? = null,
inputTokens: Int = 0,
outputTokens: Int = 0,
cost: Double? = null,
updatedAt: Long = 0L,
) = ProfileSessionRow(
profile = profile,
session = ChatSession(
sessionId = id,
title = id,
model = null,
gitRepoRoot = repo,
pullRequestNumber = prNumber,
pullRequestState = prState,
inputTokens = inputTokens,
outputTokens = outputTokens,
actualCostUsd = cost,
lastActivityAt = updatedAt,
),
)
private companion object {
const val DAY = 24L * 60L * 60L * 1_000L
}
}
@@ -8,10 +8,15 @@ import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
import androidx.compose.ui.test.performScrollToNode
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.ChatSession
import com.hermesandroid.relay.ui.theme.ProfileAccentSwatches
import org.junit.Rule
import org.junit.Test
import org.junit.Assert.assertEquals
@@ -66,6 +71,42 @@ class SessionDrawerTest {
listOf("hermes-relay", "feature/android-session-context", "PR #134 · Open"),
sessionWorkLabels(session),
)
assertEquals(
listOf(
SessionWorkBadgeKind.PROJECT,
SessionWorkBadgeKind.BRANCH,
SessionWorkBadgeKind.PULL_REQUEST,
),
sessionWorkBadges(session).map(SessionWorkBadge::kind),
)
}
@Test
fun `session rows identify project and branch badges`() {
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = listOf(
ChatSession(
sessionId = "coding-1",
title = "Ship it",
model = null,
gitRepoRoot = "/work/hermes-relay",
gitBranch = "feature/chat-polish",
),
),
currentSessionId = null,
onNewChat = {},
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("hermes-relay").assertIsDisplayed()
compose.onNodeWithContentDescription("Project: hermes-relay").assertIsDisplayed()
compose.onNodeWithContentDescription("Branch: feature/chat-polish").assertIsDisplayed()
}
@Test
@@ -120,4 +161,168 @@ class SessionDrawerTest {
compose.onNodeWithText("Now latest").assertIsDisplayed()
}
@Test
fun `all profiles toggle renders duplicate ids together in the primary list`() {
var pinned: Triple<String, String, Boolean>? = null
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = listOf(ChatSession("same", "Current", null)),
currentSessionId = null,
activeProfileName = "alpha",
allProfilesSupported = true,
allProfileSessions = listOf(
ProfileSessionRow("alpha", ChatSession("same", "Alpha session", null)),
ProfileSessionRow("beta", ChatSession("same", "Beta session", null)),
),
onRefreshAllProfiles = {},
onSelectProfileSession = { _, _ -> },
onSetProfileSessionPinned = { profile, sessionId, value ->
pinned = Triple(profile, sessionId, value)
},
onNewChat = {},
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("All Profiles").performClick()
compose.onNodeWithText("Alpha session").assertIsDisplayed()
compose.onNodeWithText("Beta session").assertIsDisplayed()
compose.onAllNodesWithContentDescription("Session actions")[0]
.assertIsDisplayed()
.performClick()
compose.onNodeWithText("Pin session").performClick()
compose.runOnIdle { assertEquals(Triple("alpha", "same", true), pinned) }
}
@Test
fun `opening an owned session keeps all profiles browsing selected`() {
var scopeTitle by mutableStateOf("Mizu Sessions")
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = emptyList(),
currentSessionId = null,
scopeTitle = scopeTitle,
activeProfileName = "mizu",
allProfilesSupported = true,
allProfileSessions = listOf(
ProfileSessionRow("mizu", ChatSession("m", "Mizu chat", null)),
ProfileSessionRow("x-bot", ChatSession("x", "X Bot chat", null)),
),
onRefreshAllProfiles = {},
onSelectProfileSession = { _, _ -> scopeTitle = "X Bot Sessions" },
onNewChat = {},
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("All Profiles").performClick()
compose.onNodeWithText("X Bot chat").performClick()
compose.onNodeWithText("Mizu chat").assertIsDisplayed()
compose.onNodeWithText("X Bot Sessions").assertDoesNotExist()
compose.onNodeWithText("2 profiles · 2 sessions").assertIsDisplayed()
}
@Test
fun `new chat from all profiles requests an explicit default draft`() {
var scopedNewChats = 0
var defaultNewChats = 0
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = emptyList(),
currentSessionId = null,
allProfilesSupported = true,
allProfileSessions = listOf(
ProfileSessionRow("default", ChatSession("d", "Default chat", null)),
),
onRefreshAllProfiles = {},
onSelectProfileSession = { _, _ -> },
onNewChat = { scopedNewChats++ },
onNewDefaultChat = { defaultNewChats++ },
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("All Profiles").performClick()
compose.waitForIdle()
compose.onNodeWithText("New Chat").performClick()
compose.runOnIdle {
assertEquals(0, scopedNewChats)
assertEquals(1, defaultNewChats)
}
}
@Test
fun `customize sessions exposes desktop backed view variants`() {
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = listOf(ChatSession("one", "One", null)),
currentSessionId = null,
onNewChat = {},
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("Customize sessions").performClick()
compose.onNodeWithText("Group by").assertIsDisplayed()
compose.onNodeWithText("Order by").assertIsDisplayed()
compose.onNodeWithText("Show details").assertIsDisplayed()
compose.onNodeWithText("Filters").assertIsDisplayed()
}
@Test
fun `all profiles customization can override a profile identity color`() {
var changed: Pair<String, String?>? = null
compose.setContent {
MaterialTheme {
SessionDrawerContent(
sessions = emptyList(),
currentSessionId = null,
allProfilesSupported = true,
allProfileSessions = listOf(
ProfileSessionRow("alpha", ChatSession("a", "Alpha session", null)),
ProfileSessionRow("beta", ChatSession("b", "Beta session", null)),
),
onProfileColorChange = { profile, color -> changed = profile to color },
onRefreshAllProfiles = {},
onSelectProfileSession = { _, _ -> },
onNewChat = {},
onSelectSession = {},
onDeleteSession = {},
onRenameSession = { _, _ -> },
)
}
}
compose.onNodeWithText("All Profiles").performClick()
compose.onNodeWithText("Customize sessions").performClick()
compose.onNodeWithText("Profile colors").performScrollTo().assertIsDisplayed()
compose.onNodeWithContentDescription(
"Set alpha profile color to ${ProfileAccentSwatches.first()}",
).performScrollTo().performClick()
compose.runOnIdle {
assertEquals("alpha" to ProfileAccentSwatches.first(), changed)
}
}
}
@@ -0,0 +1,44 @@
package com.hermesandroid.relay.ui.components
import com.hermesandroid.relay.data.ApiEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TailscaleRoutePresenceTest {
@Test
fun primaryTailnetIpCountsAsConfiguredRoute() {
assertTrue(
hasConfiguredTailscaleRoute(
endpoints = emptyList(),
primaryEndpointUrl = "http://100.75.1.2:9119",
),
)
}
@Test
fun explicitTailscaleCandidateStillCounts() {
assertTrue(
hasConfiguredTailscaleRoute(
endpoints = listOf(
EndpointCandidate(
role = "tailscale",
api = ApiEndpoint("server.ts.net", 8642),
),
),
primaryEndpointUrl = "http://192.168.1.2:9119",
),
)
}
@Test
fun ordinaryLanDoesNotCount() {
assertFalse(
hasConfiguredTailscaleRoute(
endpoints = emptyList(),
primaryEndpointUrl = "http://192.168.1.2:9119",
),
)
}
}
@@ -11,7 +11,6 @@ class ChatHeaderSubtitleTest {
resolveChatHeaderSubtitle(
isStreaming = true,
statusText = "Streaming",
projectName = "Hermes Relay",
personalityName = "Victor",
modelName = "GPT-5.6",
),
@@ -19,13 +18,12 @@ class ChatHeaderSubtitleTest {
}
@Test
fun `idle subtitle retains project personality and model metadata`() {
fun `idle subtitle retains only personality and model metadata`() {
assertEquals(
"Hermes Relay \u00B7 Victor \u00B7 GPT-5.6",
"Victor \u00B7 GPT-5.6",
resolveChatHeaderSubtitle(
isStreaming = false,
statusText = "Connected",
projectName = "Hermes Relay",
personalityName = "Victor",
modelName = "GPT-5.6",
),
@@ -0,0 +1,22 @@
package com.hermesandroid.relay.ui.screens
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ProfileInspectorEditorPolicyTest {
@Test
fun `config save requires complete model identity and an idle request`() {
assertFalse(profileConfigSaveEnabled("", "gpt-5.6", saving = false))
assertFalse(profileConfigSaveEnabled("openai", "", saving = false))
assertFalse(profileConfigSaveEnabled("openai", "gpt-5.6", saving = true))
assertTrue(profileConfigSaveEnabled("openai", "gpt-5.6", saving = false))
}
@Test
fun `gateway save action appears for either kind of retained draft`() {
assertFalse(gatewayDraftSaveVisible(emptyMap(), emptyMap()))
assertTrue(gatewayDraftSaveVisible(mapOf("weather" to false), emptyMap()))
assertTrue(gatewayDraftSaveVisible(emptyMap(), mapOf("terminal" to false)))
}
}
@@ -0,0 +1,48 @@
package com.hermesandroid.relay.ui.screens
import com.hermesandroid.relay.data.ProactiveInboxEntry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ProvisionalThreadRowsTest {
@Test
fun rowsAreConnectionScopedAndDisappearWhenRealThreadExists() {
val entries = listOf(
entry("one", connectionId = "connection-a", chatId = "phone"),
entry("two", connectionId = "connection-b", chatId = "phone"),
entry("three", connectionId = "connection-a", chatId = "project"),
)
val rows = buildProvisionalThreadRows(
entries = entries,
activeConnectionId = "connection-a",
realThreadChatIds = listOf("project"),
)
assertEquals(listOf("one"), rows.getValue("phone").map { it.id })
assertFalse("project" in rows)
}
@Test
fun legacyUnscopedEntriesRemainVisibleOnTheActiveConnection() {
val rows = buildProvisionalThreadRows(
entries = listOf(entry("legacy", connectionId = null, chatId = null)),
activeConnectionId = "connection-a",
realThreadChatIds = emptyList(),
)
assertTrue("phone" in rows)
}
private fun entry(id: String, connectionId: String?, chatId: String?) =
ProactiveInboxEntry(
id = id,
title = "Hermes",
text = id,
receivedAt = 1L,
chatId = chatId,
connectionId = connectionId,
)
}
@@ -0,0 +1,25 @@
package com.hermesandroid.relay.ui.theme
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Test
class ProfileAccentTest {
@Test
fun namedProfilesReceiveStableDistinctColors() {
assertEquals(deterministicProfileAccent("alpha"), deterministicProfileAccent("alpha"))
assertNotEquals(deterministicProfileAccent("alpha"), deterministicProfileAccent("beta"))
}
@Test
fun overrideWinsAndDefaultRemainsNeutral() {
assertEquals(accentColor("#356CFF"), resolveProfileAccent("alpha", mapOf("alpha" to "#356CFF")))
assertNull(resolveProfileAccent("default", mapOf("default" to "#356CFF")))
}
@Test
fun pickerOffersDesktopSizedPalette() {
assertEquals(12, ProfileAccentSwatches.distinct().size)
}
}
@@ -0,0 +1,23 @@
package com.hermesandroid.relay.util
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
class NavRouteRequestTest {
@Test
fun requestBeforeCollector_isRetainedAndConsumedOnce() = runBlocking {
assertTrue(NavRouteRequest.tryRequest("chat?proactiveChatId=phone"))
assertEquals(
"chat?proactiveChatId=phone",
withTimeout(1_000) { NavRouteRequest.requests.first() },
)
assertNull(withTimeoutOrNull(50) { NavRouteRequest.requests.first() })
}
}
@@ -12,6 +12,7 @@ import com.hermesandroid.relay.data.ChatTurnToolCheckpoint
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
import com.hermesandroid.relay.data.HermesCardDispatch
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
import com.hermesandroid.relay.network.upstream.GatewayChatClient
@@ -148,6 +149,75 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals("victor", gatewayClient.sessionProfileProvider())
}
@Test
fun allProfilesOpenKeepsGlobalSelectionButScopesHistoryResumeAndSendToOwner() {
val global = Profile(name = "mizu", model = "grok-4.5", description = "Mizu")
val owner = Profile(name = "x-bot", model = "grok-4.3", description = "X Bot")
var loadedProfile: String? = null
var persistedSession = "unchanged"
viewModel.setSelectedProfileProvider { global }
viewModel.setSessionProfileNameProvider { global.name }
viewModel.onSessionChanged = { persistedSession = it ?: "cleared" }
viewModel.setProfileMessageLoaderWithMode { profileName, _, _ ->
loadedProfile = profileName
Result.success(emptyList())
}
viewModel.openProfileSession(
profileName = owner.name,
profile = owner,
contextKey = AgentDisplay.profileContextKey("connection-a", owner.name),
sessionId = "x-bot-session",
)
awaitCondition { loadedProfile == owner.name }
assertEquals(owner.name, viewModel.openedSessionProfileName.value)
assertEquals(owner.name, gatewayClient.sessionProfileProvider())
assertEquals("X-bot", handler.activeAgentName)
assertEquals("unchanged", persistedSession)
viewModel.switchProfileContext(
AgentDisplay.profileContextKey("connection-a", global.name),
sessionId = null,
)
assertEquals(null, viewModel.openedSessionProfileName.value)
assertEquals(global.name, gatewayClient.sessionProfileProvider())
viewModel.openProfileSession(
profileName = owner.name,
profile = owner,
contextKey = AgentDisplay.profileContextKey("connection-a", owner.name),
sessionId = "x-bot-session",
)
assertEquals(owner.name, viewModel.openedSessionProfileName.value)
viewModel.createNewChat()
assertEquals(null, viewModel.openedSessionProfileName.value)
assertEquals(global.name, gatewayClient.sessionProfileProvider())
}
@Test
fun allProfilesNewChatUsesLiteralDefaultWithoutChangingGlobalSelection() {
val global = Profile(name = "victor", model = "grok-4.5", description = "Victor")
val rootDefault = Profile(name = "default", model = "gpt-5.5", description = "Hermes")
var persistedSession = "unchanged"
viewModel.setSelectedProfileProvider { global }
viewModel.setSessionProfileNameProvider { global.name }
viewModel.onSessionChanged = { persistedSession = it ?: "cleared" }
viewModel.createProfileChat(
profileName = "default",
profile = rootDefault,
contextKey = AgentDisplay.profileContextKey("connection-a", "default"),
)
assertEquals("default", viewModel.openedSessionProfileName.value)
assertEquals("default", gatewayClient.sessionProfileProvider())
assertEquals(null, handler.currentSessionId.value)
assertEquals("Hermes", handler.activeAgentName)
assertEquals("unchanged", persistedSession)
}
@Test
fun gatewaySessionCreateProviderPreservesExplicitFastFalse() {
serverWs.send(
@@ -662,6 +732,34 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals("once", cardMessage.cardDispatches.single().actionValue)
}
@Test
fun protectedInstructionApprovalCardOffersOneOperationScopeOnly() {
viewModel.sendMessage("Edit the disposable instruction fixture")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"approval.request",
buildJsonObject {
put("command", "<write to AGENTS.md>")
put("allow_session", false)
put("allow_permanent", false)
put("choices", buildJsonArray {
add(JsonPrimitive("once"))
add(JsonPrimitive("session"))
add(JsonPrimitive("always"))
add(JsonPrimitive("deny"))
})
},
"live-resumed",
),
)
awaitCondition { viewModel.pendingAsk.value != null }
val pending = requireNotNull(viewModel.pendingAsk.value)
val card = handler.messages.value.single { it.id == pending.messageId }.cards.single()
assertEquals(listOf("once", "deny"), card.actions.map { it.value })
}
@Test
fun multiSelectClarifyPreservesCardSemanticsAndExactWireAnswer() {
viewModel.sendMessage("Ask which environments")
@@ -1355,38 +1453,12 @@ class ChatViewModelGatewayInboundTurnTest {
}
@Test
fun unsolicitedTurnDoesNotReplaceAnActiveForcedSseTurn() {
holdCompletionsStream = true
fun gatewayVoiceTurnDoesNotRequireApiFallback() {
viewModel.sendVoiceMessage("local voice turn", "Respond for spoken playback")
awaitCondition { handler.isStreaming.value }
val localPlaceholderId = handler.messages.value.last().id
val params = gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
serverWs.send(
gatewayHarness.eventFrame(
"message.delta",
buildJsonObject { put("text", BACKGROUND_ANSWER) },
"live-resumed",
),
)
persistedHistory = persistedAnswerHistory()
serverWs.send(
gatewayHarness.eventFrame(
"message.complete",
buildJsonObject { put("text", BACKGROUND_ANSWER) },
"live-resumed",
),
)
Thread.sleep(150)
shadowOf(Looper.getMainLooper()).idle()
assertTrue("the forced SSE turn must still own streaming", handler.isStreaming.value)
assertTrue(handler.messages.value.any { it.id == localPlaceholderId && it.isStreaming })
assertFalse(handler.messages.value.any { it.content == BACKGROUND_ANSWER })
viewModel.cancelStream()
awaitCondition { !handler.isStreaming.value }
awaitCondition { handler.messages.value.any { it.content == BACKGROUND_ANSWER } }
assertEquals(JsonPrimitive("local voice turn"), params["text"])
assertEquals(0, apiCompletionsRequestCount.get())
}
@Test
@@ -0,0 +1,144 @@
package com.hermesandroid.relay.viewmodel
import androidx.lifecycle.SavedStateHandle
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryResponse
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlinx.serialization.json.buildJsonObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ProfileInspectorViewModelTest {
private val dispatcher = StandardTestDispatcher()
@Before fun setUp() { Dispatchers.setMain(dispatcher) }
@After fun tearDown() { Dispatchers.resetMain() }
@Test
fun `partial gateway save refreshes authoritative sections and retains failed draft`() = runTest(dispatcher) {
val initial = description(description = "Old", model = "old")
val refreshed = description(description = "Updated", model = "old")
val gateway = FakeGateway(
descriptions = mutableListOf(initial, refreshed),
configureResult = GatewayProfileConfigureResult(
requested = setOf(GatewayProfileSection.Description, GatewayProfileSection.Model),
applied = setOf(GatewayProfileSection.Description),
),
)
val viewModel = viewModel(gateway, FakeLegacy())
viewModel.loadAll()
advanceUntilIdle()
viewModel.beginConfigEdit()
viewModel.updateConfigDescriptionDraft("Updated")
viewModel.updateConfigModelDraft("new")
viewModel.saveConfigEdit()
advanceUntilIdle()
assertEquals("operator", gateway.requestedNames.distinct().single())
assertEquals("Updated", viewModel.configDescriptionDraft.value)
assertEquals("new", viewModel.configModelDraft.value)
assertTrue(viewModel.configEditing.value)
assertEquals("old", viewModel.gatewayDescription.value?.model)
}
@Test
fun `older gateway falls back to legacy inspector without changing profile namespace`() = runTest(dispatcher) {
val legacy = FakeLegacy()
val gateway = object : GatewayProfileEditorClient {
override suspend fun describeProfile(profileName: String) =
Result.failure<GatewayProfileDescription>(GatewayProfileEditorUnsupportedException())
override suspend fun configureProfile(profileName: String, patch: GatewayProfilePatch) =
error("configure must remain capability gated")
}
val viewModel = viewModel(gateway, legacy)
viewModel.loadAll()
advanceUntilIdle()
assertEquals(ProfileInspectorSource.Relay, viewModel.source.value)
assertEquals(listOf("operator"), legacy.configRequests)
assertTrue(viewModel.configState.value is LoadState.Loaded)
}
private fun viewModel(
gateway: GatewayProfileEditorClient?,
legacy: LegacyProfileInspectorClient,
) = ProfileInspectorViewModel(
legacyClient = legacy,
gatewayClient = gateway,
savedStateHandle = SavedStateHandle(mapOf(ProfileInspectorViewModel.ARG_PROFILE_NAME to "operator")),
)
private fun description(description: String, model: String) = GatewayProfileDescription(
name = "operator",
description = description,
soul = "# Soul",
provider = "openai",
model = model,
skills = emptyList(),
toolsets = emptyList(),
toolsetsPinned = false,
)
private class FakeGateway(
private val descriptions: MutableList<GatewayProfileDescription>,
private val configureResult: GatewayProfileConfigureResult,
) : GatewayProfileEditorClient {
val requestedNames = mutableListOf<String>()
override suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription> {
requestedNames += profileName
return Result.success(descriptions.removeAt(0))
}
override suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult> {
requestedNames += profileName
return Result.success(configureResult)
}
}
private class FakeLegacy : LegacyProfileInspectorClient {
val configRequests = mutableListOf<String>()
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> {
configRequests += profileName
return Result.success(ProfileConfigResponse(profileName, "config.yaml", buildJsonObject {}))
}
override suspend fun fetchSkills(profileName: String) =
Result.success(ProfileSkillsResponse(profileName, emptyList(), 0))
override suspend fun fetchSoul(profileName: String) =
Result.success(ProfileSoulResponse(profileName, "SOUL.md", "", false, 0))
override suspend fun fetchMemory(profileName: String) =
Result.success(ProfileMemoryResponse(profileName, "memories", emptyList(), 0))
override suspend fun updateSoul(profileName: String, content: String) =
Result.success(ProfileSoulUpdateResponse(true, profileName, "SOUL.md", content.length.toLong()))
override suspend fun updateMemoryEntry(profileName: String, filename: String, content: String) =
Result.success(ProfileMemoryUpdateResponse(true, profileName, filename, filename, content.length.toLong()))
override suspend fun updateSkillToggle(skillName: String, enabled: Boolean) =
Result.success<RelaySkillToggleResult>(RelaySkillToggleResult.Ok)
override suspend fun probeSkillToggleSupported() = false
}
}
@@ -241,6 +241,35 @@ class ProfileControllerLockTest {
}
}
@Test
fun explicitProfileSessionMutations_useOwningProfileWithoutChangingSelection() {
dashboardUrl = "https://dashboard.example"
coEvery { dashboardClient.deleteSession("session-2", profile = "coder") } returns
Result.success(buildJsonObject { })
coEvery { dashboardClient.renameSession("session-2", "Updated", profile = "coder") } returns
Result.success(buildJsonObject { })
coEvery { dashboardClient.setSessionPinned("session-2", true, profile = "coder") } returns
Result.success(buildJsonObject { })
coEvery { dashboardClient.setSessionArchived("session-2", true, profile = "coder") } returns
Result.success(buildJsonObject { })
assertTrue(runBlocking { controller.deleteSession("coder", "session-2") })
assertTrue(runBlocking { controller.renameSession("coder", "session-2", "Updated") })
assertTrue(runBlocking { controller.setSessionPinned("coder", "session-2", true) })
assertTrue(runBlocking { controller.setSessionArchived("coder", "session-2", true) })
coVerify(exactly = 1) { dashboardClient.deleteSession("session-2", profile = "coder") }
coVerify(exactly = 1) {
dashboardClient.renameSession("session-2", "Updated", profile = "coder")
}
coVerify(exactly = 1) {
dashboardClient.setSessionPinned("session-2", true, profile = "coder")
}
coVerify(exactly = 1) {
dashboardClient.setSessionArchived("session-2", true, profile = "coder")
}
}
// --- selectProfile gating while locked ----------------------------------
@Test
@@ -6,6 +6,7 @@ import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.TimeUnit
class UpstreamTransportControllerAuthClientTest {
@Test
@@ -25,6 +26,10 @@ class UpstreamTransportControllerAuthClientTest {
dashboardUrl = "https://hermes.example.test/alternate"
val moved = controller.dashboardHttpClientForActive(dashboardUrl)
assertNotSame(first, moved)
assertTrue(first.dispatcher.executorService.isShutdown)
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (!first.dispatcher.executorService.isShutdown && System.nanoTime() < deadline) {
Thread.yield()
}
assertTrue("replaced dashboard client was not disposed", first.dispatcher.executorService.isShutdown)
}
}
+1
View File
@@ -0,0 +1 @@
1.3.14
+108 -6
View File
@@ -50,7 +50,9 @@ for existing installs until explicitly enabled. Settings also exposes **Open
terminal**, **Open Hermes CLI**, **View daemon log**, and **Run diagnostics**,
and manages Desktop release updates. **Help &
About** reports the UI, CLI, and connected Relay versions and links to the docs,
troubleshooting, release notes, logs, and diagnostics. The installer download is
troubleshooting, release notes, logs, and diagnostics. Tray lifecycle and child-
process failures are written to `~/.hermes/tray.log`; daemon connection and tool-
router events remain in `~/.hermes/daemon.log`. The installer download is
verified against the release
`SHA256SUMS.txt`, preserves the startup preference, restores a previously
running daemon, and relaunches the tray after the silent replacement.
@@ -80,11 +82,15 @@ aborts, and non-zero process exits; and keeps request context collapsed until
explicitly expanded. Events record handler duration and request ID where
available. The compact Overview still shows only the three newest events.
Settings also keeps activity compact: it previews the three newest events and
opens a dedicated Activity page. Selecting an event opens bounded request,
stdout, stderr, result, exit, timing, and truncation evidence; sensitive request
inputs are excluded. Handler failures and aborts are **Issues**; non-zero process exits are
opens a dedicated Activity page. Selecting an event opens a truthful lifecycle
stepper plus bounded request, stdout, stderr, result, exit, timing, and
truncation evidence; sensitive request inputs are excluded. Screenshot events
can retain an opaque local PNG outside the JSON log and open it in a larger
borderless viewer. **Settings → Activity → Screenshot evidence** controls this
as Off, 1 day, 7 days (default), or 30 days, shows local file count/usage, and
caps storage at 20 files and 10 MB per image. Handler failures and aborts are **Issues**; non-zero process exits are
shown separately because probing commands may legitimately use them. **Clear**
removes both current and rotated local audit history after confirmation.
removes current/rotated audit history and retained screenshot evidence after confirmation.
Clicking a card under **Hosts** opens that host's detail page; it does not change
the active connection. The detail page is the per-host hub for its local display
@@ -375,7 +381,13 @@ The relay discovers background server-side tmux sessions named `hermes-*`, so `s
### Multi-endpoint pairing (ADR 24)
If your Hermes server is reachable via multiple routes (LAN + Tailscale + a public URL), the pairing invite encoded by the host QR carries all of them. Pass the printed `hermes-relay://pair?...` URL, raw JSON payload, or base64 payload to `--pair-qr` and the CLI probes in priority order, picks the first reachable endpoint, and records which route it used — subsequent connects show `Connected via LAN (plain)` / `Connected via Tailscale (secure)` etc.
If your Hermes server is reachable via multiple routes (optional Hermes Secure Link, Tailscale, a public TLS URL, and LAN), the pairing invite encoded by the host QR carries all of them. Generated defaults prefer Secure Link when enabled, then other secure routes, with plain LAN retained as a fallback. Pass the printed `hermes-relay://pair?...` URL, raw JSON payload, or base64 payload to `--pair-qr`; the CLI probes in strict priority order, picks the first reachable endpoint, and records which route it used. Secure Link protects transport to the QR-paired endpoint but does not create reachability, and its Relay, API, and Dashboard credentials remain separate.
**Hermes Reach** is an experimental outbound-broker fallback. The broker
provides rendezvous while the CLI validates QR-pinned Secure Link TLS inside
it, but Reach is never selected ahead of Tailscale, public TLS, or Direct Secure
Link by default. It is disabled unless the host explicitly opts into the
experimental feature. Reach failure never enables plaintext.
```sh
# Paste the full pairing invite URL printed by hermes-pair:
@@ -435,6 +447,81 @@ assist/control grant is active because approved input inherits that privilege.
Default computer-use policy blocks password managers, credential prompts, banking/payment/crypto surfaces, OS security/admin settings, and private-key/token material. `~/.hermes/desktop-control.json` lets operators tighten or extend that baseline.
#### Preferred CUA Driver engine
On Windows, Hermes-Relay prefers a compatible local
[CUA Driver](https://github.com/trycua/cua) runtime for structured
computer-control engine. It stays behind the same `desktop_computer_*` tools:
the agent does not receive CUA's raw tool surface, configuration, updater,
recording, replay, JavaScript, application-launch, or process-termination
operations.
Windows input is the explicit compatibility backend. A backend is selected once
when each authenticated control session starts and cannot change mid-session;
changing the setting affects only new sessions. If preferred CUA is unavailable
before a session starts, that session can use compatibility mode.
Inspect the detected runtime and selected/effective engine with:
```powershell
hermes-relay computer-use status --json
hermes-relay computer-use cua status
hermes-relay computer-use cua health # explicit accessibility recheck
hermes-relay computer-use cua check-update
hermes-relay computer-use cua install --yes
hermes-relay computer-use cua update --yes
hermes-relay computer-use engine cua # preferred; requires a ready runtime
hermes-relay computer-use engine legacy # explicit compatibility backend
hermes-relay computer-use cursor on
```
The management UI exposes the same controls under **Settings → Computer
control**. CUA is selected only when its canonical Windows package resolves from
`%USERPROFILE%\.cua-driver\packages\current\cua-driver.exe`, its supported
version and manifest agree, its required tools are present, and its permission mode
is not unrestricted. The live health report is an explicit diagnostic while the
temporary Windows workaround for trycua/cua#3103 is active. Hermes ignores an unrelated
or stale `cua-driver.exe` found earlier on `PATH`.
Background dispatch is mandatory. If an application cannot accept a
background action, the action fails instead of silently stealing focus.
**Allow foreground escalation** is reserved for a later explicitly approved
path; this release always reports it off and dispatches CUA actions in the
background. **Animated agent cursor** shows a virtual, session-scoped pointer
for agent activity; it does not move the operator's physical Windows cursor and
is not another hardware pointer. Hermes binds driver sessions and snapshot
tokens to its own control authority, target PID/window, grant, and fresh
snapshot; an element token cannot be reused across windows or after it is
consumed or expires.
CUA Driver is not bundled with the Hermes-Relay installer. The explicit
`computer-use cua install|update --yes` commands use the canonical upstream
GitHub release manifest and installer. Hermes verifies the manifest's
repository/product/version and installer SHA-256 before execution under a
sanitized child-process environment, then checks
the canonical binary's path, version, own manifest, tool surface, and permission
mode. Accessibility health can be rechecked separately. This is release-metadata/checksum validation—not a Windows
publisher signature. A native update newer than the supported `>=0.19.3,
<0.20.0` range is displayed but refused. There is no silent install/update,
and every child invocation forces CUA telemetry off. `hermes-relay update`
continues to manage only the CLI and management UI.
Window-scoped snapshots and semantic actions use the selected control backend.
The existing full-display screenshot remains a separate read-only
`system_capture` path, so observation does not cause a mid-session backend
switch. The local audit and UI Activity timeline record bounded high-level
evidence such as backend, background dispatch, control session, target
application/window identifiers, action, phase, and verification state.
Accessibility text, screenshot bytes, entered values, and raw CUA responses are
excluded from that drilldown.
CUA improves structured screen/input isolation, but it is not a sandbox for
general commands. If Commands, PowerShell, or terminal execution is allowed,
that trusted path can still use ordinary operating-system automation. Disable
raw command access when CUA's scoped UI-control boundary is part of the security
model. Full Access can remove ordinary task prompts, but it does not bypass
authenticated targeting, sensitive-surface checks, snapshot freshness, UAC or
Windows-session boundaries, audit, driver health, or emergency stop.
### Devices — server-side session management
```sh
@@ -627,6 +714,21 @@ Precedence for credentials: `--token` → `HERMES_RELAY_TOKEN` → `--code` →
## Troubleshooting
- **Many `Bun` / `hermes-relay.exe` processes, or Windows error `0xc0000142` from `reg.exe`, `adb.exe`, or `hermes-relay.exe`** — quit **Hermes-Relay CLI UI** first, then run `hermes-relay daemon stop` from a fresh PowerShell. If the CLI cannot start, inspect exact executable paths before stopping only Hermes-Relay-owned processes:
```powershell
$relayBin = [IO.Path]::GetFullPath("$env:USERPROFILE\.hermes\bin\")
$relayProcesses = Get-CimInstance Win32_Process | Where-Object {
$_.ExecutablePath -and
[IO.Path]::GetFullPath($_.ExecutablePath).StartsWith($relayBin, [StringComparison]::OrdinalIgnoreCase) -and
$_.Name -in @('hermes-relay.exe', 'hermes-relay-tray.exe')
}
$relayProcesses | Select-Object ProcessId, ParentProcessId, Name, ExecutablePath, CommandLine
# Review the rows above before stopping them:
$relayProcesses | ForEach-Object { Stop-Process -Id $_.ProcessId }
```
Do not broadly stop every process named `Bun`: unrelated development tools may use the same runtime name. After recovery, inspect `~/.hermes/tray.log` for snapshot, subprocess timeout, launch, and exit failures. Use `~/.hermes/daemon.log` for the single long-running daemon's authentication, transport, and tool-router lifecycle. If unrelated Windows programs still fail to initialize, restart Windows before relaunching the tray.
- **`auth timed out after 15000ms`** — the relay subprocess takes 15–30 s on first attach because it initializes the full agent. Bump the timeout: `HERMES_RELAY_AUTH_TIMEOUT_MS=30000 hermes-relay …`.
- **`relay rejected credentials: auth failed`** — your stored token expired or was revoked. Re-pair: `hermes-relay pair --remote ws://…`.
- **`RelayTransport: global WebSocket not available`** — your Node is too old. Need >=21.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-beta.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-beta.3",
"license": "MIT",
"bin": {
"hermes-relay": "bin/hermes-relay.js"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-beta.3",
"description": "Thin-client CLI for Hermes-Relay — talk to a remote Hermes agent over WSS with pairing auth, stream-renders tool calls and responses to plain stdout.",
"type": "module",
"bin": {
+118
View File
@@ -0,0 +1,118 @@
[CmdletBinding()]
param(
[switch]$Run,
[string]$CuaDriver = "$env:USERPROFILE\.cua-driver\packages\current\cua-driver.exe"
)
$ErrorActionPreference = 'Stop'
if (-not $Run) {
Write-Host 'Hermes CUA live acceptance is opt-in because it opens and controls two Calculator windows.'
Write-Host 'Re-run with: powershell -ExecutionPolicy Bypass -File scripts/test-cua-windows.ps1 -Run'
exit 0
}
if (-not (Test-Path -LiteralPath $CuaDriver -PathType Leaf)) {
throw "Canonical CUA Driver was not found at $CuaDriver"
}
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class HermesCuaAcceptanceNative {
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT point);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
}
'@
function Invoke-Cua([string]$Tool, [hashtable]$Payload) {
$json = $Payload | ConvertTo-Json -Depth 12 -Compress
$raw = $json | & $CuaDriver call $Tool
if ($LASTEXITCODE -ne 0) { throw "CUA $Tool failed with exit code $LASTEXITCODE" }
$result = $raw | ConvertFrom-Json
if ($result.isError -eq $true) { throw "CUA $Tool rejected the request: $raw" }
return $result
}
function Get-DesktopSentinel {
$point = New-Object HermesCuaAcceptanceNative+POINT
[void][HermesCuaAcceptanceNative]::GetCursorPos([ref]$point)
[pscustomobject]@{
CursorX = $point.X
CursorY = $point.Y
Foreground = [HermesCuaAcceptanceNative]::GetForegroundWindow().ToInt64()
}
}
function Assert-Unchanged([object]$Before, [string]$Step) {
$after = Get-DesktopSentinel
if ($after.CursorX -ne $Before.CursorX -or $after.CursorY -ne $Before.CursorY) {
throw "$Step moved the physical cursor from ($($Before.CursorX),$($Before.CursorY)) to ($($after.CursorX),$($after.CursorY))"
}
if ($after.Foreground -ne $Before.Foreground) {
throw "$Step changed the foreground HWND from $($Before.Foreground) to $($after.Foreground)"
}
}
function Get-Window([object]$Launch) {
$window = @($Launch.windows | Where-Object { $_.is_on_screen -ne $false }) | Select-Object -First 1
if (-not $window) { throw "CUA launch did not return a usable window: $($Launch | ConvertTo-Json -Depth 8 -Compress)" }
return $window
}
$sessionA = "hermes-live-a-$([guid]::NewGuid().ToString('N'))"
$sessionB = "hermes-live-b-$([guid]::NewGuid().ToString('N'))"
$opened = @()
try {
$health = Invoke-Cua health_report @{}
if ($health.overall -ne 'healthy') { throw "CUA health must be healthy, got $($health.overall)" }
[void](Invoke-Cua start_session @{ session = $sessionA; capture_scope = 'window' })
[void](Invoke-Cua start_session @{ session = $sessionB; capture_scope = 'window' })
$sentinel = Get-DesktopSentinel
$launchA = Invoke-Cua launch_app @{ aumid = 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'; creates_new_application_instance = $true; session = $sessionA }
$launchB = Invoke-Cua launch_app @{ aumid = 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'; creates_new_application_instance = $true; session = $sessionB }
$opened = @($launchA.pid, $launchB.pid)
Start-Sleep -Milliseconds 800
Assert-Unchanged $sentinel 'background launch'
$windowA = Get-Window $launchA
$windowB = Get-Window $launchB
if ($windowA.window_id -eq $windowB.window_id) { throw 'isolated sessions resolved to the same Calculator window' }
$beforeA = Invoke-Cua get_window_state @{ pid = $launchA.pid; window_id = $windowA.window_id; session = $sessionA; query = 'Seven'; include_screenshot = $false }
$seven = @($beforeA.elements | Where-Object { $_.label -eq 'Seven' -or $_.name -eq 'Seven' }) | Select-Object -First 1
if (-not $seven.element_token) { throw 'Calculator Seven element did not expose an opaque token' }
[void](Invoke-Cua click @{ pid = $launchA.pid; window_id = $windowA.window_id; element_token = $seven.element_token; session = $sessionA; scope = 'window'; delivery_mode = 'background' })
Assert-Unchanged $sentinel 'background element action'
$afterA = Invoke-Cua get_window_state @{ pid = $launchA.pid; window_id = $windowA.window_id; session = $sessionA; query = 'Display'; include_screenshot = $false }
if ($afterA.snapshot_id -eq $beforeA.snapshot_id) { throw 'post-action snapshot did not advance its generation' }
$staleRaw = (@{ pid = $launchA.pid; window_id = $windowA.window_id; element_token = $seven.element_token; session = $sessionA; scope = 'window'; delivery_mode = 'background' } | ConvertTo-Json -Compress) | & $CuaDriver call click
$stale = $staleRaw | ConvertFrom-Json
if ($stale.isError -ne $true) { throw 'stale element token was accepted after a newer snapshot' }
$cursorA = Invoke-Cua get_agent_cursor_state @{ session = $sessionA }
$cursorB = Invoke-Cua get_agent_cursor_state @{ session = $sessionB }
if (($cursorA | ConvertTo-Json -Depth 8 -Compress) -eq ($cursorB | ConvertTo-Json -Depth 8 -Compress)) {
throw 'two control sessions did not expose isolated cursor state'
}
[void](Invoke-Cua end_session @{ session = $sessionA })
$endedRaw = (@{ session = $sessionA } | ConvertTo-Json -Compress) | & $CuaDriver call get_session_state
$ended = $endedRaw | ConvertFrom-Json
if ($ended.code -ne 'session_not_started') { throw 'ended session remained active' }
Write-Host 'PASS: physical cursor and foreground stayed unchanged.'
Write-Host 'PASS: background Calculator action was bracketed by snapshots.'
Write-Host 'PASS: stale token rejection and two isolated cursor sessions were verified.'
Write-Host 'PASS: ending a session immediately revoked its CUA state.'
} finally {
foreach ($session in @($sessionA, $sessionB)) {
try { [void](Invoke-Cua end_session @{ session = $session }) } catch { Write-Warning $_ }
}
Write-Host "Calculator processes created by this acceptance run: $($opened -join ', '). Close them manually after inspection."
}
+21
View File
@@ -40,6 +40,27 @@ export const extractSpkiSha256 = (peerCertDer: Buffer): string => {
return `${PIN_PREFIX}${digest}`
}
/** Read the leaf DER across supported Node TLS APIs. Node 24 can return an
* empty legacy PeerCertificate for a valid TLS 1.3 connection while the
* X509Certificate API remains populated. Prefer the modern API and retain the
* legacy fallback for Node 21-23. */
export const peerCertificateDer = (socket: {
getPeerX509Certificate?: () => { raw?: Buffer } | undefined
getPeerCertificate?: (detailed?: boolean) => { raw?: Buffer }
}): Buffer | null => {
const modern = socket.getPeerX509Certificate?.()?.raw
if (Buffer.isBuffer(modern) && modern.length > 0) return modern
const legacy = socket.getPeerCertificate?.(false)?.raw
return Buffer.isBuffer(legacy) && legacy.length > 0 ? legacy : null
}
/** Convert the already pin-verified leaf to a PEM trust anchor for the live
* WebSocket handshake. This binds the live connection to the checked cert. */
export const certificateDerToPem = (der: Buffer): string => {
const base64 = der.toString('base64').match(/.{1,64}/g)?.join('\n') ?? ''
return `-----BEGIN CERTIFICATE-----\n${base64}\n-----END CERTIFICATE-----\n`
}
/**
* Canonical pin-store key for a URL — lowercase `host:port`. Explicit port
* is required (no implicit 443/80) so `wss://host/` and `wss://host:443/`
+34 -3
View File
@@ -5,7 +5,8 @@
// the audit flagged as the biggest desktop-tools transparency gap.
import type { ParsedArgs } from '../cli.js'
import { auditLogPath, readRecentAudit } from '../lib/auditLog.js'
import { auditLogPath, auditScreenshotEvidenceStatus, clearAuditScreenshotEvidence, pruneAuditScreenshotEvidence, readRecentAudit } from '../lib/auditLog.js'
import { readDesktopUseSettings, setActivityScreenshotRetention } from '../lib/desktopUseSettings.js'
import { renderTable } from '../lib/table.js'
import { SYMBOLS, theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec } from '../lib/usage.js'
@@ -13,10 +14,12 @@ import { printUsage, type UsageSpec } from '../lib/usage.js'
const AUDIT_USAGE: UsageSpec = {
name: 'audit',
summary: 'show recent desktop-tool activity the agent ran on this machine',
usage: ['audit [--limit <n>] [--json]'],
usage: ['audit [--limit <n>] [--json]', 'audit screenshots [on|off] [--days <1|7|30>] [--yes] [--json]'],
flags: [
{ flag: '--limit <n>', desc: 'How many recent entries to show (default 50)' },
{ flag: '--json', desc: 'Emit raw audit entries as JSON' }
{ flag: '--json', desc: 'Emit raw audit entries as JSON' },
{ flag: '--days <1|7|30>', desc: 'Local screenshot retention period' },
{ flag: '--yes', desc: 'Confirm a retention change' }
],
examples: ['hermes-relay audit', 'hermes-relay audit --limit 20']
}
@@ -36,6 +39,34 @@ export async function auditCommand(args: ParsedArgs): Promise<number> {
return 0
}
if (args.positional[0] === 'screenshots') {
const settings = await readDesktopUseSettings()
const mode = args.positional[1]
if (mode === 'on' || mode === 'off') {
if (args.flags.yes !== true) {
process.stderr.write('audit screenshots: retention changes require --yes\n')
return 1
}
const rawDays = typeof args.flags.days === 'string' ? Number(args.flags.days) : settings.activity_screenshot_retention_days
if (rawDays !== 1 && rawDays !== 7 && rawDays !== 30) {
process.stderr.write('audit screenshots: --days must be 1, 7, or 30\n')
return 1
}
await setActivityScreenshotRetention(mode === 'on', rawDays)
if (mode === 'off') await clearAuditScreenshotEvidence()
else await pruneAuditScreenshotEvidence(rawDays)
} else if (mode) {
process.stderr.write('audit screenshots: expected on or off\n')
return 1
}
const current = await readDesktopUseSettings()
const evidence = await auditScreenshotEvidenceStatus()
const result = { enabled: current.activity_screenshot_retention_enabled, days: current.activity_screenshot_retention_days, ...evidence }
if (args.flags.json) process.stdout.write(JSON.stringify(result, null, 2) + '\n')
else process.stdout.write(`Screenshot evidence: ${result.enabled ? `${result.days} days` : 'off'} · ${result.count} file${result.count === 1 ? '' : 's'}\n`)
return 0
}
const rawLimit = typeof args.flags.limit === 'string' ? parseInt(args.flags.limit, 10) : 50
const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? rawLimit : 50
+163 -4
View File
@@ -5,11 +5,19 @@ import { readDaemonStatus, isDaemonProcessAlive } from '../lib/daemonStatus.js'
import {
readDesktopUseSettings,
requestComputerGrantCancellation,
setComputerControlSettings,
setDesktopUseEnabled
} from '../lib/desktopUseSettings.js'
import { listPendingGrantRequests } from '../lib/grantBridge.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec, unknownSubcommand } from '../lib/usage.js'
import { CuaDriverAdapter, type CuaRuntimeStatus } from '../tools/cuaDriver.js'
import {
checkCuaUpdate,
getCuaManagementStatus,
installCuaDriver,
updateCuaDriver
} from '../tools/cuaManagement.js'
const COMPUTER_USE_USAGE: UsageSpec = {
name: 'computer-use',
@@ -18,21 +26,31 @@ const COMPUTER_USE_USAGE: UsageSpec = {
'computer-use status [--json]',
'computer-use enable [--yes]',
'computer-use disable',
'computer-use cancel'
'computer-use cancel',
'computer-use engine <legacy|cua>',
'computer-use cursor <on|off>',
'computer-use cua <status|health|install|check-update|update> [--json] [--yes]'
],
subcommands: [
{ verb: 'status', desc: 'Show preference, daemon state, active grant, and pending requests' },
{ verb: 'enable', desc: 'Persist desktop-use enablement after explicit confirmation' },
{ verb: 'disable', desc: 'Disable desktop use and request cancellation of any active grant' },
{ verb: 'cancel', desc: 'Cancel the active task-scoped desktop grant' }
{ verb: 'cancel', desc: 'Cancel the active task-scoped desktop grant' },
{ verb: 'engine', desc: 'Choose legacy Windows input or a ready CUA Driver backend' },
{ verb: 'cursor', desc: 'Show or hide the CUA virtual agent cursor' },
{ verb: 'cua', desc: 'Manage the canonical CUA Driver package and recheck accessibility health' }
],
flags: [
{ flag: '--json', desc: 'Emit machine-readable status' },
{ flag: '--yes', desc: 'Confirm enablement non-interactively' }
{ flag: '--yes', desc: 'Confirm enablement, CUA installation, or CUA update explicitly' }
],
examples: [
'hermes-relay computer-use status',
'hermes-relay computer-use enable',
'hermes-relay computer-use cua status',
'hermes-relay computer-use cua health',
'hermes-relay computer-use cua check-update',
'hermes-relay computer-use cua install --yes',
'hermes-relay computer-use cancel',
'hermes-relay computer-use disable'
]
@@ -62,6 +80,24 @@ async function statusPayload(): Promise<Record<string, unknown>> {
const activeGrant = daemonAlive && daemon?.computer_grant?.active === true
? daemon.computer_grant
: null
let cua: CuaRuntimeStatus | null = null
try {
cua = await CuaDriverAdapter.status()
} catch {
// The optional backend must not make ordinary desktop-use status fail.
}
const cuaReason = cua?.reason?.toLowerCase() ?? ''
const cuaState = !cua?.available
? 'not_installed'
: cua.ready
? 'ready'
: /(?:incompatible|unsupported|version|manifest|permission mode|missing required tools)/.test(cuaReason)
? 'incompatible'
: /(?:degraded|health)/.test(cuaReason)
? 'degraded'
: 'error'
const cuaReady = cuaState === 'ready'
const lifecycle = daemonAlive ? daemon?.computer_control : undefined
return {
enabled: settings.computer_use_enabled,
daemon_alive: daemonAlive,
@@ -69,7 +105,32 @@ async function statusPayload(): Promise<Record<string, unknown>> {
daemon_computer_use_enabled: daemonAlive ? (daemon?.computer_use_enabled ?? false) : false,
active_grant: activeGrant,
pending_grants: pending.length,
restart_required: daemonAlive && daemon?.computer_use_enabled !== settings.computer_use_enabled
restart_required: daemonAlive && daemon?.computer_use_enabled !== settings.computer_use_enabled,
computer_control_engine: {
selected: settings.computer_control_engine,
effective: settings.computer_control_engine === 'cua'
? lifecycle?.active_backend === 'cua'
? 'cua'
: lifecycle?.active_backend === 'legacy_compat'
? 'legacy'
: cuaReady ? 'cua' : 'legacy'
: 'legacy',
available: cua?.available === true,
state: cuaState,
version: cua?.binaryVersion ?? null,
health: cua?.health ?? null,
path: cua?.binaryPath ?? null,
cursor_enabled: settings.cua_cursor_enabled,
active_sessions: lifecycle?.active_sessions ?? 0,
active_backend: lifecycle?.active_backend ?? 'idle',
last_action: lifecycle?.last_action ?? null,
foreground_escalation_enabled: false,
message: settings.computer_control_engine === 'cua' && !cuaReady
? cuaState === 'degraded'
? `CUA Driver is installed, but UI Automation is degraded; new sessions use Windows Input compatibility mode. ${cua?.reason ?? ''}`.trim()
: `CUA Driver is unavailable before control starts; new sessions use Windows Input compatibility mode. ${cua?.reason ?? ''}`.trim()
: cua?.reason ?? null
}
}
}
@@ -81,6 +142,68 @@ export async function computerUseCommand(args: ParsedArgs): Promise<number> {
}
const subcommand = args.positional[0] ?? 'status'
if (subcommand === 'cua') {
const action = args.positional[1] ?? 'status'
const json = args.flags.json === true
try {
if (action === 'health') {
const health = await CuaDriverAdapter.healthStatus()
if (json) process.stdout.write(JSON.stringify(health, null, 2) + '\n')
else {
process.stdout.write(t.bold('CUA Driver accessibility health') + `\n state: ${health.state}\n`)
if (health.reason) process.stdout.write(t.warnLine(` ${health.reason}`) + '\n')
process.stdout.write(t.muted(' This diagnostic does not disable the runtime while the temporary Windows compatibility policy is active.') + '\n')
}
// The probe result is data, not command failure. Callers (including the
// tray) inspect state while still receiving the JSON for degradation.
return 0
}
const payload = action === 'status'
? await getCuaManagementStatus()
: action === 'check-update'
? await checkCuaUpdate()
: action === 'install'
? args.flags.yes === true
? await installCuaDriver()
: null
: action === 'update'
? args.flags.yes === true
? await updateCuaDriver()
: null
: undefined
if (payload === undefined) {
process.stderr.write(t.err('cua action must be status, health, install, check-update, or update') + '\n')
return 1
}
if (payload === null) {
process.stderr.write(t.err(`CUA ${action} requires explicit confirmation with --yes`) + '\n')
return 1
}
if (json) {
process.stdout.write(JSON.stringify(payload, null, 2) + '\n')
return 0
}
const version = payload.current_version ?? 'not installed'
process.stdout.write(t.bold('CUA Driver') + `\n version: ${version}\n`)
process.stdout.write(` package: ${payload.canonical_path ?? 'not installed'}\n`)
process.stdout.write(` compatibility: ${payload.compatible ? 'supported' : payload.compatibility_reason ?? 'not ready'}\n`)
if (payload.stale_path_shim) {
process.stdout.write(t.warnLine(` PATH resolves a competing copy: ${payload.discovered_path}`) + '\n')
process.stdout.write(t.muted(' Hermes uses the canonical package/current install instead.') + '\n')
}
if (payload.update) {
if (payload.update.error) process.stdout.write(t.warnLine(` update check: ${payload.update.error}`) + '\n')
else if (payload.update.update_available) {
process.stdout.write(` update: ${payload.update.latest_version}${payload.update.compatible ? ' available' : ' available but unsupported'}\n`)
} else process.stdout.write(' update: up to date\n')
}
if (payload.operation) process.stdout.write(t.okLine(`CUA ${payload.operation.kind} completed`) + '\n')
return 0
} catch (error) {
process.stderr.write(t.err(error instanceof Error ? error.message : String(error)) + '\n')
return 1
}
}
if (subcommand === 'status') {
const payload = await statusPayload()
if (args.flags.json) {
@@ -129,6 +252,42 @@ export async function computerUseCommand(args: ParsedArgs): Promise<number> {
return 0
}
if (subcommand === 'engine') {
const engine = args.positional[1]
if (engine !== 'legacy' && engine !== 'cua') {
process.stderr.write(t.err('engine must be legacy or cua') + '\n')
return 1
}
if (engine === 'cua') {
const payload = await statusPayload()
const status = payload.computer_control_engine as { state?: string }
if (status.state !== 'ready') {
process.stderr.write(t.err('CUA Driver is not ready; engine selection was not changed') + '\n')
return 1
}
}
await setComputerControlSettings({ computer_control_engine: engine })
process.stdout.write(t.okLine(`computer control engine set to ${engine}`) + '\n')
return 0
}
if (subcommand === 'cursor') {
const value = args.positional[1]
if (value !== 'on' && value !== 'off') {
process.stderr.write(t.err(`${subcommand} must be on or off`) + '\n')
return 1
}
const payload = await statusPayload()
const status = payload.computer_control_engine as { selected?: string; state?: string }
if (status.selected !== 'cua' || status.state !== 'ready') {
process.stderr.write(t.err(`CUA Driver must be selected and ready before changing ${subcommand}`) + '\n')
return 1
}
await setComputerControlSettings({ cua_cursor_enabled: value === 'on' })
process.stdout.write(t.okLine(`CUA ${subcommand} ${value}`) + '\n')
return 0
}
return unknownSubcommand(COMPUTER_USE_USAGE, subcommand, t)
}
+283 -17
View File
@@ -31,11 +31,13 @@
import { spawn } from 'node:child_process'
import { closeSync, openSync, promises as fs } from 'node:fs'
import { randomUUID } from 'node:crypto'
import * as os from 'node:os'
import * as path from 'node:path'
import type { ParsedArgs } from '../cli.js'
import { desktopRelayIdentity } from '../deviceIdentity.js'
import { inferEndpointRole } from '../endpoint.js'
import { GatewayClient } from '../gatewayClient.js'
import type { GatewayEvent, SessionCreateResponse } from '../gatewayTypes.js'
import {
@@ -49,23 +51,26 @@ import {
type DaemonStatus
} from '../lib/daemonStatus.js'
import { rpcErrorMessage, asRpcResult } from '../lib/rpc.js'
import { appendAudit } from '../lib/auditLog.js'
import { effectiveHostAccessMode, effectiveHostCapabilityPolicies, getHostAccessMode, getHostCapabilityPolicies } from '../lib/hostAccessPolicy.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec } from '../lib/usage.js'
import { resolveFirstRunUrl } from '../relayUrlPrompt.js'
import { getSession } from '../remoteSessions.js'
import { probeCandidatesByPriority, secureFirstCandidates } from '../pairingQr.js'
import {
advertisedDesktopTools,
desktopHandlers,
shouldAdvertiseComputerUse
} from '../tools/handlerSet.js'
import {
cancelComputerGrant,
cancelAllComputerGrants,
configureComputerUseRuntime,
getActiveComputerGrant,
expireComputerControlSessions,
setComputerGrantChangeListener,
type ComputerGrant
} from '../tools/computerGrants.js'
import { closeCuaControlSession, setComputerControlLifecycleListener } from '../tools/cuaDriver.js'
import { DesktopToolRouter } from '../tools/router.js'
import { configureCapabilityPolicies } from '../tools/capabilityRuntime.js'
import { adbBackendAvailable } from '../tools/handlers/adb.js'
@@ -83,6 +88,156 @@ const VOICE_DISCOVERY_FILE = 'desktop-voice.json'
const STATUS_HEARTBEAT_MS = 30_000
const DETACHED_START_TIMEOUT_MS = 20_000
const DETACHED_START_POLL_MS = 100
const LIFECYCLE_LOCK_TIMEOUT_MS = 25_000
const INSTANCE_LOCK_TIMEOUT_MS = 2_000
const LOCK_POLL_MS = 50
const INCOMPLETE_LOCK_GRACE_MS = 1_000
interface ProcessLockOwner {
pid: number
process_name: string
token: string
created_at: number
purpose: string
}
interface ProcessLock {
owner: ProcessLockOwner
release: () => Promise<void>
}
interface ProcessLockOptions {
timeoutMs: number
purpose: string
now?: () => number
sleep?: (ms: number) => Promise<void>
ownerAlive?: (owner: ProcessLockOwner) => boolean
}
function daemonLockPath(kind: 'lifecycle' | 'instance'): string {
return path.join(os.homedir(), '.hermes', `daemon-${kind}.lock`)
}
async function readProcessLockOwner(lockPath: string): Promise<ProcessLockOwner | null> {
try {
const parsed = JSON.parse(await fs.readFile(path.join(lockPath, 'owner.json'), 'utf8')) as Partial<ProcessLockOwner>
if (
typeof parsed.pid !== 'number' ||
typeof parsed.process_name !== 'string' ||
typeof parsed.token !== 'string' ||
typeof parsed.created_at !== 'number' ||
typeof parsed.purpose !== 'string'
) return null
return parsed as ProcessLockOwner
} catch {
return null
}
}
function processLockOwnerAlive(owner: ProcessLockOwner): boolean {
// PID liveness is deliberately authoritative here. Unlike status/stop, a
// conservative false positive only causes a bounded lock timeout; a false
// negative could let a second daemon start. It also avoids spawning tasklist
// or ps from the startup hot path (and executable-name truncation on Unix).
return isPidAlive(owner.pid)
}
async function releaseProcessLock(lockPath: string, token: string): Promise<void> {
const owner = await readProcessLockOwner(lockPath)
if (owner?.token !== token) return
try {
// Remove the ownership record before the directory. mkdir remains blocked
// until rmdir succeeds, so a newer owner cannot appear between the token
// check and release.
await fs.unlink(path.join(lockPath, 'owner.json'))
await fs.rmdir(lockPath)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
}
/** Atomic directory lock shared by compiled Bun binaries and Node-based dev
* invocations. Stale recovery quarantines an observed directory before it is
* removed, while token-checked release never recursively removes the path. */
async function acquireProcessLock(lockPath: string, options: ProcessLockOptions): Promise<ProcessLock> {
const now = options.now ?? Date.now
const sleep = options.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms)))
const ownerAlive = options.ownerAlive ?? processLockOwnerAlive
const deadline = now() + options.timeoutMs
const owner: ProcessLockOwner = {
pid: process.pid,
process_name: path.basename(process.execPath),
token: randomUUID(),
created_at: now(),
purpose: options.purpose
}
await fs.mkdir(path.dirname(lockPath), { recursive: true })
while (true) {
try {
await fs.mkdir(lockPath)
try {
await fs.writeFile(
path.join(lockPath, 'owner.json'),
JSON.stringify(owner) + '\n',
{ encoding: 'utf8', flag: 'wx', mode: 0o600 }
)
} catch (error) {
await fs.rm(lockPath, { recursive: true, force: true }).catch(() => undefined)
throw error
}
return { owner, release: () => releaseProcessLock(lockPath, owner.token) }
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
}
const observed = await readProcessLockOwner(lockPath)
let stale = observed !== null && !ownerAlive(observed)
if (!observed) {
try {
const stat = await fs.stat(lockPath)
stale = now() - stat.mtimeMs >= INCOMPLETE_LOCK_GRACE_MS
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
throw error
}
}
if (stale) {
const quarantinePath = `${lockPath}.stale-${process.pid}-${randomUUID()}`
try {
await fs.rename(lockPath, quarantinePath)
await fs.rm(quarantinePath, { recursive: true, force: true })
continue
} catch (error) {
if (['ENOENT', 'EEXIST', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code ?? '')) continue
throw error
}
}
if (now() >= deadline) {
const detail = observed
? `owner pid ${observed.pid} (${observed.purpose})`
: 'owner metadata is still being created'
throw new Error(`timed out after ${options.timeoutMs}ms waiting for ${options.purpose} lock; ${detail}`)
}
await sleep(Math.min(LOCK_POLL_MS, Math.max(1, deadline - now())))
}
}
async function withDaemonLifecycleLock<T>(operation: string, fn: () => Promise<T>): Promise<T> {
const lock = await acquireProcessLock(daemonLockPath('lifecycle'), {
timeoutMs: LIFECYCLE_LOCK_TIMEOUT_MS,
purpose: `daemon ${operation}`
})
try {
return await fn()
} finally {
try {
await lock.release()
} catch (error) {
process.stderr.write(`daemon: lifecycle_lock_release_failed: ${rpcErrorMessage(error)}\n`)
}
}
}
const DAEMON_USAGE: UsageSpec = {
name: 'daemon',
@@ -476,7 +631,7 @@ async function runElevatedDaemonLifecycle(
/** `daemon start` / `--detach` — spawn the foreground daemon as a detached
* background process (no console window on Windows), logging to a file. */
async function startDetachedDaemon(args: ParsedArgs): Promise<number> {
async function startDetachedDaemonLocked(args: ParsedArgs): Promise<number> {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const existing = await readDaemonStatus()
@@ -572,8 +727,17 @@ async function startDetachedDaemon(args: ParsedArgs): Promise<number> {
return 0
}
async function startDetachedDaemon(args: ParsedArgs): Promise<number> {
try {
return await withDaemonLifecycleLock('start', () => startDetachedDaemonLocked(args))
} catch (error) {
process.stderr.write(`daemon: lifecycle_lock_failed: ${rpcErrorMessage(error)}\n`)
return 1
}
}
/** `daemon stop` — terminate the running background daemon by its status pid. */
async function stopDaemon(args: ParsedArgs): Promise<number> {
async function stopDaemonLocked(args: ParsedArgs): Promise<number> {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const status = await readDaemonStatus()
if (!status) {
@@ -598,7 +762,16 @@ async function stopDaemon(args: ParsedArgs): Promise<number> {
return 0
}
async function restartDaemon(args: ParsedArgs): Promise<number> {
async function stopDaemon(args: ParsedArgs): Promise<number> {
try {
return await withDaemonLifecycleLock('stop', () => stopDaemonLocked(args))
} catch (error) {
process.stderr.write(`daemon: lifecycle_lock_failed: ${rpcErrorMessage(error)}\n`)
return 1
}
}
async function restartDaemonLocked(args: ParsedArgs): Promise<number> {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const existing = await readDaemonStatus()
if (existing && isDaemonProcessAlive(existing)) {
@@ -621,7 +794,16 @@ async function restartDaemon(args: ParsedArgs): Promise<number> {
}
}
await clearDaemonStatus()
return startDetachedDaemon(args)
return startDetachedDaemonLocked(args)
}
async function restartDaemon(args: ParsedArgs): Promise<number> {
try {
return await withDaemonLifecycleLock('restart', () => restartDaemonLocked(args))
} catch (error) {
process.stderr.write(`daemon: lifecycle_lock_failed: ${rpcErrorMessage(error)}\n`)
return 1
}
}
async function restartDaemonAsUser(args: ParsedArgs): Promise<number> {
@@ -715,6 +897,26 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
const human = humanFlag || (!args.flags['log-json'] && !!process.stderr.isTTY)
const log = makeLogger(human)
let instanceLock: ProcessLock
try {
instanceLock = await acquireProcessLock(daemonLockPath('instance'), {
timeoutMs: INSTANCE_LOCK_TIMEOUT_MS,
purpose: 'daemon runtime'
})
log.info({
event: 'instance_lock_acquired',
lock_path: daemonLockPath('instance'),
pid: process.pid
})
} catch (error) {
log.error({
event: 'instance_lock_failed',
message: rpcErrorMessage(error),
lock_path: daemonLockPath('instance')
})
return 1
}
// URL resolution mirrors chat/shell — explicit --remote / HERMES_RELAY_URL
// win, otherwise fall back to a stored session. resolveFirstRunUrl with
// nonInteractive:true auto-picks when exactly one session exists, throws a
@@ -733,17 +935,51 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
(e instanceof Error ? e.message : String(e)) +
' Pass --remote <url>, set HERMES_RELAY_URL, or pair first with `hermes-relay pair`.'
})
await instanceLock.release()
return 1
}
}
// Keep the selected host as the policy/storage identity, while resolving
// its current network route independently. A v3 pair can therefore prefer
// WSS/Tailscale and fall back to LAN without creating duplicate hosts.
const configuredUrl = url
const configuredSession = await getSession(configuredUrl)
let useSessionHeader = false
let brokerRoute: import('../transport/BrokerRelaySocket.js').BrokerRouteConfig | undefined
let activeRoute = configuredSession?.routeCandidates?.find(candidate => candidate.relay.url === configuredUrl)?.role
?? (configuredSession?.routeCandidates?.length ? null : configuredSession?.endpointRole ?? inferEndpointRole(configuredUrl))
if (!resolveRemoteOrNull(args) && configuredSession?.routeCandidates?.length) {
const candidates = configuredSession.preferSecureRoutes
? secureFirstCandidates(configuredSession.routeCandidates)
: configuredSession.routeCandidates
try {
const route = await probeCandidatesByPriority(candidates, { sessionToken: configuredSession.token })
url = route.relay.url
useSessionHeader = route.role.toLowerCase() === 'plugin_proxy' && !route.broker
if (route.broker && route.proxy) {
if (!route.proxy.certificateDerBase64) throw new Error('Hermes Reach route is missing its paired certificate')
brokerRoute = { url: route.broker.url, hostId: route.broker.hostId, credentialKind: route.broker.credentialKind, token: route.broker.token, innerUrl: route.relay.url, innerPinSha256: route.proxy.pinSha256, innerCertificateDerBase64: route.proxy.certificateDerBase64 }
}
activeRoute = route.broker ? 'outbound_broker' : route.role
log.info({ event: 'route_selected', configured_url: configuredUrl, url, role: route.role })
} catch (e) {
log.warn({
event: 'route_probe_failed',
configured_url: configuredUrl,
message: e instanceof Error ? e.message : String(e),
fallback_url: configuredUrl
})
}
}
// Resolve credentials: daemon takes ONLY --token or stored session. No
// pairing code path (the daemon can't do the one-time code → token
// trade safely — the token should already be stored). No interactive
// fallback (headless).
const argToken = typeof args.flags.token === 'string' ? args.flags.token : undefined
const envToken = process.env.HERMES_RELAY_TOKEN
const stored = await getSession(url)
const stored = configuredSession ?? await getSession(url)
const token = argToken ?? envToken ?? stored?.token
if (!token) {
@@ -752,6 +988,7 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
url,
message: 'no session token. Run `hermes-relay pair --remote <url>` once, then start the daemon.'
})
await instanceLock.release()
return 1
}
@@ -760,7 +997,7 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
// connectivity itself a privileged operation.
const consented = stored?.toolsConsented === true
const allowToolsFlag = !!args.flags['allow-tools']
const storedAccessMode = await getHostAccessMode(url)
const storedAccessMode = await getHostAccessMode(configuredUrl)
const accessMode = effectiveHostAccessMode(storedAccessMode, stored?.toolsConsented === true)
const toolsEnabled = consented || allowToolsFlag || accessMode !== 'ask'
@@ -782,6 +1019,8 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
pid: process.pid,
process_name: path.basename(process.execPath),
url,
configured_url: configuredUrl,
active_route: activeRoute ?? undefined,
state: 'starting',
started_at: nowSec(),
updated_at: nowSec(),
@@ -802,6 +1041,8 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
const relay = new RelayTransport({
url,
sessionToken: token,
sessionHeader: useSessionHeader,
broker: brokerRoute,
...desktopRelayIdentity()
})
@@ -814,17 +1055,26 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
? (info as { attempt?: number; delayMs?: number })
: {}
log.warn({ event: 'reconnecting', attempt: attempt ?? null, delay_ms: delayMs ?? null })
updateStatus({ state: 'reconnecting', last_event: 'reconnecting' })
const retryAt = nowSec() + Math.ceil((delayMs ?? 0) / 1000)
updateStatus({ state: 'reconnecting', last_event: 'reconnecting', reconnect_attempt: attempt ?? null, retry_at: retryAt, last_error: 'Relay connection interrupted' })
if ((attempt ?? 1) === 1) {
void appendAudit({
ts: Date.now(), kind: 'connection.state', tool: 'daemon.reconnecting', category: 'system', ok: false,
host_url: configuredUrl, summary: 'Automatic reconnect started', error: 'Relay connection interrupted'
})
}
})
relay.on('reconnected', () => {
log.info({ event: 'reconnected' })
updateStatus({ state: 'connected', last_event: 'reconnected' })
updateStatus({ state: 'connected', last_event: 'reconnected', reconnect_attempt: null, retry_at: null, last_error: null })
void appendAudit({ ts: Date.now(), kind: 'connection.state', tool: 'daemon.reconnected', category: 'system', ok: true, host_url: configuredUrl, summary: 'Relay tunnel restored' })
})
relay.on('exit', (code: unknown) => {
// Transport gave up (auth.fail, reconnect gate returned false, or
// reconnect attempts exhausted). Daemon exits non-zero so the
// service manager decides whether to restart.
log.error({ event: 'transport_exited', code: typeof code === 'number' ? code : null })
void appendAudit({ ts: Date.now(), kind: 'connection.state', tool: 'daemon.disconnected', category: 'system', ok: false, host_url: configuredUrl, summary: 'Relay transport stopped', error: 'Automatic reconnect stopped' })
// Defer exit so the log line flushes before the process dies.
setImmediate(() => process.exit(1))
})
@@ -834,11 +1084,14 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
const outcome = await relay.whenAuthResolved()
if (!outcome.ok) {
log.error({ event: 'auth_failed', reason: outcome.reason })
updateStatus({ state: 'stopped', last_event: 'auth_failed', last_error: outcome.reason, reconnect_attempt: null, retry_at: null })
void appendAudit({ ts: Date.now(), kind: 'connection.state', tool: 'daemon.auth_failed', category: 'system', ok: false, host_url: configuredUrl, summary: 'Relay authentication failed', error: outcome.reason })
try {
relay.kill()
} catch {
/* ignore */
}
await instanceLock.release()
return 1
}
@@ -847,7 +1100,7 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
server_version: relay.serverVersion ?? null,
transport: relay.authMeta?.transportHint ?? null
})
updateStatus({ state: 'connected', server_version: relay.serverVersion ?? null, last_event: 'authed' })
updateStatus({ state: 'connected', server_version: relay.serverVersion ?? null, last_event: 'authed', reconnect_attempt: null, retry_at: null, last_error: null })
// Signal downstream handlers that we're running headless. The router
// also checks this env var in its detectInteractive() fallback, so any
@@ -865,10 +1118,10 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
const capabilities = effectiveHostCapabilityPolicies(
storedAccessMode,
stored?.toolsConsented === true,
await getHostCapabilityPolicies(url)
await getHostCapabilityPolicies(configuredUrl)
)
configureComputerUseRuntime({
url,
url: configuredUrl,
computerUseConsented: computerUseEnabled,
consentSource: consented ? 'stored' : toolsEnabled ? 'override' : 'none',
accessMode,
@@ -886,8 +1139,14 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
expires_at: grant?.expires_at ?? null,
reason: grant?.reason
})
const restoreGrantListener = setComputerGrantChangeListener(grant => {
const restoreGrantListener = setComputerGrantChangeListener((grant, controlSessionId) => {
updateStatus({ computer_grant: toDaemonGrantStatus(grant), last_event: 'grant_changed' })
if (!grant && controlSessionId) {
void closeCuaControlSession(controlSessionId, 'computer grant ended')
}
})
const restoreControlLifecycleListener = setComputerControlLifecycleListener(computerControl => {
updateStatus({ computer_control: computerControl })
})
let cancellationCheckRunning = false
@@ -897,10 +1156,10 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
try {
const request = await consumeComputerGrantCancellation()
if (request) {
const result = cancelComputerGrant(request.reason)
const result = { cancelled: cancelAllComputerGrants(request.reason) }
log.info({ event: 'computer_grant_cancelled_locally', reason: request.reason, result })
} else {
getActiveComputerGrant()
expireComputerControlSessions()
}
} catch (error) {
log.warn({ event: 'computer_grant_control_failed', message: rpcErrorMessage(error) })
@@ -988,8 +1247,9 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
clearInterval(statusHeartbeat)
clearInterval(grantControlInterval)
restoreGrantListener()
restoreControlLifecycleListener()
try {
await clearDaemonStatus()
await clearDaemonStatus(process.pid)
} catch {
/* ignore */
}
@@ -1013,6 +1273,11 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
} catch {
/* ignore */
}
try {
await instanceLock.release()
} catch (error) {
log.warn({ event: 'instance_lock_release_failed', message: rpcErrorMessage(error) })
}
}
setupGracefulExit({ cleanups: [cleanup] })
@@ -1034,6 +1299,7 @@ export {
daemonStatusIsReady as __daemonStatusIsReadyForTests,
buildDaemonChildArgs as __buildDaemonChildArgsForTests,
buildElevationLaunchPlan as __buildElevationLaunchPlanForTests,
acquireProcessLock as __acquireProcessLockForTests,
quoteWindowsArgument as __quoteWindowsArgumentForTests,
makeLogger as __makeLoggerForTests,
readDetachedStartupFailure as __readDetachedStartupFailureForTests,
+40 -3
View File
@@ -18,6 +18,9 @@ import {
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec, unknownSubcommand } from '../lib/usage.js'
import { deleteSession, getSession, listSessions, saveSession } from '../remoteSessions.js'
import { candidateDisplayLabel, displayLabel, inferEndpointRole } from '../endpoint.js'
import { probeCandidate, secureFirstCandidates } from '../pairingQr.js'
import { describeTransportSecurity } from '../transportSecurity.js'
const HOSTS_USAGE: UsageSpec = {
name: 'hosts',
@@ -26,6 +29,7 @@ const HOSTS_USAGE: UsageSpec = {
'hosts [list] [--json]',
'hosts select <relay-url>',
'hosts rename <relay-url> <name>',
'hosts test [--remote <relay-url>] [--json]',
'hosts forget <relay-url> --yes',
'hosts access <restricted|ask-every-time|standard|full-access> [--remote <url>] [--yes]',
'hosts capability <commands|files|screen-input|usb|microphone|camera> <disabled|ask|allow> [--remote <url>] [--yes]'
@@ -34,6 +38,7 @@ const HOSTS_USAGE: UsageSpec = {
{ verb: 'list', desc: 'List locally paired Hermes hosts (default)' },
{ verb: 'select <url>', desc: 'Choose the host used by the tray and daemon' },
{ verb: 'rename <url> <name>', desc: 'Set a local display name for a paired host' },
{ verb: 'test', desc: 'Test saved routes and report the best available connection' },
{ verb: 'forget <url>', desc: 'Remove the local pairing, alias, and access policy' },
{ verb: 'access <mode>', desc: 'Set a Restricted, Ask Every Time, Standard, or Full Access preset' },
{ verb: 'capability <name> <mode>', desc: 'Set one capability; exact presets are recognized automatically' }
@@ -61,6 +66,7 @@ export interface LocalHostSummary {
is_active: boolean
access_mode: HostAccessMode
capabilities: CapabilityPolicies
broker_configured: boolean
}
function hostLabel(url: string): string {
@@ -96,11 +102,12 @@ async function localHosts(): Promise<LocalHostSummary[]> {
url,
host: aliases[url] ?? hostLabel(url),
server_version: session.serverVersion,
endpoint_role: session.endpointRole ?? null,
endpoint_role: session.endpointRole ?? inferEndpointRole(url),
paired_at: session.pairedAt,
is_active: url === active,
access_mode: effectiveHostAccessMode(storedMode, legacyConsented),
capabilities: effectiveHostCapabilityPolicies(storedMode, legacyConsented, await getHostCapabilityPolicies(url))
capabilities: effectiveHostCapabilityPolicies(storedMode, legacyConsented, await getHostCapabilityPolicies(url)),
broker_configured: session.routeCandidates?.some(candidate => ['outbound_broker', 'relay_broker', 'broker'].includes(candidate.role.toLowerCase())) ?? false
}
})).then(hosts => hosts.sort((a, b) =>
Number(b.is_active) - Number(a.is_active) || b.paired_at - a.paired_at || a.url.localeCompare(b.url)
@@ -139,13 +146,42 @@ async function listHosts(args: ParsedArgs): Promise<number> {
for (const host of hosts) {
process.stdout.write(
` ${host.is_active ? '*' : ' '} ${host.host} ${displayAccessMode(host.access_mode)}\n` +
t.muted(` ${host.url}${host.endpoint_role ? ` (${host.endpoint_role})` : ''}`) + '\n' +
t.muted(` ${host.url}${host.endpoint_role ? ` (${displayLabel(host.endpoint_role)})` : ''}`) + '\n' +
t.muted(` Commands: ${host.capabilities.commands} · Files: ${host.capabilities.files} · Screen/input: ${host.capabilities.screen_input} · USB: ${host.capabilities.usb}`) + '\n'
)
}
return 0
}
async function testHostRoutes(args: ParsedArgs): Promise<number> {
const requested = typeof args.flags.remote === 'string' ? args.flags.remote.trim() : ''
const url = requested || await getActiveDesktopRelayUrl() || ''
const session = url ? await getSession(url) : null
if (!url || !session) {
process.stderr.write('error: select or pass a locally paired Hermes host\n')
return 1
}
const candidates = secureFirstCandidates(session.routeCandidates?.length ? session.routeCandidates : [{
role: session.endpointRole ?? 'custom', priority: 0,
api: { host: new URL(url).hostname, port: Number(new URL(url).port || (url.startsWith('wss:') ? 443 : 80)), tls: url.startsWith('wss:') },
relay: { url }
}])
const results = await Promise.all(candidates.map(async candidate => {
const result = await probeCandidate(candidate, AbortSignal.timeout(5_000), session.token)
const security = describeTransportSecurity(candidate.relay.url, candidate.role)
return { role: candidate.role, label: candidateDisplayLabel(candidate), url: candidate.broker?.url ?? candidate.relay.url, reachable: result.reachable, elapsed_ms: result.elapsedMs, encrypted: security.encrypted, security: candidate.broker ? 'Reachability only; inner Secure Link verifies on connect' : security.label, error: result.error ?? null }
}))
const best = results.find(result => result.reachable) ?? null
if (args.flags.json) process.stdout.write(JSON.stringify({ ok: best !== null, host_url: url, best, routes: results }, null, 2) + '\n')
else {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
process.stdout.write(t.bold('Hermes connection test') + '\n')
for (const result of results) process.stdout.write(` ${result.reachable ? t.ok('●') : t.err('●')} ${result.label} ${result.security} ${result.reachable ? `${result.elapsed_ms}ms` : result.error ?? 'unreachable'}\n`)
process.stdout.write(best ? t.okLine(`Best route: ${best.label}`) + '\n' : t.errLine('No saved route is reachable.') + '\n')
}
return best ? 0 : 1
}
async function selectHost(args: ParsedArgs): Promise<number> {
const url = args.positional[0]?.trim()
if (!url) {
@@ -290,6 +326,7 @@ export async function hostsCommand(args: ParsedArgs): Promise<number> {
if (subcommand === 'list') return listHosts(args)
if (subcommand === 'select') return selectHost(args)
if (subcommand === 'rename') return renameHost(args)
if (subcommand === 'test') return testHostRoutes(args)
if (subcommand === 'forget') return forgetHost(args)
if (subcommand === 'access') return setAccess(args)
if (subcommand === 'capability') return setCapability(args)
+56 -7
View File
@@ -24,12 +24,15 @@ import {
import {
payloadToRelayCandidates,
probeCandidatesByPriority,
relayPairingCodeFromPayload
relayPairingCodeFromPayload,
secureFirstCandidates
} from '../pairingQr.js'
import { DEFAULT_RELAY_PORT, normalizeRelayUrl, resolveFirstRunUrl } from '../relayUrlPrompt.js'
import { saveSession } from '../remoteSessions.js'
import { ensureToolsConsent } from '../tools/consent.js'
import { RelayTransport } from '../transport/RelayTransport.js'
import { candidateDisplayLabel, displayLabel, inferEndpointRole } from '../endpoint.js'
import type { BrokerRouteConfig } from '../transport/BrokerRelaySocket.js'
const PAIR_USAGE: UsageSpec = {
name: 'pair',
@@ -41,6 +44,7 @@ const PAIR_USAGE: UsageSpec = {
desc: 'Paste a full QR payload or hermes-relay://pair invite (recommended — probes endpoints)'
},
{ flag: '--remote <url>', desc: 'Relay URL (with [CODE] or an interactive prompt)' },
{ flag: '--prefer-direct', desc: 'Respect invite order instead of preferring secure routes' },
{ flag: '--code <code>', desc: '6-char pairing code (or pass it as the positional arg)' },
{
flag: '--grant-tools',
@@ -73,6 +77,27 @@ interface PairTarget {
code: string
/** Active-endpoint role if this came from a multi-endpoint QR probe. */
endpointRole: string | null
routeCandidates?: ReturnType<typeof payloadToRelayCandidates>
preferSecureRoutes?: boolean
certPin?: string
broker?: BrokerRouteConfig
}
export function rankPairingCandidates(candidates: ReturnType<typeof payloadToRelayCandidates>, preferSecure: boolean) {
return preferSecure ? secureFirstCandidates(candidates) : candidates
}
export function brokerRouteForCandidate(candidate: ReturnType<typeof payloadToRelayCandidates>[number]): BrokerRouteConfig | undefined {
if (!candidate.broker || !candidate.proxy?.certificateDerBase64) return undefined
return {
url: candidate.broker.url,
hostId: candidate.broker.hostId,
credentialKind: candidate.broker.credentialKind,
token: candidate.broker.token,
innerUrl: candidate.relay.url,
innerPinSha256: candidate.proxy.pinSha256,
innerCertificateDerBase64: candidate.proxy.certificateDerBase64,
}
}
async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error: string }> {
@@ -97,12 +122,17 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: e instanceof Error ? e.message : String(e) }
}
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const preferSecure = args.flags['prefer-direct'] !== true
process.stderr.write(t.bold(`Probing ${candidates.length} endpoint(s)…`) + '\n')
let winner
try {
winner = await probeCandidatesByPriority(candidates, {
// Hermes Secure Link tunnels the normal first pairing-code frame. The
// QR pin is the operator trust ceremony, so secure-only invites can
// bootstrap without falling back to a plain/direct route.
const rankedCandidates = rankPairingCandidates(candidates, preferSecure)
winner = await probeCandidatesByPriority(rankedCandidates, {
onProbe: (ev) => {
const label = `[${ev.index}/${ev.total}] ${ev.candidate.role} ${ev.candidate.relay.url}`
const label = `[${ev.index}/${ev.total}] ${candidateDisplayLabel(ev.candidate)} ${ev.candidate.relay.url}`
if (ev.phase === 'result' && ev.reachable) {
process.stderr.write(` ${t.okLine(label)} ${t.muted(`${ev.elapsedMs}ms`)}\n`)
} else if (ev.phase === 'result') {
@@ -116,12 +146,17 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: `no endpoints reachable: ${e instanceof Error ? e.message : String(e)}` }
}
process.stderr.write(
` ${t.cyan(SYMBOLS.arrow)} picked ${t.bold(winner.role)} endpoint ${winner.relay.url}\n`
` ${t.cyan(SYMBOLS.arrow)} picked ${t.bold(candidateDisplayLabel(winner))} endpoint ${winner.relay.url}\n`
)
const broker = brokerRouteForCandidate(winner)
return {
url: winner.relay.url,
code: pairingCode,
endpointRole: winner.role
endpointRole: winner.role,
routeCandidates: candidates,
preferSecureRoutes: preferSecure,
certPin: winner.proxy?.pinSha256,
...(broker ? { broker } : {})
}
}
@@ -163,7 +198,7 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: e instanceof Error ? e.message : String(e) }
}
}
return { url, code, endpointRole: null }
return { url, code, endpointRole: inferEndpointRole(url) }
}
export async function pairCommand(args: ParsedArgs): Promise<number> {
@@ -192,6 +227,8 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
const relay = new RelayTransport({
url: target.url,
pairingCode: target.code,
expectedCertPin: target.certPin,
broker: target.broker,
...desktopRelayIdentity()
})
@@ -199,6 +236,12 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
const outcome = await relay.whenAuthResolved()
if (outcome.ok) {
const persistedRoutes = target.routeCandidates?.flatMap(candidate => {
if (!candidate.broker) return candidate
const durable = outcome.meta.routeCredential
if (!durable) return []
return { ...candidate, broker: { ...candidate.broker, url: durable.brokerUrl, hostId: durable.hostId, credentialKind: 'route' as const, token: durable.token, expiresAt: durable.expiresAt } }
})
// Fold --auto-grant-tools into the initial save so the consent flag and
// the token land atomically. The interactive --grant-tools path runs
// ensureToolsConsent() below, which writes its own follow-up save.
@@ -206,6 +249,9 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
grants: outcome.meta.grants,
ttlExpiresAt: outcome.meta.ttlExpiresAt,
endpointRole: target.endpointRole,
routeCandidates: persistedRoutes,
preferSecureRoutes: target.preferSecureRoutes,
certPin: target.certPin,
initializeAccessPolicy: true,
...(autoGrant ? { toolsConsented: true } : {})
})
@@ -213,7 +259,10 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
process.stdout.write(t.muted(` server: ${outcome.serverVersion ?? '?'}`) + '\n')
process.stdout.write(t.muted(` relay: ${target.url}`) + '\n')
if (target.endpointRole) {
process.stdout.write(t.muted(` route: ${target.endpointRole}`) + '\n')
process.stdout.write(t.muted(` route: ${target.broker ? 'Hermes Reach (experimental)' : displayLabel(target.endpointRole)}`) + '\n')
if (target.broker) {
process.stdout.write(t.warnLine('Experimental route selected; Tailscale or a direct TLS route is recommended for normal use.') + '\n')
}
}
if (autoGrant) {
+4 -3
View File
@@ -9,6 +9,7 @@ import type { ParsedArgs } from '../cli.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec } from '../lib/usage.js'
import { listSessions, type RemoteSessionRecord } from '../remoteSessions.js'
import { displayLabel } from '../endpoint.js'
const STATUS_USAGE: UsageSpec = {
name: 'status',
@@ -60,7 +61,7 @@ export async function statusCommand(args: ParsedArgs): Promise<number> {
: Object.fromEntries(
Object.entries(sessions).map(([url, rec]) => [
url,
{ ...rec, token: '(redacted)' }
{ ...rec, token: '(redacted)', routeCandidates: rec.routeCandidates?.map(candidate => candidate.broker ? { ...candidate, broker: { ...candidate.broker, token: '(redacted)' } } : candidate) }
])
)
process.stdout.write(JSON.stringify(out, null, 2) + '\n')
@@ -93,8 +94,8 @@ export async function statusCommand(args: ParsedArgs): Promise<number> {
kv('desktop', `${t.statusDot(!!rec.toolsConsented)} tools=${rec.toolsConsented ? 'yes' : 'no'}, computer-use=${computerUse}`) + '\n'
)
const role = parseRole(rec.endpointRole)
if (role) {
process.stdout.write(kv('route', roleLabel(role)) + '\n')
if (rec.endpointRole) {
process.stdout.write(kv('route', role ? roleLabel(role) : displayLabel(rec.endpointRole)) + '\n')
}
if (rec.grants && Object.keys(rec.grants).length > 0) {
const formatted = Object.entries(rec.grants)
+64
View File
@@ -57,6 +57,37 @@ export interface EndpointCandidate {
priority: number
api: ApiEndpoint
relay: RelayEndpoint
/** Native plugin secure-proxy advertisement. Preserved even when the
* desktop currently consumes only its relay WSS path. */
proxy?: {
url: string
transportHint?: string
pinSha256: string
certificateDerBase64?: string
surfaces?: string[]
}
security?: string
recommended?: boolean
/** Experimental routes are supported for explicit evaluation but are
* never presented as the default remote-access recommendation. */
experimental?: boolean
broker?: {
url: string
hostId: string
credentialKind: 'bootstrap' | 'route'
token: string
expiresAt?: string | number | null
}
}
export function candidateDisplayLabel(candidate: Pick<EndpointCandidate, 'role' | 'broker'> & Partial<Pick<EndpointCandidate, 'relay'>>): string {
const role = candidate.role.toLowerCase()
if (candidate.broker && (role === 'outbound_broker' || role === 'broker' || role === 'relay_broker')) return 'Hermes Reach (experimental)'
// Older session files used the generic `custom` role even for ordinary
// private-address routes. Keep named operator-defined roles intact, but
// classify that legacy placeholder from its actual relay URL.
if (role === 'custom' && candidate.relay?.url) return displayLabel(inferEndpointRole(candidate.relay.url))
return displayLabel(candidate.role)
}
/**
@@ -96,6 +127,9 @@ export function isKnownRole(role: string): boolean {
* exactly what they labeled it.
*/
export function displayLabel(role: string): string {
const normalized = role.toLowerCase()
if (normalized === 'plugin_proxy') return 'Hermes Secure Link'
if (normalized === 'outbound_broker' || normalized === 'relay_broker' || normalized === 'broker') return 'Hermes Reach (experimental)'
switch (parseRawRole(role)) {
case 'lan':
return 'LAN'
@@ -108,6 +142,36 @@ export function displayLabel(role: string): string {
}
}
/** Infer a built-in role for legacy/direct sessions that did not persist one. */
export function inferEndpointRole(rawUrl: string): EndpointRole {
try {
const parsed = new URL(rawUrl)
const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase()
const octets = host.split('.').map(Number)
const ipv4 = octets.length === 4 && octets.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
if (host.endsWith('.ts.net') || (ipv4 && octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127)) {
return 'tailscale'
}
if (
host === 'localhost' || host.endsWith('.local') || host === '::1' ||
host.startsWith('fc') || host.startsWith('fd') ||
/^(fe8|fe9|fea|feb)/.test(host) ||
(ipv4 && (
octets[0] === 10 || octets[0] === 127 ||
(octets[0] === 169 && octets[1] === 254) ||
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
(octets[0] === 192 && octets[1] === 168)
))
) {
return 'lan'
}
return 'public'
} catch {
return 'custom'
}
}
/**
* Type guard — is this value shaped like an `ApiEndpoint`? Used by the
* pairing parser to filter malformed candidates without throwing.
+145 -3
View File
@@ -9,7 +9,8 @@
//
// Best-effort by design: a logging failure must never break a tool dispatch.
import { appendFile, mkdir, readFile, rename, stat } from 'node:fs/promises'
import { appendFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -17,7 +18,7 @@ export interface AuditEntry {
/** Epoch milliseconds when the command completed. */
ts: number
/** Stable event type for consumers that do not want to infer it from fields. */
kind?: 'tool.completed'
kind?: 'tool.completed' | 'connection.state'
tool: string
category?: AuditCategory
ok: boolean
@@ -25,6 +26,20 @@ export interface AuditEntry {
request_id?: string
/** Relay identity that issued the action, when known. */
host_url?: string
relay_session_id?: string
requester_device_id?: string
run_id?: string
target_device_id?: string
backend?: 'cua' | 'legacy_compat' | 'system_capture'
dispatch?: 'background' | 'foreground_compatibility'
control_session_id?: string
target_app?: string
target_title?: string
target_pid?: number
target_window_id?: number
action?: string
verification?: 'snapshot_captured' | 'not_requested' | 'failed'
phase?: 'structured_primary' | 'explicit_compatibility' | 'pre_session_safe_fallback'
/** Handler wall time, excluding relay transport latency. */
duration_ms?: number
/** Process exit code when the handler returns one. Non-zero is attention-worthy. */
@@ -45,6 +60,11 @@ export interface AuditEntry {
/** Short success summary (path / exit code / first stdout line). */
summary?: string
error?: string
/** Opaque local evidence identifier. Screenshot pixels never enter JSONL. */
screenshot_evidence_id?: string
screenshot_mime_type?: 'image/png'
screenshot_width?: number
screenshot_height?: number
}
export type AuditCategory = 'command' | 'files' | 'screen' | 'input' | 'devices' | 'system' | 'other'
@@ -52,11 +72,109 @@ export type AuditCategory = 'command' | 'files' | 'screen' | 'input' | 'devices'
/** Rotate the log once it crosses ~1 MB, keeping a single `.1` backup. */
const MAX_BYTES = 1_000_000
const MAX_DETAIL_BYTES = 32_768
const MAX_SCREENSHOT_BYTES = 10_000_000
const MAX_SCREENSHOT_FILES = 20
export function auditLogPath(): string {
return join(homedir(), '.hermes', 'desktop-audit.jsonl')
}
export function auditEvidenceDirectory(): string {
return process.env.HERMES_RELAY_ACTIVITY_EVIDENCE_DIR ?? join(homedir(), '.hermes', 'activity-evidence')
}
type ScreenshotEvidence = Pick<AuditEntry, 'screenshot_evidence_id' | 'screenshot_mime_type' | 'screenshot_width' | 'screenshot_height'>
function screenshotPayload(result: unknown): { base64: string; width?: number; height?: number } | null {
if (!result || typeof result !== 'object' || Array.isArray(result)) return null
const record = result as Record<string, unknown>
const nested = record.after_screenshot
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
const found = screenshotPayload(nested)
if (found) return found
}
const base64 = typeof record.screenshot_base64 === 'string'
? record.screenshot_base64
: typeof record.bytes_base64 === 'string'
? record.bytes_base64
: null
if (!base64) return null
const display = record.display && typeof record.display === 'object' && !Array.isArray(record.display)
? record.display as Record<string, unknown>
: null
const width = typeof record.screenshot_width === 'number' ? record.screenshot_width
: typeof display?.width === 'number' ? display.width : undefined
const height = typeof record.screenshot_height === 'number' ? record.screenshot_height
: typeof display?.height === 'number' ? display.height : undefined
return { base64, width, height }
}
async function pruneScreenshotEvidence(directory: string, retentionDays: number): Promise<void> {
const now = Date.now()
const maxAgeMs = retentionDays * 24 * 60 * 60 * 1000
const records = await Promise.all((await readdir(directory, { withFileTypes: true }))
.filter(entry => entry.isFile() && /^[a-f0-9]{32}\.png$/.test(entry.name))
.map(async entry => ({ name: entry.name, stats: await stat(join(directory, entry.name)) })))
records.sort((left, right) => right.stats.mtimeMs - left.stats.mtimeMs)
await Promise.all(records
.filter((record, index) => index >= MAX_SCREENSHOT_FILES || now - record.stats.mtimeMs > maxAgeMs)
.map(record => unlink(join(directory, record.name)).catch(() => {})))
}
export async function pruneAuditScreenshotEvidence(retentionDays: 1 | 7 | 30): Promise<void> {
try {
await pruneScreenshotEvidence(auditEvidenceDirectory(), retentionDays)
} catch {
/* Missing or unreadable evidence is equivalent to an empty store. */
}
}
/** Retain a bounded, local screenshot for the activity evidence viewer. The
* audit log stores only an opaque identifier; clearing activity removes the
* evidence directory too. */
export async function persistAuditScreenshot(result: unknown, requestId: string, retentionDays = 7): Promise<ScreenshotEvidence> {
const payload = screenshotPayload(result)
if (!payload) return {}
let bytes: Buffer
try {
bytes = Buffer.from(payload.base64, 'base64')
} catch {
return {}
}
if (!bytes.length || bytes.length > MAX_SCREENSHOT_BYTES || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') return {}
const id = createHash('sha256').update(`${requestId}:${Date.now()}`).digest('hex').slice(0, 32)
const directory = auditEvidenceDirectory()
try {
await mkdir(directory, { recursive: true })
await writeFile(join(directory, `${id}.png`), bytes, { mode: 0o600, flag: 'wx' })
await pruneScreenshotEvidence(directory, retentionDays)
return {
screenshot_evidence_id: id,
screenshot_mime_type: 'image/png',
...(payload.width ? { screenshot_width: payload.width } : {}),
...(payload.height ? { screenshot_height: payload.height } : {})
}
} catch {
return {}
}
}
export async function clearAuditScreenshotEvidence(): Promise<void> {
const { rm } = await import('node:fs/promises')
await rm(auditEvidenceDirectory(), { recursive: true, force: true })
}
export async function auditScreenshotEvidenceStatus(): Promise<{ count: number; bytes: number }> {
try {
const records = await Promise.all((await readdir(auditEvidenceDirectory(), { withFileTypes: true }))
.filter(entry => entry.isFile() && /^[a-f0-9]{32}\.png$/.test(entry.name))
.map(entry => stat(join(auditEvidenceDirectory(), entry.name))))
return { count: records.length, bytes: records.reduce((total, value) => total + value.size, 0) }
} catch {
return { count: 0, bytes: 0 }
}
}
export async function appendAudit(entry: AuditEntry): Promise<void> {
const path = auditLogPath()
try {
@@ -127,7 +245,8 @@ function boundedText(value: string): { text: string; truncated: boolean } {
* bodies, environment values, or unbounded process output. */
export function auditDetails(
args: Record<string, unknown>,
result?: unknown
result?: unknown,
options: { redactComputerContent?: boolean } = {}
): Pick<AuditEntry, 'request_detail' | 'stdout' | 'stderr' | 'result_detail' | 'request_truncated' | 'stdout_truncated' | 'stderr_truncated' | 'result_truncated'> {
const safeRequest: Record<string, unknown> = {}
for (const key of [
@@ -141,6 +260,29 @@ export function auditDetails(
request_detail: request.text,
request_truncated: request.truncated || undefined
}
if (options.redactComputerContent) {
if (result && typeof result === 'object' && !Array.isArray(result)) {
const record = result as Record<string, unknown>
const target = record.target && typeof record.target === 'object' && !Array.isArray(record.target)
? record.target as Record<string, unknown>
: {}
const safeResult = {
backend: record.backend,
action: record.action,
status: record.status,
code: record.code,
target: {
pid: target.pid,
windowId: target.windowId
},
redacted: true
}
const value = boundedText(JSON.stringify(safeResult, null, 2))
details.result_detail = value.text
details.result_truncated = value.truncated || undefined
}
return details
}
if (!result || typeof result !== 'object') {
if (result !== undefined) {
const value = boundedText(String(result))

Some files were not shown because too many files have changed in this diff Show More