Compare commits
99
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
447ec356d7 | ||
|
|
ab359e5efb | ||
|
|
86b8161cb7 | ||
|
|
e401fdb0c7 | ||
|
|
d4325d5aab | ||
|
|
c734d75484 | ||
|
|
0411804780 | ||
|
|
8f89c2841d | ||
|
|
933c1842a0 | ||
|
|
dfe1b53327 | ||
|
|
d36580a983 | ||
|
|
2d178ff884 | ||
|
|
d61955f82a | ||
|
|
adec6ed2c0 | ||
|
|
e9e44c8bb2 | ||
|
|
c6b0732a02 | ||
|
|
d919115788 | ||
|
|
49da085ae8 | ||
|
|
889b6f0858 | ||
|
|
5100c524f6 | ||
|
|
c609ae867f | ||
|
|
107f8c7720 | ||
|
|
8963e4fafd | ||
|
|
5d9624e2ef | ||
|
|
4b063d3fd7 | ||
|
|
9b9d7b654c | ||
|
|
a26e17e72c | ||
|
|
a3a6a9bb13 | ||
|
|
169bd09559 | ||
|
|
45d631e7ac | ||
|
|
eb6a6c95d2 | ||
|
|
3b102663c2 | ||
|
|
0e5fc4c606 | ||
|
|
c3189f2cbb | ||
|
|
0d6c3bd6b0 | ||
|
|
06d88ad40a | ||
|
|
8ae5b3fbc2 | ||
|
|
39b7a8f108 | ||
|
|
af6e167692 | ||
|
|
274bd6ae98 | ||
|
|
9fc55b379a | ||
|
|
559a0ffdc8 | ||
|
|
75bcd9180f | ||
|
|
9c995a443d | ||
|
|
7440ef2948 | ||
|
|
a88539bc59 | ||
|
|
b2ccfdc500 | ||
|
|
481c62ac59 | ||
|
|
5d415fbaf0 | ||
|
|
074b715055 | ||
|
|
f63ee8721e | ||
|
|
777bc80bcc | ||
|
|
9539975bb5 | ||
|
|
2863a1bc8f | ||
|
|
b0a7cf0494 | ||
|
|
76b4084310 | ||
|
|
2ace70c4fc | ||
|
|
4f52f371ba | ||
|
|
064c89bda4 | ||
|
|
0cb1e3642f | ||
|
|
cf4bf87242 | ||
|
|
9cbed21014 | ||
|
|
ce75c0fa01 | ||
|
|
bf2aece6e6 | ||
|
|
198da78fc8 | ||
|
|
986ce3b12b | ||
|
|
b53f757830 | ||
|
|
cdeccd69e4 | ||
|
|
bb72516bb5 | ||
|
|
3a51644342 | ||
|
|
51c0c7dee9 | ||
|
|
d383002583 | ||
|
|
e3aae829e1 | ||
|
|
5207ed4193 | ||
|
|
b46bb00ea8 | ||
|
|
b8dde409c5 | ||
|
|
ca7ded3939 | ||
|
|
db85a26c68 | ||
|
|
aa2595629d | ||
|
|
d79146dc90 | ||
|
|
eabc4dd328 | ||
|
|
e165bfeff3 | ||
|
|
40bcd796d1 | ||
|
|
57ae0c9456 | ||
|
|
9b31a16c89 | ||
|
|
f97bbdd395 | ||
|
|
722a294947 | ||
|
|
bbfb57b462 | ||
|
|
6db12a0bec | ||
|
|
f1de957848 | ||
|
|
cc01d9c8ad | ||
|
|
d574182d84 | ||
|
|
a328763da3 | ||
|
|
f53db68e7d | ||
|
|
eb9e570fc0 | ||
|
|
260f119637 | ||
|
|
d0fa2ea39d | ||
|
|
a1c74b1567 | ||
|
|
7c45acd38d |
@@ -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
|
||||
|
||||
+94
-1
@@ -6,10 +6,103 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.9.0] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Android session browsing matches Hermes Desktop's recent organization model.** The primary session drawer can toggle between the active profile and all profiles, group by recency, project, status, or profile, order by supported session metrics, and narrow rows by status, project, profile, or pull-request state without collapsing duplicate IDs across profile stores. Named profiles receive stable identity-color badges with locally persisted color overrides.
|
||||
- **Android can edit current Hermes profiles through the standard Gateway.** The Profile Inspector capability-gates `profiles.describe` and `profiles.configure`, keeps Relay-only memory editing and older-Hermes fallback intact, and reports partial section saves without discarding failed drafts.
|
||||
- **Android sessions show their coding context when Hermes supplies it.** Session rows can display repository, Git branch, and the current state of the pull request created by that session while older hosts remain unchanged.
|
||||
- Android Manage can now finish host-owned backup workflows, edit or remove learning nodes with explicit recovery guidance, configure and activate memory providers, and complete profile-scoped WhatsApp QR onboarding through the authenticated upstream Dashboard contracts.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android network clients shut down safely during route changes.** Replacing an authenticated Dashboard client now moves OkHttp connection-pool eviction off the main thread, preventing a live TLS socket close from crashing the app with `NetworkOnMainThreadException`. (#334)
|
||||
- **Android preserves authoritative Gateway outcomes.** Protected-file cards cannot offer forbidden persistent scopes, compression no-ops show the server result, bounded resume failures do not create context-free replacement sessions, and edit/regenerate retains durable row identities across consecutive rewinds.
|
||||
- **Android routes and uploads against live upstream truth.** Multiplex API fallback trusts `served_profiles` instead of installed profiles, and generic documents carry the Gateway-issued `@file:` reference into ordinary and queued prompts.
|
||||
- **Android clarify cards preserve upstream decision semantics.** Multi-select prompts keep independent selections and submit one exact list, while server expiry events—not an invented local deadline—retire unanswered cards.
|
||||
- **Android keeps profile management and retained automation truthful.** Custom Endpoint list and mutation routes now follow the selected Hermes profile, while completed one-shot cron jobs show their retained outcome and expose only valid Runs/Delete actions.
|
||||
- **Android and Relay recover more generated media reliably.** Android accepts upstream-valid wrapped, punctuated, adjacent, spaced, and Windows `MEDIA:` markers without consuming fenced examples, and Relay translates Docker-visible workspace, home, cache, and configured-mount paths before applying its existing credential, sandbox, and size checks.
|
||||
- **Android keeps cross-profile sessions with their owning agent.** Opening a session from All Profiles hydrates, resumes, sends, and renders with that session's profile without changing the global profile selection; New Chat from that view starts with the default profile.
|
||||
- **Android reactions and standard voice follow the active conversation.** Reactions resolve durable rows for both user and assistant messages, while Vanilla Hermes voice remains on the authenticated Gateway instead of requiring the optional API fallback.
|
||||
- **Android session navigation behaves predictably.** The drawer closes on outside taps, uses an ungrouped recent-session list by default, retains project grouping as an explicit option, and exposes secondary actions in All Profiles mode.
|
||||
|
||||
## [0.4.0-beta.3] - 2026-08-14
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows tray polling can no longer accumulate unbounded helper processes.** Grant discovery now uses lightweight local state, management refreshes are single-flight and visibility-aware, and child probes have hard timeouts, bounded output, tree cleanup, caching, and backoff. A dedicated bounded `tray.log` records sanitized operational failures without mixing them into daemon logs.
|
||||
- **Concurrent Desktop lifecycle requests cannot start duplicate daemons.** Cross-process lifecycle and runtime ownership locks serialize startup and recovery while preserving stale-owner cleanup.
|
||||
|
||||
## [1.8.0] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Official Hermes Desktop can surface Relay through its supported runtime Plugin SDK.** The unified plugin package now includes an opt-in, profile-scoped Desktop pane for Relay status, paired devices, bridge activity, media, pairing, revocation, and remote-access management. Loading, startup, reconnects, profile changes, and updates never open it; only labeled sidebar, status-bar, or command-palette actions register and reveal the movable native pane.
|
||||
|
||||
## [0.4.0-beta.2] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Desktop Activity now keeps inspectable local evidence.** Commands, files, devices, connection lifecycle, and computer control share a truthful event stepper with dedicated failure details; screenshot events can retain bounded local PNG evidence and open it in a larger borderless viewer. Settings controls retention as Off, 1 day, 7 days, or 30 days and shows local file usage.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Tunnel state stays responsive through interruption and retry.** The CLI UI distinguishes connected, reconnecting, and stopped states, exposes retry attempt/timing and a Retry now action, records connection failures and recovery in Activity, and shows compact connection cards only while the main UI is hidden.
|
||||
- **Windows CUA readiness no longer depends on the flaky whole-desktop health scan.** Hermes-Relay verifies the canonical runtime, manifest, required tools, daemon, and safe permission mode before starting structured sessions, while accessibility health remains an explicit CLI/UI diagnostic that can be rechecked without forcing the compatibility backend. This temporary workaround is scoped to the upstream fixed-timeout issue and keeps individual actions fail-closed.
|
||||
|
||||
## [0.4.0-beta.1] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- **CUA Driver is the preferred Windows structured-control engine.** New local settings prefer a verified CUA runtime for window-targeted background actions, fresh snapshot tokens, and optional per-session animated agent cursors without moving the physical pointer; Windows Input is the explicit compatibility backend and backend choice is fixed for each control session. Full-display observation remains on the read-only system capture path. CLI and UI can explicitly install, check, or update the canonical CUA package after verifying the upstream release manifest and installer checksum; nothing is bundled or updated automatically, driver telemetry stays off for Hermes sessions, and activity records contain only bounded, redacted control metadata.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows bundle updates fail closed when installed processes retain a binary lock.** Setup waits for the invoking CLI, quiesces the tray and its short-lived CLI children, checks every payload extraction before writing release metadata, preserves custom install directories, and returns a failure instead of reporting a mixed-version installation.
|
||||
- **CUA readiness follows the published driver contract.** Hermes accepts the documented `ok` health state, distinguishes an installed-but-degraded runtime from a missing installation, and constructs trusted Windows installer paths consistently across verification environments.
|
||||
|
||||
## [1.7.0] - 2026-08-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Hermes Secure Link provides self-hosted pinned TLS ingress.** Relay, API, and Dashboard namespaces share one operator-owned TLS endpoint while retaining their native authentication boundaries, QR-carried certificate continuity, explicit rotation, and fail-closed route validation.
|
||||
- **Hermes Reach is available for explicit experimentation.** The optional self-hosted rendezvous broker carries opaque Secure Link TLS records over outbound-only connections with bounded multiplexing, hashed credentials, replay protection, persistence, revocation, and no access to Hermes payloads.
|
||||
- **Remote-access management exposes supported reachability clearly.** Dashboard status and pairing metadata distinguish Tailscale reachability, Secure Link transport protection, direct routes, and experimental Reach without presenting the broker as a replacement for authentication.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Tailscale is the recommended remote route.** Pairing, Dashboard, documentation, and public site guidance present Tailscale as the easiest supported remote-access path; Reach remains disabled by default, advanced, and lower priority than supported routes.
|
||||
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients honor custom headers, custom CA bundles, standard CA environment precedence, and an explicitly warned development-only verification override.
|
||||
- **Voice Lab xAI sign-in uses device authorization.** The standalone login shows a verification URL and user code and polls for approval without requiring a loopback callback.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Phone delivery remains compatible with strict Hermes targets.** Version-tolerant parser and validator hooks retain older-host registration and exactly-once standalone delivery.
|
||||
- **Profile-owned Relay registrations stay isolated.** Current Hermes uses profile-scoped ownership and context-local profile homes while legacy hosts retain a guarded compatibility path.
|
||||
- **Phone is discoverable before its first historical session.** The Relay phone adapter publishes its configured home destination through Hermes' standard channel directory.
|
||||
|
||||
## [0.4.0-alpha.8] - 2026-08-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Windows management separates each Relay host from this PC.** Host detail owns identity, pairing, access, capabilities, authorized clients, re-pairing, and guarded removal; Settings owns local daemon lifecycle, startup, privilege, terminal, logs, diagnostics, updates, and Help & About.
|
||||
- **Desktop access uses clear host-scoped presets and capabilities.** Restricted, Ask Every Time, Standard, Full Access, and Custom remain explicit across commands, files, screen/input, USB, microphone, and camera controls.
|
||||
- **Activity drilldown preserves bounded execution evidence.** Overview shows the latest three events and detail views expose request, output, result, exit, duration, and truncation metadata without copying sensitive inputs.
|
||||
- **Connection presentation shows the live Agent-to-PC path.** Host selection, bidirectional packet motion, transition feedback, route details, and connection testing stay compact, responsive, and reduced-motion aware.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Connect and disconnect remain responsive during daemon work.** Lifecycle calls and snapshot collection run outside the UI thread, transition status polls quickly without overlapping probes, and progress remains visible until authoritative daemon state arrives.
|
||||
- **Tailscale is recommended for remote access.** Secure Link and direct TLS routes remain supported, while Hermes Reach is visibly experimental and lower priority.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Connection tests classify legacy private routes correctly.** A saved generic role is inferred from its actual endpoint, so LAN and Tailscale routes no longer appear as Custom VPN; results include reachability, latency, security, endpoint, and route count.
|
||||
- **Ask-mode approval cards show the requested action.** A bounded preview appears in the compact card with full context and an Open in UI action.
|
||||
- **Mixed capability policies are labeled Custom.** Overview no longer claims a preset when individual capability controls differ.
|
||||
- **Tray placement follows the notification-area monitor and DPI.** Responsive popup geometry stays anchored above the tray icon across compact and high-DPI desktops.
|
||||
- **PowerShell success output is complete and self-describing.** Scalar, pipeline, JSON, native stdout/stderr, exit status, and truncation metadata survive the desktop RPC response.
|
||||
|
||||
## [1.6.4] - 2026-08-12
|
||||
|
||||
@@ -593,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
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -6,26 +6,37 @@ 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
|
||||
|
||||
Desktop command, PowerShell, process, and job tools currently execute with the
|
||||
desktop daemon's OS-user authority. Add typed hardware operations for reliable
|
||||
schemas, audit detail, and task-scoped approval, but do not present hardware
|
||||
toggles as isolation while an enabled general shell can reach the same device.
|
||||
|
||||
- Define per-host capabilities for commands, files, processes, clipboard,
|
||||
screen, input, connected devices, microphone, and camera. Disabled must win,
|
||||
hardware-sensitive capabilities must default off, and unavailable backends
|
||||
must appear unavailable rather than as inert toggles.
|
||||
- Add a **Structured only** access profile that withholds shell/process escape
|
||||
hatches so individual capability toggles become enforceable boundaries.
|
||||
- Implement connected-device support first with typed, serial-bound ADB
|
||||
operations (`list`, `shell`, `push`, `pull`, `install`, and bounded logcat)
|
||||
instead of a generic device-exec wrapper.
|
||||
Structured access and per-host USB policy now ship with typed, serial-bound ADB
|
||||
list, shell, push, pull, install, and bounded logcat operations. Remaining work:
|
||||
- Add microphone and camera only with backend readiness detection, bounded local
|
||||
grants, active-use indicators, audit events, and immediate cancellation.
|
||||
- Reconcile legacy `desktop_screenshot` with the task-granted computer screenshot
|
||||
path so screen capture follows one policy.
|
||||
- Extend capability policy beyond hardware only where a typed broker provides a
|
||||
meaningfully stronger boundary than Structured mode already provides.
|
||||
|
||||
---
|
||||
|
||||
@@ -932,7 +943,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
|
||||
- Live gateway must discover the plugin (`~/.hermes/plugins/hermes-relay` → `plugin/`) and `plugins.enabled` must include `hermes-relay` for the `phone` platform to register. Confirm `phone` appears in `hermes gateway status` with `PHONE_ENABLED=1`.
|
||||
- End-to-end: with the app paired + "Let Hermes message me" on, run `send_message target=phone text=...` (and a cron `deliver=phone`) and confirm a notification on the device. Verify 503 (no phone) and the off-by-default gates.
|
||||
- **Phase 2c reply round-trip — ✅ DONE (verified on-device 2026-06-29).** Confirmed: agent → phone notification → inline reply → drained through the relay's loopback `GET /phone/replies` (different process) → `handle_message` (`role_authorized=True`, no `PHONE_ALLOW_ALL_USERS`) → agent answer back in the *same* thread. Both fixes required (see DEVLOG / the Phase 2c bullet above).
|
||||
- **FIX: cron `deliver=phone` / standalone send is broken.** Live testing: `hermes send --to phone` returns `{"error": "Unknown platform: phone"}`. The standalone (non-gateway) send path doesn't run a `kind=standalone` plugin's programmatic `ctx.register_platform`, so it never learns `phone` — only the running gateway (which loads `register()` at startup) does. The agent path (`send_message target=phone` in the gateway) works and was verified end-to-end on-device; the standalone/cron path needs the platform discoverable there too (declare it so the standalone loader picks it up, or route cron through the gateway). Until then `cron deliver=phone` won't work.
|
||||
- **Cron `deliver=phone` live certification pending.** The plugin now registers its standalone sender and enumerates the canonical phone home through the upstream adapter channel-directory hook. Re-run the device scenario above on the deployed plugin to certify scheduled delivery, including the offline queue and opt-in gates.
|
||||
- **FIX SHIPPED (2026-07-07) — installer + doctor guard against stale duplicate plugin copies; live-host verify pending.** Root cause of the 2026-06-29 round-trip failure: the gateway loader dedups discovered plugins by manifest `name`, so a second directory declaring `name: hermes-relay` (an old-installer backup copy, or a stray native install) could win the dedup and make the gateway load stale code — silently ignoring every later deploy. `plugin/doctor.py` now emits a `plugin-name-unique` warning when more than one directory under `~/.hermes/plugins/` declares the same plugin name (distinct real targets only — two links to the same target are deduped), and `install.sh` sweeps any such duplicate so only the canonical `hermes-relay` symlink survives. (Current `install.sh` already `rm -rf`s the old link rather than backing it up inside the plugins dir, so the original "back up outside the plugins dir" half is moot.) **Verify on the live host:** `hermes relay doctor` reports the `plugin-name-unique` check, and a reinstall leaves exactly one `hermes-relay` entry under `~/.hermes/plugins/`.
|
||||
|
||||
## Phone platform — usability roadmap (post device-verification, 2026-06-29)
|
||||
@@ -945,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).
|
||||
@@ -965,7 +976,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
|
||||
The gateway-platform model is the *correct + sufficient architecture* (the phone is a registered platform peer, so anything that routes to a platform — `send_message`, cron `deliver=`, channel directory, background jobs — can reach the phone). These are the concrete gaps between "architecturally a peer" and "I never open Discord":
|
||||
|
||||
- **Guaranteed background delivery (the biggest gap; no push today).** Delivery is **live-WSS-only** + a 24 h relay buffer; there is **no FCM/UnifiedPush** wake-up. If the app process is dead AND not holding a socket, a message waits for the next reconnect, and the relay buffer is ephemeral (lost on relay restart). Discord/Telegram feel instant because they wake the device via push even when the app is dead. Decide a **push transport**: **UnifiedPush/ntfy** (recommended — self-hostable, no Google dependency, upstream *already* ships an `ntfy` platform, on-brand for self-hosted) vs **FCM** (simplest UX but adds Play Services + a push relay; clashes with self-hosted ethos — at most the `googlePlay` flavor) vs **persistent foreground keep-alive service** holding the relay WSS (zero new infra, like `GatewayKeepAliveService`, but battery cost + Doze-fragile). Likely: UnifiedPush primary + foreground-keepalive fallback.
|
||||
- **Cron / background-job delivery is BROKEN** (already tracked above): `deliver=phone` standalone path → `Unknown platform: phone`. This is load-bearing for "receiver of crons/background jobs" — fix is required, not optional, for the replacement goal.
|
||||
- **Cron / background-job delivery needs live certification.** The standalone sender and channel-directory enumeration are implemented; certify `deliver=phone` against a deployed Relay and paired device, including reconnect delivery from the bounded offline queue.
|
||||
- **Agent-initiated multi-thread creation remains.** The app already renders N
|
||||
`source=phone` sessions, user-created Threads vary `chat_id`, and replies route
|
||||
by `chat_id` + `reply_to`. The missing parity is letting the agent open/name a
|
||||
@@ -974,7 +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.
|
||||
|
||||
@@ -1240,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
|
||||
|
||||
@@ -324,6 +324,7 @@ dependencies {
|
||||
|
||||
// QR Code scanning (ML Kit + CameraX)
|
||||
implementation(libs.mlkit.barcode)
|
||||
implementation(libs.zxing.core)
|
||||
implementation(libs.camera.core)
|
||||
implementation(libs.camera.camera2)
|
||||
implementation(libs.camera.lifecycle)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
@@ -421,7 +461,21 @@ data class ChatSession(
|
||||
/** Durable upstream session metadata, scoped by the owning connection/profile DB. */
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
/** Optional newer-upstream workspace context; absent on legacy/API-only hosts. */
|
||||
val workingDirectory: String? = null,
|
||||
val gitBranch: String? = null,
|
||||
val gitRepoRoot: String? = null,
|
||||
val pullRequestNumber: Int? = null,
|
||||
val pullRequestUrl: String? = null,
|
||||
val pullRequestState: String? = null,
|
||||
val pullRequestDraft: Boolean = false,
|
||||
) {
|
||||
val totalTokens: Int
|
||||
get() = inputTokens + outputTokens
|
||||
|
||||
val costUsd: Double
|
||||
get() = actualCostUsd ?: estimatedCostUsd ?: 0.0
|
||||
|
||||
val activityTimestamp: Long
|
||||
get() = firstPositive(lastActivityAt, updatedAt, startedAt)
|
||||
|
||||
|
||||
@@ -129,6 +129,7 @@ data class ChatTurnAskCheckpoint(
|
||||
val requestId: String? = null,
|
||||
val text: String,
|
||||
val choices: List<String>? = null,
|
||||
val multiSelect: Boolean = false,
|
||||
val smartDenied: Boolean = false,
|
||||
val envVar: String? = null,
|
||||
val timeoutSeconds: Int,
|
||||
|
||||
@@ -14,6 +14,9 @@ data class DashboardConnectionStatus(
|
||||
val gatewayTicketAvailable: Boolean? = null,
|
||||
val message: String? = null,
|
||||
val gatewayMode: String? = null,
|
||||
/** Profiles positively advertised by the live multiplex gateway. */
|
||||
val servedProfiles: List<String> = emptyList(),
|
||||
/** Installed profiles reported by the dashboard; never routing authority. */
|
||||
val profiles: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
|
||||
@@ -63,12 +63,8 @@ fun EndpointCandidate?.isEncryptedOverlayRoute(isTailscaleDetected: Boolean): Bo
|
||||
val hint = security.orEmpty().lowercase()
|
||||
return r == "tailscale" ||
|
||||
(isTailscaleDetected && hint.contains("tailscale")) ||
|
||||
r == "plugin_proxy" ||
|
||||
r == "plugin-proxy" ||
|
||||
hasSecureProxy() ||
|
||||
hint.contains("wireguard") ||
|
||||
hint.contains("https") ||
|
||||
hint.contains("tls")
|
||||
(!hasSecureProxy() && (hint.contains("https") || hint.contains("tls")))
|
||||
}
|
||||
|
||||
/** Human label for the overlay mechanism encrypting a route. */
|
||||
@@ -78,7 +74,6 @@ fun EndpointCandidate?.overlayMechanism(isTailscaleDetected: Boolean): String {
|
||||
val hint = security.orEmpty().lowercase()
|
||||
return when {
|
||||
r == "tailscale" || (isTailscaleDetected && hint.contains("tailscale")) -> "Tailscale"
|
||||
r == "plugin_proxy" || r == "plugin-proxy" || hasSecureProxy() -> "Proxy"
|
||||
hint.contains("wireguard") -> "WireGuard"
|
||||
hint.contains("https") || hint.contains("tls") -> "TLS"
|
||||
else -> "Encrypted"
|
||||
@@ -92,7 +87,10 @@ fun classifySurfaceSecurity(
|
||||
activeEndpoint: EndpointCandidate?,
|
||||
isTailscaleDetected: Boolean,
|
||||
): SurfaceSecurity {
|
||||
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
|
||||
val (kind, mechanism) = when {
|
||||
secureLinkProtected -> SurfaceSecurityKind.Tls to
|
||||
if (activeEndpoint?.hasHermesReach() == true) "Hermes Reach" else "Hermes Secure Link"
|
||||
isTlsUrl(url) -> SurfaceSecurityKind.Tls to "TLS"
|
||||
activeEndpoint.isEncryptedOverlayRoute(isTailscaleDetected) ->
|
||||
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
|
||||
@@ -101,6 +99,33 @@ fun classifySurfaceSecurity(
|
||||
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
|
||||
}
|
||||
|
||||
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
|
||||
val candidate = this ?: return false
|
||||
val routes = candidate.proxy?.takeIf { candidate.hasSecureProxy() }
|
||||
?.let { proxy ->
|
||||
val base = proxy.url.trim().trimEnd('/')
|
||||
Triple(
|
||||
"$base/dashboard",
|
||||
"$base/api",
|
||||
"wss://${base.substringAfter("://")}/relay/ws",
|
||||
)
|
||||
} ?: return false
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage" -> "dashboard"
|
||||
"API / sessions" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
if (service !in candidate.secureLinkServices()) return false
|
||||
val expected = when (service) {
|
||||
"dashboard" -> routes.first
|
||||
"api" -> routes.second
|
||||
else -> routes.third
|
||||
}
|
||||
return normalized.equals(expected, ignoreCase = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Roll up the per-surface verdicts into one connection-level [ConnectionSecurity].
|
||||
* Pure + side-effect free so it is unit-testable without Android.
|
||||
|
||||
@@ -45,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)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/**
|
||||
* A rich content card emitted inline in an assistant message via the
|
||||
@@ -117,6 +119,8 @@ data class HermesCardInput(
|
||||
val kind: String,
|
||||
/** Quick-answer chips (clarify). Empty = no chip row. */
|
||||
val choices: List<String> = emptyList(),
|
||||
/** Choices toggle independently and require an explicit submit. */
|
||||
val multiSelect: Boolean = false,
|
||||
/** Render the inline free-text mini field under the chips. */
|
||||
val allowFreeText: Boolean = false,
|
||||
/** Password-style field: masked glyphs + reveal toggle (secret/sudo). */
|
||||
@@ -124,7 +128,7 @@ data class HermesCardInput(
|
||||
/** Submit is a 650ms hold-to-confirm press-fill instead of a tap (sudo). */
|
||||
val holdToConfirm: Boolean = false,
|
||||
/**
|
||||
* Wall-clock expiry for timed asks (sudo 120s, clarify/secret 300s).
|
||||
* Wall-clock expiry for asks with an advertised deadline.
|
||||
* The renderer shows a countdown footer (Amber under 30s) and
|
||||
* self-collapses to "Expired — not granted" past it. Null = no timeout
|
||||
* (approval is session-scoped).
|
||||
@@ -155,6 +159,10 @@ data class HermesCardInput(
|
||||
}
|
||||
}
|
||||
|
||||
/** Exact JSON-array wire value expected by upstream multi-select clarify. */
|
||||
internal fun encodeClarifyMultiSelectAnswer(values: List<String>): String =
|
||||
Json.encodeToString(values.map(String::trim).filter(String::isNotEmpty).distinct())
|
||||
|
||||
/**
|
||||
* A label/value row inside a card. [value] is rendered as markdown so the
|
||||
* agent can embed emphasis, inline code, or links.
|
||||
|
||||
@@ -34,6 +34,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)}")
|
||||
|
||||
+10
-8
@@ -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" -> {
|
||||
|
||||
+14
-17
@@ -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,
|
||||
@@ -2036,6 +2068,13 @@ class ChatHandler {
|
||||
hasModelConfig = item.hasModelConfig,
|
||||
pinned = item.pinned,
|
||||
archived = item.archived,
|
||||
workingDirectory = item.cwd,
|
||||
gitBranch = item.gitBranch,
|
||||
gitRepoRoot = item.gitRepoRoot,
|
||||
pullRequestNumber = item.pullRequest?.number,
|
||||
pullRequestUrl = item.pullRequest?.url,
|
||||
pullRequestState = item.pullRequest?.state,
|
||||
pullRequestDraft = item.pullRequest?.draft == true,
|
||||
)
|
||||
}.sortedByDescending { it.activityTimestamp }
|
||||
// Preserve the active session's optimistic row when the server list
|
||||
|
||||
+417
-2
@@ -7,9 +7,12 @@ import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPullRequest
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPullRequestScanResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPruneFilters
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPrunePreview
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPruneResult
|
||||
import com.hermesandroid.relay.network.upstream.models.RepositoryPullRequestListResponse
|
||||
import com.hermesandroid.relay.auth.SecureStoreCache
|
||||
import com.hermesandroid.relay.auth.SessionTokenStore
|
||||
import com.hermesandroid.relay.auth.buildRawTokenStore
|
||||
@@ -35,13 +38,18 @@ import okhttp3.CookieJar
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
import okio.BufferedSink
|
||||
|
||||
// Status/session/provider snapshots are @Serializable so the Manage tab's
|
||||
// disk cache (DashboardManageDiskCache) can persist Loaded entries verbatim.
|
||||
@@ -67,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,
|
||||
@@ -173,6 +198,71 @@ data class DashboardCustomEndpointValidation(
|
||||
val models: List<String>,
|
||||
)
|
||||
|
||||
internal class BoundedStreamRequestBody(
|
||||
private val declaredLength: Long?,
|
||||
private val limitBytes: Long,
|
||||
private val openStream: () -> InputStream,
|
||||
) : RequestBody() {
|
||||
init {
|
||||
require(limitBytes > 0)
|
||||
require(declaredLength == null || declaredLength >= 0)
|
||||
require(declaredLength == null || declaredLength <= limitBytes) {
|
||||
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit."
|
||||
}
|
||||
}
|
||||
|
||||
override fun contentType() = "application/zip".toMediaType()
|
||||
|
||||
override fun contentLength(): Long = declaredLength ?: -1L
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
openStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var written = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > limitBytes) {
|
||||
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit.")
|
||||
}
|
||||
sink.write(buffer, 0, read)
|
||||
}
|
||||
if (declaredLength != null && written != declaredLength) {
|
||||
throw IOException("Backup archive changed while it was being read.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun copyBounded(
|
||||
input: InputStream,
|
||||
output: OutputStream,
|
||||
declaredLength: Long?,
|
||||
limitBytes: Long,
|
||||
): Long {
|
||||
require(limitBytes > 0)
|
||||
require(declaredLength == null || declaredLength >= 0)
|
||||
require(declaredLength == null || declaredLength <= limitBytes) {
|
||||
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit."
|
||||
}
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var written = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > limitBytes) {
|
||||
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit.")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
if (declaredLength != null && written != declaredLength) {
|
||||
throw IOException("Backup archive changed while it was being downloaded.")
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/** One entry from `GET /api/audio/elevenlabs/voices` — non-secret voice metadata. */
|
||||
data class ElevenLabsVoice(
|
||||
val voiceId: String,
|
||||
@@ -206,8 +296,14 @@ class DashboardApiClient(
|
||||
isLenient = true
|
||||
coerceInputValues = true
|
||||
},
|
||||
private val nowMillis: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
private val baseUrl: String = baseUrl.trim().trimEnd('/')
|
||||
private val sessionPrScanLock = Any()
|
||||
private val sessionPrScannedAt = mutableMapOf<String, Long>()
|
||||
private val sessionPrScanWasTerminal = mutableMapOf<String, Boolean>()
|
||||
private val sessionPullRequests = mutableMapOf<String, SessionPullRequest>()
|
||||
private var sessionPrScanSupported: Boolean? = null
|
||||
|
||||
/**
|
||||
* Resolve a request URL without ever throwing. okhttp's
|
||||
@@ -518,6 +614,157 @@ class DashboardApiClient(
|
||||
suspend fun createServerBackup(): Result<JsonObject> =
|
||||
postJsonObject("/api/ops/backup")
|
||||
|
||||
/** Download only archives created inside upstream's guarded dashboard backup directory. */
|
||||
suspend fun downloadServerBackup(
|
||||
archive: String,
|
||||
openOutput: () -> OutputStream,
|
||||
): Result<String> = download(
|
||||
path = "/api/ops/backup/download?archive=${queryValue(archive)}",
|
||||
operation = "Hermes backup",
|
||||
openOutput = openOutput,
|
||||
)
|
||||
|
||||
/** Import a server-local archive path after the user confirms the destructive restore. */
|
||||
suspend fun importServerBackup(archive: String): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/ops/import",
|
||||
payload = buildJsonObject { put("archive", archive) },
|
||||
)
|
||||
|
||||
/** Upload an Android-selected zip to upstream's guarded staging directory and start import. */
|
||||
suspend fun uploadServerBackup(
|
||||
filename: String,
|
||||
contentLength: Long?,
|
||||
openStream: () -> InputStream,
|
||||
force: Boolean = false,
|
||||
): Result<JsonObject> = withContext(Dispatchers.IO) {
|
||||
val path = "/api/ops/import-upload"
|
||||
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
|
||||
val body = MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("force", force.toString())
|
||||
.addFormDataPart(
|
||||
"file",
|
||||
filename.ifBlank { "hermes-backup.zip" },
|
||||
runCatching {
|
||||
BoundedStreamRequestBody(contentLength, MAX_BACKUP_TRANSFER_BYTES, openStream)
|
||||
}.getOrElse { return@withContext Result.failure(it) },
|
||||
)
|
||||
.build()
|
||||
executeJson(Request.Builder().url(httpUrl).post(body).build(), path)
|
||||
}
|
||||
|
||||
suspend fun getLearningNode(id: String, profile: String? = null): Result<JsonObject> =
|
||||
getJsonObject("/api/learning/node?id=${queryValue(id)}${profileQuerySuffix(profile)}")
|
||||
|
||||
suspend fun updateLearningNode(
|
||||
id: String,
|
||||
content: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/learning/node",
|
||||
payload = buildJsonObject {
|
||||
put("id", id)
|
||||
put("content", content)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun deleteLearningNode(id: String, profile: String? = null): Result<JsonObject> =
|
||||
deleteJsonObjectWithBody(
|
||||
path = "/api/learning/node",
|
||||
payload = buildJsonObject {
|
||||
put("id", id)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun selectMemoryProvider(provider: String): Result<JsonObject> =
|
||||
putJsonObject(
|
||||
path = "/api/memory/provider",
|
||||
payload = buildJsonObject { put("provider", provider) },
|
||||
)
|
||||
|
||||
/** Activate an already-configured provider inside the selected upstream profile. */
|
||||
suspend fun activateMemoryProvider(provider: String, profile: String? = null): Result<JsonObject> =
|
||||
updateMemoryProviderConfig(provider, JsonObject(emptyMap()), profile)
|
||||
|
||||
suspend fun getMemoryProviderConfig(
|
||||
provider: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = getJsonObject(
|
||||
"/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun updateMemoryProviderConfig(
|
||||
provider: String,
|
||||
values: JsonObject,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
|
||||
payload = buildJsonObject { put("values", values) },
|
||||
)
|
||||
|
||||
suspend fun setupMemoryProvider(provider: String): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/memory/providers/${pathSegment(provider)}/setup",
|
||||
// Dependency installation is host-global upstream. Do not submit
|
||||
// profile-owned values through this unscoped route.
|
||||
payload = buildJsonObject { put("values", JsonObject(emptyMap())) },
|
||||
)
|
||||
|
||||
suspend fun startWhatsAppOnboarding(
|
||||
mode: String,
|
||||
allowedUsers: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = postJsonObject(
|
||||
path = "/api/messaging/whatsapp/onboarding/start",
|
||||
payload = buildJsonObject {
|
||||
put("mode", mode)
|
||||
put("allowed_users", allowedUsers)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun getWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
|
||||
getJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
|
||||
|
||||
suspend fun applyWhatsAppOnboarding(
|
||||
pairingId: String,
|
||||
mode: String,
|
||||
allowedUsers: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = postJsonObject(
|
||||
path = "/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}/apply",
|
||||
payload = buildJsonObject {
|
||||
put("mode", mode)
|
||||
put("allowed_users", allowedUsers)
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun cancelWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
|
||||
deleteJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
|
||||
|
||||
suspend fun setMessagingPlatformEnabled(
|
||||
platform: String,
|
||||
enabled: Boolean,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> = putJsonObject(
|
||||
path = "/api/messaging/platforms/${pathSegment(platform)}${profileQuery(profile)}",
|
||||
payload = buildJsonObject {
|
||||
put("enabled", enabled)
|
||||
put("env", JsonObject(emptyMap()))
|
||||
put("clear_env", JsonArray(emptyList()))
|
||||
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun testMessagingPlatform(platform: String, profile: String? = null): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
"/api/messaging/platforms/${pathSegment(platform)}/test${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun setProfileDescription(name: String, description: String): Result<JsonObject> =
|
||||
putJsonObject(
|
||||
path = "/api/profiles/${pathSegment(name)}/description",
|
||||
@@ -764,7 +1011,13 @@ class DashboardApiClient(
|
||||
pageSessions.forEach { sessions.putIfAbsent(it.id, it) }
|
||||
if (pageSessions.size < page.limit) break
|
||||
}
|
||||
Result.success(sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)))
|
||||
Result.success(
|
||||
enrichSessionWorkState(
|
||||
sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)),
|
||||
fixedProfile = profile?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: DEFAULT_SESSION_PROFILE_SCOPE,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -776,7 +1029,7 @@ class DashboardApiClient(
|
||||
limit: Int = SESSION_LIST_WINDOW_LIMIT,
|
||||
): Result<List<SessionItem>> = withContext(Dispatchers.IO) {
|
||||
val boundedLimit = limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)
|
||||
getJson(
|
||||
val result = getJson(
|
||||
"/api/profiles/sessions?limit=$boundedLimit&offset=0&order=recent" +
|
||||
"&min_messages=1&archived=include&profile=all",
|
||||
).mapCatching { root ->
|
||||
@@ -786,8 +1039,129 @@ class DashboardApiClient(
|
||||
.distinctBy { "${it.profile}:${it.id}" }
|
||||
.take(boundedLimit)
|
||||
}
|
||||
if (result.isFailure) return@withContext result
|
||||
Result.success(enrichSessionWorkState(result.getOrThrow(), fixedProfile = null))
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach the PR a coding session created using the current upstream
|
||||
* transcript-backed endpoint. Repository and branch already arrive on the
|
||||
* list row. Missing/older endpoints are deliberately ignored, leaving the
|
||||
* original rows intact. Active misses retry on a bounded cadence; terminal
|
||||
* rows get one final scan and resolved associations remain cached.
|
||||
*/
|
||||
private suspend fun enrichSessionWorkState(
|
||||
sessions: List<SessionItem>,
|
||||
fixedProfile: String?,
|
||||
): List<SessionItem> {
|
||||
val candidates = sessions.filter {
|
||||
it.id.isNotBlank() &&
|
||||
(!it.gitRepoRoot.isNullOrBlank() || !it.gitBranch.isNullOrBlank() || !it.cwd.isNullOrBlank())
|
||||
}
|
||||
val duplicateIds = if (fixedProfile == null) {
|
||||
candidates.groupingBy { it.id }.eachCount().filterValues { it > 1 }.keys
|
||||
} else {
|
||||
emptySet()
|
||||
}
|
||||
val now = nowMillis()
|
||||
val pending = synchronized(sessionPrScanLock) {
|
||||
candidates.filter { session ->
|
||||
if (session.id in duplicateIds) return@filter false
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
val scannedAt = sessionPrScannedAt[key]
|
||||
val resolved = sessionPullRequests[key] != null
|
||||
!resolved && when {
|
||||
scannedAt == null -> true
|
||||
session.endedAt != null -> sessionPrScanWasTerminal[key] != true
|
||||
else -> now - scannedAt >= ACTIVE_SESSION_PR_MISS_TTL_MILLIS
|
||||
}
|
||||
}
|
||||
}
|
||||
val pendingIds = pending.map { it.id }.distinct()
|
||||
if (pendingIds.isNotEmpty()) {
|
||||
val payload = buildJsonObject {
|
||||
put("ids", JsonArray(pendingIds.map { JsonPrimitive(it) }))
|
||||
}
|
||||
val scan = postJsonObject("/api/profiles/sessions/pull-requests", payload)
|
||||
.mapCatching { root ->
|
||||
json.decodeFromJsonElement(SessionPullRequestScanResponse.serializer(), root)
|
||||
}
|
||||
synchronized(sessionPrScanLock) {
|
||||
// A legacy 404 is a compatibility outcome, not a session-list failure.
|
||||
// Avoid hammering an unsupported host on every drawer refresh.
|
||||
if (scan.isSuccess || sessionPrScanSupported == null) {
|
||||
sessionPrScanSupported = scan.isSuccess
|
||||
}
|
||||
pending.forEach { session ->
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
sessionPrScannedAt[key] = now
|
||||
sessionPrScanWasTerminal[key] = session.endedAt != null
|
||||
scan.getOrNull()?.pullRequests?.get(session.id)?.takeIf {
|
||||
it.number > 0 && it.url.isNotBlank()
|
||||
}?.let { pullRequest ->
|
||||
sessionPullRequests[key] = pullRequest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
refreshPullRequestStates(candidates, fixedProfile)
|
||||
val pullRequests = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
|
||||
return sessions.map { session ->
|
||||
session.copy(pullRequest = pullRequests[sessionWorkKey(session, fixedProfile)])
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh current PR lifecycle state using upstream's repo-scoped GitHub view. */
|
||||
private suspend fun refreshPullRequestStates(
|
||||
sessions: List<SessionItem>,
|
||||
fixedProfile: String?,
|
||||
) {
|
||||
if (synchronized(sessionPrScanLock) { sessionPrScanSupported } != true) return
|
||||
val known = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
|
||||
sessions.groupBy { (it.gitRepoRoot ?: it.cwd).orEmpty().trim() }
|
||||
.filterKeys { it.isNotBlank() }
|
||||
.forEach { (path, repositorySessions) ->
|
||||
val branches = repositorySessions.mapNotNull { it.gitBranch?.trim() }
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
val numbers = repositorySessions.mapNotNull {
|
||||
known[sessionWorkKey(it, fixedProfile)]?.number
|
||||
}
|
||||
.filter { it > 0 }
|
||||
.distinct()
|
||||
if (branches.isEmpty() && numbers.isEmpty()) return@forEach
|
||||
val payload = buildJsonObject {
|
||||
put("path", path)
|
||||
put("branches", JsonArray(branches.map { JsonPrimitive(it) }))
|
||||
put("numbers", JsonArray(numbers.map { JsonPrimitive(it) }))
|
||||
}
|
||||
val response = postJsonObject("/api/git/review/pr-list", payload)
|
||||
.mapCatching { root ->
|
||||
json.decodeFromJsonElement(RepositoryPullRequestListResponse.serializer(), root)
|
||||
}
|
||||
.getOrNull()
|
||||
?: return@forEach
|
||||
if (!response.ghReady) return@forEach
|
||||
synchronized(sessionPrScanLock) {
|
||||
repositorySessions.forEach { session ->
|
||||
val key = sessionWorkKey(session, fixedProfile)
|
||||
val recovered = sessionPullRequests[key]
|
||||
val current = response.prs.firstOrNull { pr ->
|
||||
recovered != null && pr.number == recovered.number
|
||||
} ?: response.prs.firstOrNull { pr ->
|
||||
!session.gitBranch.isNullOrBlank() && pr.branch == session.gitBranch
|
||||
}
|
||||
if (current != null && current.number > 0 && current.url.isNotBlank()) {
|
||||
sessionPullRequests[key] = current
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sessionWorkKey(session: SessionItem, fixedProfile: String?): String =
|
||||
"${fixedProfile ?: session.profile.orEmpty()}\u0000${session.id}"
|
||||
|
||||
/**
|
||||
* A session's message history, scoped to its owning profile via the dashboard
|
||||
* `GET /api/sessions/{id}/messages?profile=`. Required twin of [listSessions]:
|
||||
@@ -1110,8 +1484,44 @@ class DashboardApiClient(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun download(
|
||||
path: String,
|
||||
operation: String,
|
||||
openOutput: () -> OutputStream,
|
||||
): Result<String> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder().url(httpUrl).get().build()
|
||||
try {
|
||||
okHttpClient.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return@withContext Result.failure(apiFailure(response, operation))
|
||||
val disposition = response.header("Content-Disposition").orEmpty()
|
||||
val filename = Regex("filename=\\\"?([^\\\";]+)").find(disposition)?.groupValues?.get(1)
|
||||
?: "hermes-backup.zip"
|
||||
val body = response.body
|
||||
val declaredLength = body.contentLength().takeIf { it >= 0 }
|
||||
if (declaredLength != null && declaredLength > MAX_BACKUP_TRANSFER_BYTES) {
|
||||
throw IOException("Backup archive exceeds the ${MAX_BACKUP_TRANSFER_BYTES / (1024 * 1024)} MB download limit.")
|
||||
}
|
||||
openOutput().use { output ->
|
||||
body.byteStream().use { input ->
|
||||
copyBounded(input, output, declaredLength, MAX_BACKUP_TRANSFER_BYTES)
|
||||
}
|
||||
}
|
||||
Result.success(filename)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val JSON_MEDIA = "application/json; charset=utf-8".toMediaType()
|
||||
private const val DEFAULT_SESSION_PROFILE_SCOPE = "__dashboard_default__"
|
||||
internal const val ACTIVE_SESSION_PR_MISS_TTL_MILLIS = 60_000L
|
||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||
// client-side avoids uploading a body the Dashboard will reject.
|
||||
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
|
||||
|
||||
fun pathSegment(value: String): String =
|
||||
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
@@ -1169,6 +1579,11 @@ class DashboardApiClient(
|
||||
return if (trimmed.isBlank()) "" else "?profile=${pathSegment(trimmed)}"
|
||||
}
|
||||
|
||||
private fun profileQuerySuffix(profile: String?): String {
|
||||
val trimmed = profile?.trim().orEmpty()
|
||||
return if (trimmed.isBlank()) "" else "&profile=${queryValue(trimmed)}"
|
||||
}
|
||||
|
||||
private fun profileLimitQuery(profile: String?, limit: Int): String {
|
||||
val params = buildList {
|
||||
val trimmed = profile?.trim().orEmpty()
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
+29
-12
@@ -444,15 +444,26 @@ class GatewayEventMapper(
|
||||
}
|
||||
|
||||
fun interactionRequest(type: String, payload: JsonObject?): GatewayAsk? = when (type) {
|
||||
"clarify.request" -> GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
|
||||
?.takeIf { it.isNotEmpty() },
|
||||
timeoutSeconds = CLARIFY_TIMEOUT_SECONDS,
|
||||
)
|
||||
"clarify.request" -> {
|
||||
val choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
|
||||
?.filter { it.isNotEmpty() }
|
||||
?.distinct()
|
||||
?.take(MAX_CLARIFY_CHOICES)
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = choices,
|
||||
multiSelect = payload.boolean("multi_select") == true && choices != null,
|
||||
// Current upstream owns expiry through clarify.expire and
|
||||
// does not advertise its configurable deadline. Never
|
||||
// invent a local deadline; consume future additive
|
||||
// metadata only when it is present and positive.
|
||||
timeoutSeconds = payload.int("timeout_seconds")?.coerceAtLeast(0) ?: 0,
|
||||
)
|
||||
}
|
||||
|
||||
"approval.request" -> GatewayAsk(
|
||||
kind = GatewayAsk.Kind.APPROVAL,
|
||||
@@ -561,9 +572,9 @@ class GatewayEventMapper(
|
||||
}
|
||||
}
|
||||
|
||||
// Upstream `_block()` timeouts per ask kind (server.py) — the blocked thread
|
||||
// resolves to "" when these elapse. Approval has none (session-scoped).
|
||||
private const val CLARIFY_TIMEOUT_SECONDS = 300
|
||||
// Upstream clarify tool accepts at most four choices. Sudo/secret retain fixed
|
||||
// `_block()` timeouts; clarify is configurable and expires authoritatively.
|
||||
private const val MAX_CLARIFY_CHOICES = 4
|
||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
||||
|
||||
@@ -583,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() }
|
||||
|
||||
|
||||
@@ -218,13 +218,15 @@ data class GatewayAsk(
|
||||
val text: String,
|
||||
/** Server-advertised answers for clarify and approval requests. */
|
||||
val choices: List<String>? = null,
|
||||
/** Clarify-only: several advertised choices may be returned together. */
|
||||
val multiSelect: Boolean = false,
|
||||
/** Approval-only: the smart observer denied and the owner may override once. */
|
||||
val smartDenied: Boolean = false,
|
||||
/** Secret-only: the env var the value will be stored under. */
|
||||
val envVar: String? = null,
|
||||
/**
|
||||
* Upstream blocking timeout (clarify/secret 300s, sudo 120s). 0 means no
|
||||
* countdown — approvals are session-scoped and never expire on their own.
|
||||
* Server-advertised blocking timeout. 0 means no client countdown; the
|
||||
* authoritative `*.expire` event still retires the interaction.
|
||||
*/
|
||||
val timeoutSeconds: Int,
|
||||
) {
|
||||
|
||||
@@ -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()
|
||||
|
||||
+152
-2
@@ -1,21 +1,27 @@
|
||||
package com.hermesandroid.relay.network.upstream.models
|
||||
|
||||
import com.hermesandroid.relay.data.MessageReaction
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.descriptors.PrimitiveKind
|
||||
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
|
||||
import kotlinx.serialization.encoding.Decoder
|
||||
import kotlinx.serialization.encoding.Encoder
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonDecoder
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonEncoder
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.Instant
|
||||
|
||||
/**
|
||||
@@ -76,6 +82,56 @@ object FlexibleIdNonNullSerializer : KSerializer<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Unknown-safe durable SQLite row id used by current Gateway history. */
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
object FlexibleLongSerializer : KSerializer<Long?> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("FlexibleLong", PrimitiveKind.LONG)
|
||||
|
||||
override fun deserialize(decoder: Decoder): Long? {
|
||||
return try {
|
||||
val jsonDecoder = decoder as? JsonDecoder
|
||||
?: return decoder.decodeLong()
|
||||
(jsonDecoder.decodeJsonElement() as? JsonPrimitive)?.longOrNull
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: Long?) {
|
||||
if (value != null) encoder.encodeLong(value) else encoder.encodeNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard versions may expose SQLite JSON columns either as an object or as
|
||||
* their raw JSON string. Normalize both shapes so persisted presentation data
|
||||
* (notably message reactions) survives a history reload on every supported
|
||||
* upstream version.
|
||||
*/
|
||||
object FlexibleJsonObjectSerializer : KSerializer<JsonObject?> {
|
||||
override val descriptor = JsonObject.serializer().descriptor
|
||||
|
||||
override fun deserialize(decoder: Decoder): JsonObject? {
|
||||
return try {
|
||||
val jsonDecoder = decoder as? JsonDecoder ?: return null
|
||||
when (val element = jsonDecoder.decodeJsonElement()) {
|
||||
is JsonObject -> element
|
||||
is JsonPrimitive -> element.content.takeIf { it.isNotBlank() }
|
||||
?.let { Json.parseToJsonElement(it) as? JsonObject }
|
||||
else -> null
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: JsonObject?) {
|
||||
val jsonEncoder = encoder as? JsonEncoder
|
||||
?: throw SerializationException("FlexibleJsonObjectSerializer requires JSON")
|
||||
jsonEncoder.encodeJsonElement(value ?: JsonNull)
|
||||
}
|
||||
}
|
||||
|
||||
/** Timestamp serializer for Hermes session metadata.
|
||||
*
|
||||
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
|
||||
@@ -113,6 +169,32 @@ object FlexibleTimestampSerializer : KSerializer<Double?> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Boolean serializer for session flags backed by SQLite integer columns.
|
||||
*
|
||||
* Older Dashboard responses can expose those columns as `0` / `1` instead of
|
||||
* JSON booleans. Accept the equivalent primitive forms without making arbitrary
|
||||
* numbers or strings truthy, and always serialize back to a real JSON boolean.
|
||||
*/
|
||||
object FlexibleBooleanSerializer : KSerializer<Boolean> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("FlexibleBoolean", PrimitiveKind.BOOLEAN)
|
||||
|
||||
override fun deserialize(decoder: Decoder): Boolean {
|
||||
val jsonDecoder = decoder as? JsonDecoder ?: return decoder.decodeBoolean()
|
||||
val element = jsonDecoder.decodeJsonElement()
|
||||
val value = (element as? JsonPrimitive)?.content?.trim()?.lowercase()
|
||||
return when (value) {
|
||||
"true", "1" -> true
|
||||
"false", "0" -> false
|
||||
else -> throw SerializationException("Expected a boolean-compatible value, got $element")
|
||||
}
|
||||
}
|
||||
|
||||
override fun serialize(encoder: Encoder, value: Boolean) {
|
||||
encoder.encodeBoolean(value)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Session CRUD responses ---
|
||||
|
||||
@Serializable
|
||||
@@ -166,15 +248,50 @@ data class SessionItem(
|
||||
@SerialName("tool_call_count") val toolCallCount: Int? = null,
|
||||
@SerialName("input_tokens") val inputTokens: Int? = null,
|
||||
@SerialName("output_tokens") val outputTokens: Int? = null,
|
||||
@SerialName("has_model_config") val hasModelConfig: Boolean = false,
|
||||
@SerialName("actual_cost_usd") val actualCostUsd: Double? = null,
|
||||
@SerialName("estimated_cost_usd") val estimatedCostUsd: Double? = null,
|
||||
@SerialName("is_active") val isActive: Boolean = false,
|
||||
@SerialName("has_model_config")
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val hasModelConfig: Boolean = false,
|
||||
/** Durable flags returned by current Dashboard and API-server session resources. */
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val pinned: Boolean = false,
|
||||
@Serializable(with = FlexibleBooleanSerializer::class)
|
||||
val archived: Boolean = false,
|
||||
/** Optional workspace metadata added by newer Dashboard session lists. */
|
||||
val cwd: String? = null,
|
||||
@SerialName("git_branch") val gitBranch: String? = null,
|
||||
@SerialName("git_repo_root") val gitRepoRoot: String? = null,
|
||||
/** Best-effort association from the Dashboard's read-only transcript scan. */
|
||||
val pullRequest: SessionPullRequest? = null,
|
||||
) {
|
||||
val resolvedLastActivity: Double?
|
||||
get() = lastActive ?: lastActivity ?: lastActivityAt ?: updatedAt
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SessionPullRequest(
|
||||
val number: Int,
|
||||
val url: String,
|
||||
val branch: String? = null,
|
||||
val state: String? = null,
|
||||
val draft: Boolean = false,
|
||||
val title: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SessionPullRequestScanResponse(
|
||||
@SerialName("pull_requests") val pullRequests: Map<String, SessionPullRequest> = emptyMap(),
|
||||
val scanned: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RepositoryPullRequestListResponse(
|
||||
val ghReady: Boolean = false,
|
||||
val prs: List<SessionPullRequest> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CreateSessionRequest(
|
||||
val title: String? = null,
|
||||
@@ -265,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,
|
||||
@@ -275,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
|
||||
@@ -283,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) {
|
||||
@@ -315,6 +450,21 @@ data class MessageItem(
|
||||
}
|
||||
}
|
||||
|
||||
fun parseMessageReactions(element: JsonElement?): List<MessageReaction> =
|
||||
(element as? JsonArray).orEmpty().mapNotNull { raw ->
|
||||
val reaction = raw as? JsonObject ?: return@mapNotNull null
|
||||
val emoji = (reaction["emoji"] as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() }
|
||||
?: return@mapNotNull null
|
||||
val author = (reaction["author"] as? JsonPrimitive)?.content
|
||||
?.takeIf { it == "user" || it == "agent" }
|
||||
?: return@mapNotNull null
|
||||
MessageReaction(
|
||||
emoji = emoji,
|
||||
author = author,
|
||||
at = (reaction["at"] as? JsonPrimitive)?.doubleOrNull ?: 0.0,
|
||||
)
|
||||
}
|
||||
|
||||
// --- SSE streaming events from /api/sessions/{id}/chat/stream ---
|
||||
//
|
||||
// Hermes WebAPI event types (from server source):
|
||||
|
||||
+8
-4
@@ -9,6 +9,7 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
@@ -47,10 +48,13 @@ object ProactiveMessageNotifier {
|
||||
/**
|
||||
* Tap route — opens Chat, where the message lives as a Thread. Must match
|
||||
* `Screen.Chat.route()` in RelayApp. Routed via the EXTRA_NAV_ROUTE deep-link
|
||||
* path (MainActivity → NavRouteRequest → RelayApp collector). Opening the
|
||||
* exact Thread by chat_id is a follow-up (see TODO).
|
||||
* path (MainActivity → NavRouteRequest → RelayApp collector), carrying the
|
||||
* `chat_id` so RelayApp opens the exact real or provisional Thread.
|
||||
*/
|
||||
private const val TAP_ROUTE = "chat"
|
||||
private fun tapRoute(chatId: String?): String =
|
||||
chatId?.takeIf { it.isNotBlank() }
|
||||
?.let { "chat?proactiveChatId=${Uri.encode(it)}" }
|
||||
?: "chat"
|
||||
|
||||
/**
|
||||
* Post (or replace) a proactive-message notification.
|
||||
@@ -80,7 +84,7 @@ object ProactiveMessageNotifier {
|
||||
|
||||
val tapIntent = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
putExtra(MainActivity.EXTRA_NAV_ROUTE, TAP_ROUTE)
|
||||
putExtra(MainActivity.EXTRA_NAV_ROUTE, tapRoute(chatId))
|
||||
}
|
||||
val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
// Distinct requestCode per slot so each notification gets its own
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+10
-1
@@ -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
|
||||
|
||||
@@ -45,6 +45,8 @@ import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -81,6 +83,7 @@ import com.hermesandroid.relay.data.HermesCardAction
|
||||
import com.hermesandroid.relay.data.HermesCardDispatch
|
||||
import com.hermesandroid.relay.data.HermesCardField
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import com.hermesandroid.relay.data.encodeClarifyMultiSelectAnswer
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
@@ -389,7 +392,8 @@ private fun ChoseRow(
|
||||
/**
|
||||
* The interactive answer surface for ask cards, composed from the
|
||||
* [HermesCardInput] flags rather than the card type:
|
||||
* - [HermesCardInput.choices] → AssistChip row, one tap dispatches.
|
||||
* - [HermesCardInput.choices] → one-tap AssistChips, or independently
|
||||
* selected FilterChips plus explicit submit for multi-select clarifies.
|
||||
* - [HermesCardInput.allowFreeText] → [InlineAnswerField] mini pill +
|
||||
* 18dp send affordance.
|
||||
* - [HermesCardInput.masked] → password-style OutlinedTextField with a
|
||||
@@ -411,6 +415,8 @@ private fun CardInputSlot(
|
||||
// never be written into the saved-instance-state Bundle.
|
||||
var answerText by remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
var selectedChoices by remember(input.choices) { mutableStateOf(emptyList<String>()) }
|
||||
val isMultiSelect = input.multiSelect && input.choices.isNotEmpty()
|
||||
|
||||
val showFreeText = !input.masked && (
|
||||
input.allowFreeText ||
|
||||
@@ -428,16 +434,45 @@ private fun CardInputSlot(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
input.choices.forEach { choice ->
|
||||
AssistChip(
|
||||
onClick = { onSubmit(choice) },
|
||||
label = {
|
||||
Text(choice, style = MaterialTheme.typography.labelMedium)
|
||||
},
|
||||
colors = AssistChipDefaults.assistChipColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
labelColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
)
|
||||
if (isMultiSelect) {
|
||||
val selected = choice in selectedChoices
|
||||
FilterChip(
|
||||
selected = selected,
|
||||
onClick = {
|
||||
selectedChoices = if (selected) {
|
||||
selectedChoices - choice
|
||||
} else {
|
||||
selectedChoices + choice
|
||||
}
|
||||
},
|
||||
label = { Text(choice, style = MaterialTheme.typography.labelMedium) },
|
||||
leadingIcon = if (selected) {
|
||||
{
|
||||
Icon(
|
||||
Icons.Filled.Check,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
},
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
AssistChip(
|
||||
onClick = { onSubmit(choice) },
|
||||
label = {
|
||||
Text(choice, style = MaterialTheme.typography.labelMedium)
|
||||
},
|
||||
colors = AssistChipDefaults.assistChipColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
labelColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,21 +517,38 @@ private fun CardInputSlot(
|
||||
onValueChange = { answerText = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(
|
||||
onClick = { onSubmit(answerText.trim()) },
|
||||
enabled = answerText.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(R.string.card_send_answer_a11y),
|
||||
tint = if (answerText.isNotBlank()) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
if (!isMultiSelect) {
|
||||
IconButton(
|
||||
onClick = { onSubmit(answerText.trim()) },
|
||||
enabled = answerText.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(R.string.card_send_answer_a11y),
|
||||
tint = if (answerText.isNotBlank()) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isMultiSelect) {
|
||||
val answers = selectedChoices +
|
||||
listOfNotNull(answerText.trim().takeIf(String::isNotEmpty))
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Button(
|
||||
onClick = { onSubmit(encodeClarifyMultiSelectAnswer(answers)) },
|
||||
enabled = answers.isNotEmpty(),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.card_submit),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Submit affordance for masked / hold-to-confirm inputs
|
||||
when {
|
||||
input.holdToConfirm -> {
|
||||
|
||||
@@ -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,11 +2216,23 @@ 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,
|
||||
pinned = item.pinned,
|
||||
archived = item.archived,
|
||||
workingDirectory = item.cwd,
|
||||
gitBranch = item.gitBranch,
|
||||
gitRepoRoot = item.gitRepoRoot,
|
||||
pullRequestNumber = item.pullRequest?.number,
|
||||
pullRequestUrl = item.pullRequest?.url,
|
||||
pullRequestState = item.pullRequest?.state,
|
||||
pullRequestDraft = item.pullRequest?.draft == true,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -2157,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 {
|
||||
@@ -2167,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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
) {
|
||||
@@ -2272,7 +2434,6 @@ fun ChatScreen(
|
||||
resolveChatHeaderSubtitle(
|
||||
isStreaming = isStreaming,
|
||||
statusText = statusText,
|
||||
projectName = gatewayProjectName,
|
||||
personalityName = nonDefaultPersonality,
|
||||
modelName = modelName,
|
||||
)
|
||||
@@ -2579,7 +2740,7 @@ fun ChatScreen(
|
||||
selectedProfile = selectedProfile,
|
||||
resolvedProfile = effectiveProfile,
|
||||
presentation = profilePresentation,
|
||||
activeDisplayName = agentDisplayName,
|
||||
activeDisplayName = globalSelectedAgentDisplayName,
|
||||
isProfileLocked = isProfileLocked,
|
||||
lockedProfileName = lockedProfileName,
|
||||
switchEnabled = profileSwitchEnabled,
|
||||
@@ -3105,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
|
||||
},
|
||||
@@ -4223,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
|
||||
|
||||
@@ -54,6 +54,14 @@ internal enum class DashboardActionKind {
|
||||
ValidateCustomEndpoint,
|
||||
ActivateCustomEndpoint,
|
||||
DeleteCustomEndpoint,
|
||||
EditLearningNode,
|
||||
DeleteLearningNode,
|
||||
ConfigureMemoryProvider,
|
||||
ActivateMemoryProvider,
|
||||
SetupWhatsApp,
|
||||
EnableChannel,
|
||||
DisableChannel,
|
||||
TestChannel,
|
||||
|
||||
// Input-backed kinds — intercepted before runAction and routed to a
|
||||
// text-input or model-picker dialog instead of firing immediately.
|
||||
|
||||
+588
-13
@@ -3,11 +3,16 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.ContentResolver
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
@@ -35,6 +40,7 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
@@ -90,6 +96,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
@@ -125,16 +132,24 @@ import com.hermesandroid.relay.viewmodel.PendingMcpOAuth
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
import java.io.IOException
|
||||
import com.google.zxing.BarcodeFormat
|
||||
import com.google.zxing.qrcode.QRCodeWriter
|
||||
|
||||
/**
|
||||
* Section of the Hermes dashboard Manage tab. The enum identity is used for
|
||||
@@ -248,7 +263,10 @@ internal fun scopeDashboardManageItems(
|
||||
if (
|
||||
sectionPath == "/api/mcp/servers" ||
|
||||
sectionPath == "/api/mcp/catalog" ||
|
||||
sectionPath == "/api/providers/custom-endpoints"
|
||||
sectionPath == "/api/providers/custom-endpoints" ||
|
||||
sectionPath == "/api/learning/graph" ||
|
||||
sectionPath == "/api/memory" ||
|
||||
sectionPath == "/api/messaging/platforms"
|
||||
) {
|
||||
items.map { it.copy(profile = profile) }
|
||||
} else {
|
||||
@@ -375,6 +393,9 @@ private enum class DashboardSectionAction {
|
||||
UpdateSkillsHub,
|
||||
AddCustomEndpoint,
|
||||
CreateServerBackup,
|
||||
DownloadServerBackup,
|
||||
ImportServerBackup,
|
||||
SetupWhatsApp,
|
||||
}
|
||||
|
||||
/** Editor session for a profile's SOUL.md — content is the FULL file from GET. */
|
||||
@@ -384,6 +405,28 @@ private data class SoulEditorState(
|
||||
val exists: Boolean,
|
||||
)
|
||||
|
||||
private data class LearningEditorState(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val initialContent: String,
|
||||
val profile: String?,
|
||||
)
|
||||
|
||||
private data class MemoryProviderEditorState(
|
||||
val name: String,
|
||||
val schema: JsonObject,
|
||||
val profile: String?,
|
||||
)
|
||||
|
||||
private data class WhatsAppOnboardingState(
|
||||
val pairingId: String,
|
||||
val status: String,
|
||||
val qrPayload: String?,
|
||||
val mode: String,
|
||||
val allowedUsers: String,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** Which config slot a model-picker selection writes to. */
|
||||
private sealed interface ModelPickerTarget {
|
||||
data object Main : ModelPickerTarget
|
||||
@@ -424,6 +467,9 @@ fun DashboardManagementScreen(
|
||||
val pendingMcpOAuth by oauthViewModel.pending.collectAsState()
|
||||
val unsupportedOAuthRoutes by oauthViewModel.unsupportedRoutes.collectAsState()
|
||||
val supportedOAuthRoutes by oauthViewModel.supportedRoutes.collectAsState()
|
||||
val clientFactory = remember(dashboardUrl, connectionViewModel) {
|
||||
{ connectionViewModel.dashboardClientForActive(dashboardUrl) }
|
||||
}
|
||||
var selectedTab by remember { mutableStateOf(0) }
|
||||
var showingDetail by remember { mutableStateOf(false) }
|
||||
var reloadNonce by remember { mutableStateOf(0) }
|
||||
@@ -446,6 +492,66 @@ fun DashboardManagementScreen(
|
||||
var oauthDialogHidden by remember(pendingMcpOAuth?.flowId) { mutableStateOf(false) }
|
||||
var customEndpointEditor by remember { mutableStateOf<DashboardSummaryItem?>(null) }
|
||||
var showCustomEndpointEditor by remember { mutableStateOf(false) }
|
||||
var learningEditor by remember { mutableStateOf<LearningEditorState?>(null) }
|
||||
var memoryProviderEditor by remember { mutableStateOf<MemoryProviderEditorState?>(null) }
|
||||
var showWhatsAppSetup by remember { mutableStateOf(false) }
|
||||
var whatsappOnboarding by remember { mutableStateOf<WhatsAppOnboardingState?>(null) }
|
||||
var backupArchive by remember { mutableStateOf<String?>(null) }
|
||||
var importArchiveInput by remember { mutableStateOf(false) }
|
||||
var pendingBackupDownload by remember { mutableStateOf<String?>(null) }
|
||||
val backupSaveLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
val archive = pendingBackupDownload
|
||||
pendingBackupDownload = null
|
||||
if (uri != null && archive != null) scope.launch {
|
||||
actionInFlight = true
|
||||
withDashboardClient(clientFactory) {
|
||||
it.downloadServerBackup(archive) {
|
||||
context.contentResolver.openOutputStream(uri)
|
||||
?: throw IOException("The selected destination could not be opened.")
|
||||
}
|
||||
}.fold(
|
||||
onSuccess = { actionMessage = context.getString(R.string.dashboard_backup_saved, it) },
|
||||
onFailure = {
|
||||
withContext(Dispatchers.IO) { runCatching { context.contentResolver.delete(uri, null, null) } }
|
||||
actionMessage = it.message ?: context.getString(R.string.dashboard_backup_download_failed)
|
||||
},
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
}
|
||||
val backupImportLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) scope.launch {
|
||||
actionInFlight = true
|
||||
val metadata = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
dashboardImportMetadata(context.contentResolver, uri)
|
||||
}
|
||||
}
|
||||
metadata.fold(
|
||||
onSuccess = { file ->
|
||||
withDashboardClient(clientFactory) {
|
||||
it.uploadServerBackup(
|
||||
filename = file.name,
|
||||
contentLength = file.length,
|
||||
openStream = {
|
||||
context.contentResolver.openInputStream(uri)
|
||||
?: throw IOException("The selected archive could not be opened.")
|
||||
},
|
||||
)
|
||||
}.fold(
|
||||
onSuccess = { actionMessage = context.getString(R.string.dashboard_import_started) },
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_import_failed) },
|
||||
)
|
||||
},
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_import_failed) },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
val section = managementSections[selectedTab]
|
||||
val connectionId = activeConnection?.id ?: "default"
|
||||
@@ -490,10 +596,6 @@ fun DashboardManagementScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
val clientFactory = remember(dashboardUrl, connectionViewModel) {
|
||||
{ connectionViewModel.dashboardClientForActive(dashboardUrl) }
|
||||
}
|
||||
|
||||
suspend fun loadDashboardSection(
|
||||
targetSection: DashboardManagementSection,
|
||||
targetKey: String,
|
||||
@@ -828,9 +930,10 @@ fun DashboardManagementScreen(
|
||||
}
|
||||
actionMessage = result.fold(
|
||||
onSuccess = { root ->
|
||||
backupArchive = root.stringField("archive")
|
||||
root.stringField("message")
|
||||
?: root.stringField("filename")?.let { "Server backup ready: $it" }
|
||||
?: "Server backup created."
|
||||
?: root.stringField("archive")?.let { "Server backup started: $it" }
|
||||
?: "Server backup started."
|
||||
},
|
||||
onFailure = { error -> error.message ?: "Server backup failed." },
|
||||
)
|
||||
@@ -838,6 +941,41 @@ fun DashboardManagementScreen(
|
||||
}
|
||||
}
|
||||
|
||||
fun openLearningEditor(item: DashboardSummaryItem) {
|
||||
if (actionInFlight) return
|
||||
actionInFlight = true
|
||||
scope.launch {
|
||||
val result = withDashboardClient(clientFactory) { it.getLearningNode(item.id, effectiveProfileName) }
|
||||
result.fold(
|
||||
onSuccess = { root ->
|
||||
learningEditor = LearningEditorState(
|
||||
id = item.id,
|
||||
title = item.title,
|
||||
initialContent = root.stringField("content").orEmpty(),
|
||||
profile = effectiveProfileName,
|
||||
)
|
||||
},
|
||||
onFailure = { actionMessage = it.message ?: "Learning node could not be loaded." },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
fun openMemoryProvider(item: DashboardSummaryItem) {
|
||||
if (actionInFlight) return
|
||||
actionInFlight = true
|
||||
scope.launch {
|
||||
val result = withDashboardClient(clientFactory) {
|
||||
it.getMemoryProviderConfig(item.id, effectiveProfileName)
|
||||
}
|
||||
result.fold(
|
||||
onSuccess = { memoryProviderEditor = MemoryProviderEditorState(item.id, it, effectiveProfileName) },
|
||||
onFailure = { actionMessage = it.message ?: "Memory provider configuration could not be loaded." },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(dashboardUrl, selectedTab, reloadNonce, activeConnection?.id, effectiveProfileName) {
|
||||
val forceCurrent = forceReloadKey == payloadKey
|
||||
loadDashboardSection(
|
||||
@@ -909,6 +1047,7 @@ fun DashboardManagementScreen(
|
||||
|
||||
pendingAction?.let { pending ->
|
||||
val isActivateProfile = pending.action.kind == DashboardActionKind.ActivateProfile
|
||||
val isDeleteLearning = pending.action.kind == DashboardActionKind.DeleteLearningNode
|
||||
val actionLabel = dashboardActionLabel(pending.action)
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingAction = null },
|
||||
@@ -922,6 +1061,8 @@ fun DashboardManagementScreen(
|
||||
Text(
|
||||
text = if (isActivateProfile) {
|
||||
stringResource(R.string.dashboard_activate_profile_body, pending.item.title)
|
||||
} else if (isDeleteLearning) {
|
||||
stringResource(R.string.dashboard_learning_delete_warning)
|
||||
} else {
|
||||
stringResource(R.string.dashboard_generic_action_body, pending.item.title)
|
||||
},
|
||||
@@ -1354,6 +1495,9 @@ fun DashboardManagementScreen(
|
||||
)
|
||||
DashboardActionKind.EditProfileSoul ->
|
||||
openSoulEditor(item)
|
||||
DashboardActionKind.EditLearningNode -> openLearningEditor(item)
|
||||
DashboardActionKind.ConfigureMemoryProvider -> openMemoryProvider(item)
|
||||
DashboardActionKind.SetupWhatsApp -> showWhatsAppSetup = true
|
||||
DashboardActionKind.AuthenticateMcp ->
|
||||
if (mcpOAuthStartAllowed) {
|
||||
oauthDialogHidden = false
|
||||
@@ -1370,7 +1514,9 @@ fun DashboardManagementScreen(
|
||||
// per-conversation switch in chat.
|
||||
DashboardActionKind.ActivateProfile,
|
||||
DashboardActionKind.ActivateCustomEndpoint,
|
||||
DashboardActionKind.DeleteCustomEndpoint ->
|
||||
DashboardActionKind.DeleteCustomEndpoint,
|
||||
DashboardActionKind.ActivateMemoryProvider,
|
||||
DashboardActionKind.DeleteLearningNode ->
|
||||
pendingAction = PendingDashboardAction(item, action)
|
||||
else -> if (action.destructive) {
|
||||
pendingAction = PendingDashboardAction(item, action)
|
||||
@@ -1395,6 +1541,20 @@ fun DashboardManagementScreen(
|
||||
}
|
||||
DashboardSectionAction.CreateServerBackup ->
|
||||
runServerBackup()
|
||||
DashboardSectionAction.DownloadServerBackup -> {
|
||||
val archive = backupArchive
|
||||
if (archive == null) {
|
||||
actionMessage = context.getString(R.string.dashboard_backup_create_first)
|
||||
} else {
|
||||
pendingBackupDownload = archive
|
||||
backupSaveLauncher.launch(
|
||||
archive.substringAfterLast('/').substringAfterLast('\\')
|
||||
.ifBlank { "hermes-backup.zip" },
|
||||
)
|
||||
}
|
||||
}
|
||||
DashboardSectionAction.ImportServerBackup -> importArchiveInput = true
|
||||
DashboardSectionAction.SetupWhatsApp -> showWhatsAppSetup = true
|
||||
}
|
||||
},
|
||||
mcpOAuthSupported = mcpOAuthStartAllowed,
|
||||
@@ -1432,6 +1592,141 @@ fun DashboardManagementScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
learningEditor?.let { editor ->
|
||||
TextDocumentEditorDialog(
|
||||
title = context.getString(R.string.dashboard_learning_edit_title, editor.title),
|
||||
initialContent = editor.initialContent,
|
||||
warning = context.getString(R.string.dashboard_learning_edit_warning),
|
||||
saving = actionInFlight,
|
||||
onSave = { content ->
|
||||
scope.launch {
|
||||
actionInFlight = true
|
||||
withDashboardClient(clientFactory) {
|
||||
it.updateLearningNode(editor.id, content, editor.profile)
|
||||
}.fold(
|
||||
onSuccess = {
|
||||
learningEditor = null
|
||||
forceReloadKey = payloadKey
|
||||
reloadNonce += 1
|
||||
actionMessage = context.getString(R.string.dashboard_learning_saved)
|
||||
},
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_learning_save_failed) },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
},
|
||||
onDismiss = { learningEditor = null },
|
||||
)
|
||||
}
|
||||
|
||||
memoryProviderEditor?.let { editor ->
|
||||
MemoryProviderDialog(
|
||||
editor = editor,
|
||||
saving = actionInFlight,
|
||||
onSubmit = { rawValues, setup ->
|
||||
val values = if (setup) JsonObject(emptyMap())
|
||||
else runCatching { Json.parseToJsonElement(rawValues).jsonObject }.getOrNull()
|
||||
if (!setup && values == null) {
|
||||
actionMessage = context.getString(R.string.dashboard_memory_invalid_json)
|
||||
} else scope.launch {
|
||||
actionInFlight = true
|
||||
val result = withDashboardClient(clientFactory) { client ->
|
||||
if (setup) client.setupMemoryProvider(editor.name)
|
||||
else client.updateMemoryProviderConfig(editor.name, checkNotNull(values), editor.profile)
|
||||
}
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
memoryProviderEditor = null
|
||||
forceReloadKey = payloadKey
|
||||
reloadNonce += 1
|
||||
actionMessage = if (setup) context.getString(R.string.dashboard_memory_setup_started)
|
||||
else context.getString(R.string.dashboard_memory_saved)
|
||||
},
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_memory_save_failed) },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
},
|
||||
onDismiss = { memoryProviderEditor = null },
|
||||
)
|
||||
}
|
||||
|
||||
if (importArchiveInput) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { importArchiveInput = false },
|
||||
title = { Text(stringResource(R.string.dashboard_import_title)) },
|
||||
text = { Text(stringResource(R.string.dashboard_import_warning)) },
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
importArchiveInput = false
|
||||
backupImportLauncher.launch(arrayOf("application/zip", "application/octet-stream"))
|
||||
},
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
) { Text(stringResource(R.string.dashboard_import_confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { importArchiveInput = false }) { Text(stringResource(R.string.dashboard_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showWhatsAppSetup) {
|
||||
WhatsAppSetupDialog(
|
||||
onboarding = whatsappOnboarding,
|
||||
busy = actionInFlight,
|
||||
onStart = { mode, allowed ->
|
||||
scope.launch {
|
||||
actionInFlight = true
|
||||
withDashboardClient(clientFactory) {
|
||||
it.startWhatsAppOnboarding(mode, allowed, effectiveProfileName)
|
||||
}.fold(
|
||||
onSuccess = { root -> whatsappOnboarding = root.toWhatsAppOnboarding(mode, allowed) },
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_whatsapp_start_failed) },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
},
|
||||
onApply = { state ->
|
||||
scope.launch {
|
||||
actionInFlight = true
|
||||
withDashboardClient(clientFactory) {
|
||||
it.applyWhatsAppOnboarding(state.pairingId, state.mode, state.allowedUsers, effectiveProfileName)
|
||||
}.fold(
|
||||
onSuccess = {
|
||||
showWhatsAppSetup = false
|
||||
whatsappOnboarding = null
|
||||
forceReloadKey = payloadKey
|
||||
reloadNonce += 1
|
||||
actionMessage = context.getString(R.string.dashboard_whatsapp_saved)
|
||||
},
|
||||
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_whatsapp_apply_failed) },
|
||||
)
|
||||
actionInFlight = false
|
||||
}
|
||||
},
|
||||
onDismiss = {
|
||||
whatsappOnboarding?.pairingId?.let { pairingId ->
|
||||
scope.launch { withDashboardClient(clientFactory) { it.cancelWhatsAppOnboarding(pairingId) } }
|
||||
}
|
||||
whatsappOnboarding = null
|
||||
showWhatsAppSetup = false
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(whatsappOnboarding?.pairingId, whatsappOnboarding?.status) {
|
||||
val pairingId = whatsappOnboarding?.pairingId ?: return@LaunchedEffect
|
||||
while (true) {
|
||||
val current = whatsappOnboarding ?: break
|
||||
if (current.pairingId != pairingId || current.status in setOf("connected", "error", "expired", "cancelled")) break
|
||||
delay(1_500)
|
||||
withDashboardClient(clientFactory) { it.getWhatsAppOnboarding(pairingId) }
|
||||
.onSuccess { whatsappOnboarding = it.toWhatsAppOnboarding(current.mode, current.allowedUsers) }
|
||||
.onFailure { whatsappOnboarding = current.copy(status = "error", error = it.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class ManageTileSpec(
|
||||
@@ -2296,6 +2591,9 @@ private fun LoadedBody(
|
||||
val actionLabelUpdateInstalled = stringResource(R.string.dashboard_section_action_update_installed)
|
||||
val actionLabelAddEndpoint = stringResource(R.string.dashboard_custom_endpoint_add)
|
||||
val actionLabelServerBackup = stringResource(R.string.dashboard_section_action_server_backup)
|
||||
val actionLabelDownloadBackup = stringResource(R.string.dashboard_section_action_download_backup)
|
||||
val actionLabelImportBackup = stringResource(R.string.dashboard_section_action_import_backup)
|
||||
val actionLabelSetupWhatsApp = stringResource(R.string.dashboard_action_setup_whatsapp)
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(
|
||||
@@ -2325,6 +2623,11 @@ private fun LoadedBody(
|
||||
)
|
||||
DashboardManagementSection.Operations -> listOf(
|
||||
DashboardSectionAction.CreateServerBackup to actionLabelServerBackup,
|
||||
DashboardSectionAction.DownloadServerBackup to actionLabelDownloadBackup,
|
||||
DashboardSectionAction.ImportServerBackup to actionLabelImportBackup,
|
||||
)
|
||||
DashboardManagementSection.Channels -> listOf(
|
||||
DashboardSectionAction.SetupWhatsApp to actionLabelSetupWhatsApp,
|
||||
)
|
||||
else -> emptyList()
|
||||
}
|
||||
@@ -2420,6 +2723,14 @@ private fun dashboardActionLabel(kind: DashboardActionKind): String = when (kind
|
||||
DashboardActionKind.ValidateCustomEndpoint -> stringResource(R.string.dashboard_action_validate)
|
||||
DashboardActionKind.ActivateCustomEndpoint -> stringResource(R.string.dashboard_action_use)
|
||||
DashboardActionKind.DeleteCustomEndpoint -> stringResource(R.string.dashboard_action_delete)
|
||||
DashboardActionKind.EditLearningNode -> stringResource(R.string.dashboard_action_edit)
|
||||
DashboardActionKind.DeleteLearningNode -> stringResource(R.string.dashboard_action_delete)
|
||||
DashboardActionKind.ConfigureMemoryProvider -> stringResource(R.string.dashboard_action_configure)
|
||||
DashboardActionKind.ActivateMemoryProvider -> stringResource(R.string.dashboard_action_use)
|
||||
DashboardActionKind.SetupWhatsApp -> stringResource(R.string.dashboard_action_setup)
|
||||
DashboardActionKind.EnableChannel -> stringResource(R.string.dashboard_action_enable)
|
||||
DashboardActionKind.DisableChannel -> stringResource(R.string.dashboard_action_disable)
|
||||
DashboardActionKind.TestChannel -> stringResource(R.string.dashboard_action_test)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2454,6 +2765,14 @@ private fun dashboardActionLabel(context: android.content.Context, kind: Dashboa
|
||||
DashboardActionKind.ValidateCustomEndpoint -> context.getString(R.string.dashboard_action_validate)
|
||||
DashboardActionKind.ActivateCustomEndpoint -> context.getString(R.string.dashboard_action_use)
|
||||
DashboardActionKind.DeleteCustomEndpoint -> context.getString(R.string.dashboard_action_delete)
|
||||
DashboardActionKind.EditLearningNode -> context.getString(R.string.dashboard_action_edit)
|
||||
DashboardActionKind.DeleteLearningNode -> context.getString(R.string.dashboard_action_delete)
|
||||
DashboardActionKind.ConfigureMemoryProvider -> context.getString(R.string.dashboard_action_configure)
|
||||
DashboardActionKind.ActivateMemoryProvider -> context.getString(R.string.dashboard_action_use)
|
||||
DashboardActionKind.SetupWhatsApp -> context.getString(R.string.dashboard_action_setup)
|
||||
DashboardActionKind.EnableChannel -> context.getString(R.string.dashboard_action_enable)
|
||||
DashboardActionKind.DisableChannel -> context.getString(R.string.dashboard_action_disable)
|
||||
DashboardActionKind.TestChannel -> context.getString(R.string.dashboard_action_test)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@@ -3793,14 +4112,32 @@ private fun summarize(
|
||||
?.map { (name, value) -> summarizeObjectItem(value, name) }
|
||||
?: listOf(summarizeObjectItem(root, "Profile"))
|
||||
}
|
||||
DashboardManagementSection.Memory -> summarizeKeyValueOrList(root, "Memory")
|
||||
DashboardManagementSection.Memory -> summarizeMemoryProviders(root)
|
||||
DashboardManagementSection.Learning ->
|
||||
root.arrayItems("nodes", "items")
|
||||
?.mapIndexed { index, item -> summarizeObjectItem(item, "Node ${index + 1}") }
|
||||
?.mapIndexed { index, item ->
|
||||
val summary = summarizeObjectItem(item, "Node ${index + 1}")
|
||||
summary.copy(
|
||||
actions = listOf(
|
||||
DashboardItemAction("Edit", DashboardActionKind.EditLearningNode),
|
||||
DashboardItemAction("Delete", DashboardActionKind.DeleteLearningNode, destructive = true),
|
||||
),
|
||||
)
|
||||
}
|
||||
?: summarizeKeyValueOrList(root, "Learning")
|
||||
DashboardManagementSection.Channels ->
|
||||
root.arrayItems("platforms", "channels", "items")
|
||||
?.mapIndexed { index, item -> summarizeObjectItem(item, "Channel ${index + 1}") }
|
||||
?.mapIndexed { index, item ->
|
||||
val summary = summarizeObjectItem(item, "Channel ${index + 1}")
|
||||
val enabled = (item as? JsonObject)?.booleanField("enabled") == true
|
||||
summary.copy(actions = buildList {
|
||||
add(DashboardItemAction(if (enabled) "Disable" else "Enable", if (enabled) DashboardActionKind.DisableChannel else DashboardActionKind.EnableChannel))
|
||||
add(DashboardItemAction("Test", DashboardActionKind.TestChannel))
|
||||
if (summary.id.equals("whatsapp", ignoreCase = true)) {
|
||||
add(DashboardItemAction("Setup", DashboardActionKind.SetupWhatsApp))
|
||||
}
|
||||
})
|
||||
}
|
||||
?: summarizeKeyValueOrList(root, "Channel")
|
||||
DashboardManagementSection.Operations -> summarizeKeyValueOrList(root, "Status")
|
||||
DashboardManagementSection.Models -> summarizeKeyValueOrList(root, "Model")
|
||||
@@ -3809,6 +4146,32 @@ private fun summarize(
|
||||
}
|
||||
}
|
||||
|
||||
private fun summarizeMemoryProviders(root: JsonElement): List<DashboardSummaryItem> {
|
||||
val obj = root as? JsonObject ?: return emptyList()
|
||||
val active = obj.stringField("active").orEmpty()
|
||||
return obj.arrayItems("providers").orEmpty().mapIndexed { index, provider ->
|
||||
val summary = summarizeObjectItem(provider, "Provider ${index + 1}")
|
||||
val providerObj = provider as? JsonObject
|
||||
val available = providerObj?.booleanField("available") != false
|
||||
val configured = providerObj?.booleanField("configured") == true ||
|
||||
providerObj?.booleanField("ready") == true
|
||||
summary.copy(
|
||||
meta = listOfNotNull(
|
||||
if (summary.id == active) "active" else null,
|
||||
if (available) "available" else "setup required",
|
||||
summary.meta,
|
||||
).joinToString(" · "),
|
||||
actions = buildList {
|
||||
add(DashboardItemAction("Configure", DashboardActionKind.ConfigureMemoryProvider))
|
||||
if (summary.id != active && configured) {
|
||||
add(DashboardItemAction("Use", DashboardActionKind.ActivateMemoryProvider))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /api/env` returns a map of var name → metadata. Upstream's SPA hides
|
||||
* `channel_managed` vars because its Channels page owns them — we have no
|
||||
@@ -4064,6 +4427,14 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
|
||||
from = DashboardActionKind.DisableMcp,
|
||||
to = DashboardItemAction("Enable", DashboardActionKind.EnableMcp),
|
||||
)
|
||||
DashboardActionKind.EnableChannel -> withEnabledMeta(true).withActionSwap(
|
||||
from = DashboardActionKind.EnableChannel,
|
||||
to = DashboardItemAction("Disable", DashboardActionKind.DisableChannel),
|
||||
)
|
||||
DashboardActionKind.DisableChannel -> withEnabledMeta(false).withActionSwap(
|
||||
from = DashboardActionKind.DisableChannel,
|
||||
to = DashboardItemAction("Enable", DashboardActionKind.EnableChannel),
|
||||
)
|
||||
DashboardActionKind.PauseCron -> withActionSwap(
|
||||
from = DashboardActionKind.PauseCron,
|
||||
to = DashboardItemAction("Resume", DashboardActionKind.ResumeCron),
|
||||
@@ -4075,7 +4446,8 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
|
||||
DashboardActionKind.DeleteCron,
|
||||
DashboardActionKind.RemoveMcp,
|
||||
DashboardActionKind.DeleteProfile,
|
||||
DashboardActionKind.DeleteCustomEndpoint -> null
|
||||
DashboardActionKind.DeleteCustomEndpoint,
|
||||
DashboardActionKind.DeleteLearningNode -> null
|
||||
DashboardActionKind.InstallMcpCatalog -> copy(
|
||||
meta = appendMeta(meta, "installed"),
|
||||
actions = emptyList(),
|
||||
@@ -4094,7 +4466,12 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
|
||||
DashboardActionKind.RevealEnvKey,
|
||||
DashboardActionKind.EditProfileDescription,
|
||||
DashboardActionKind.SetProfileModel,
|
||||
DashboardActionKind.EditProfileSoul -> this
|
||||
DashboardActionKind.EditProfileSoul,
|
||||
DashboardActionKind.EditLearningNode,
|
||||
DashboardActionKind.ConfigureMemoryProvider,
|
||||
DashboardActionKind.ActivateMemoryProvider,
|
||||
DashboardActionKind.SetupWhatsApp,
|
||||
DashboardActionKind.TestChannel -> this
|
||||
DashboardActionKind.EditCustomEndpoint,
|
||||
DashboardActionKind.ValidateCustomEndpoint,
|
||||
DashboardActionKind.ActivateCustomEndpoint -> this
|
||||
@@ -4226,6 +4603,11 @@ private suspend fun DashboardApiClient.runDashboardAction(
|
||||
deleteCustomEndpoint(id, profile = item.profile).map { JsonObject(emptyMap()) }
|
||||
DashboardActionKind.RevealEnvKey -> revealEnvVar(id)
|
||||
DashboardActionKind.ClearEnvKey -> deleteEnvVar(id)
|
||||
DashboardActionKind.DeleteLearningNode -> deleteLearningNode(id, item.profile)
|
||||
DashboardActionKind.ActivateMemoryProvider -> activateMemoryProvider(id, item.profile)
|
||||
DashboardActionKind.EnableChannel -> setMessagingPlatformEnabled(id, true, item.profile)
|
||||
DashboardActionKind.DisableChannel -> setMessagingPlatformEnabled(id, false, item.profile)
|
||||
DashboardActionKind.TestChannel -> testMessagingPlatform(id, item.profile)
|
||||
// Input-backed kinds are intercepted at the onAction layer and routed
|
||||
// to dialogs; reaching here means a wiring bug, not a server problem.
|
||||
DashboardActionKind.SetEnvKey,
|
||||
@@ -4233,6 +4615,10 @@ private suspend fun DashboardApiClient.runDashboardAction(
|
||||
DashboardActionKind.SetProfileModel,
|
||||
DashboardActionKind.EditProfileSoul ->
|
||||
Result.failure(IllegalStateException("${action.label} requires input"))
|
||||
DashboardActionKind.EditLearningNode,
|
||||
DashboardActionKind.ConfigureMemoryProvider,
|
||||
DashboardActionKind.SetupWhatsApp ->
|
||||
Result.failure(IllegalStateException("${action.label} requires input"))
|
||||
DashboardActionKind.EditCustomEndpoint,
|
||||
DashboardActionKind.ValidateCustomEndpoint ->
|
||||
Result.failure(IllegalStateException("${action.label} requires input"))
|
||||
@@ -4294,3 +4680,192 @@ private fun compactJsonLines(root: JsonObject): String =
|
||||
root.entries.joinToString("\n") { (key, value) ->
|
||||
"$key: ${value.shortDisplay()}"
|
||||
}.ifBlank { "{ }" }
|
||||
|
||||
private fun JsonObject.toWhatsAppOnboarding(mode: String, allowedUsers: String): WhatsAppOnboardingState =
|
||||
WhatsAppOnboardingState(
|
||||
pairingId = stringField("pairing_id").orEmpty(),
|
||||
status = stringField("status").orEmpty(),
|
||||
qrPayload = stringField("qr_payload"),
|
||||
mode = stringField("mode") ?: mode,
|
||||
allowedUsers = stringField("allowed_users") ?: allowedUsers,
|
||||
error = stringField("error"),
|
||||
)
|
||||
|
||||
private fun memoryInitialValues(schema: JsonObject): String {
|
||||
val direct = schema["values"] as? JsonObject
|
||||
if (direct != null) return Json { prettyPrint = true }.encodeToString(JsonObject.serializer(), direct)
|
||||
val fields = schema["fields"] as? JsonArray ?: return "{}"
|
||||
val values = buildJsonObject {
|
||||
fields.forEach { element ->
|
||||
val field = element as? JsonObject ?: return@forEach
|
||||
val key = field.stringField("key") ?: return@forEach
|
||||
field["value"]?.let { put(key, it) }
|
||||
}
|
||||
}
|
||||
return Json { prettyPrint = true }.encodeToString(JsonObject.serializer(), values)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TextDocumentEditorDialog(
|
||||
title: String,
|
||||
initialContent: String,
|
||||
warning: String,
|
||||
saving: Boolean,
|
||||
onSave: (String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var content by remember(initialContent) { mutableStateOf(initialContent) }
|
||||
Dialog(onDismissRequest = { if (!saving) onDismiss() }) {
|
||||
Card(modifier = Modifier.fillMaxWidth().heightIn(min = 360.dp, max = 680.dp)) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
Text(warning, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
OutlinedTextField(
|
||||
value = content,
|
||||
onValueChange = { content = it },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
enabled = !saving,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = onDismiss, enabled = !saving) { Text(stringResource(R.string.dashboard_cancel)) }
|
||||
Button(onClick = { onSave(content) }, enabled = !saving && content.isNotBlank()) {
|
||||
Text(stringResource(R.string.dashboard_save))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryProviderDialog(
|
||||
editor: MemoryProviderEditorState,
|
||||
saving: Boolean,
|
||||
onSubmit: (String, Boolean) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var values by remember(editor) { mutableStateOf(memoryInitialValues(editor.schema)) }
|
||||
val fields = editor.schema["fields"] as? JsonArray
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!saving) onDismiss() },
|
||||
title = { Text(stringResource(R.string.dashboard_memory_config_title, editor.name)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.dashboard_memory_config_help), style = MaterialTheme.typography.bodySmall)
|
||||
if (!fields.isNullOrEmpty()) {
|
||||
Text(fields.joinToString("\n") { field ->
|
||||
val obj = field as? JsonObject
|
||||
val key = obj?.stringField("key").orEmpty()
|
||||
val label = obj?.stringField("label") ?: key
|
||||
val required = if (obj?.booleanField("required") == true) " *" else ""
|
||||
"$label$required"
|
||||
}, style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = values,
|
||||
onValueChange = { values = it },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 160.dp),
|
||||
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
enabled = !saving,
|
||||
label = { Text(stringResource(R.string.dashboard_memory_values_json)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = { onSubmit(values, false) }, enabled = !saving) { Text(stringResource(R.string.dashboard_save)) }
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
TextButton(onClick = { onSubmit(values, true) }, enabled = !saving) { Text(stringResource(R.string.dashboard_memory_run_setup)) }
|
||||
TextButton(onClick = onDismiss, enabled = !saving) { Text(stringResource(R.string.dashboard_cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun qrBitmap(payload: String): Bitmap {
|
||||
val matrix = QRCodeWriter().encode(payload, BarcodeFormat.QR_CODE, 640, 640)
|
||||
val pixels = IntArray(matrix.width * matrix.height)
|
||||
for (y in 0 until matrix.height) for (x in 0 until matrix.width) {
|
||||
pixels[y * matrix.width + x] = if (matrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE
|
||||
}
|
||||
return Bitmap.createBitmap(pixels, matrix.width, matrix.height, Bitmap.Config.ARGB_8888)
|
||||
}
|
||||
|
||||
private data class DashboardImportMetadata(val name: String, val length: Long?)
|
||||
|
||||
private fun dashboardImportMetadata(resolver: ContentResolver, uri: Uri): DashboardImportMetadata {
|
||||
var name: String? = null
|
||||
var length: Long? = null
|
||||
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)
|
||||
?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
|
||||
if (nameIndex >= 0 && !cursor.isNull(nameIndex)) name = cursor.getString(nameIndex)
|
||||
if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) length = cursor.getLong(sizeIndex).takeIf { it >= 0 }
|
||||
}
|
||||
}
|
||||
return DashboardImportMetadata(
|
||||
name = name?.takeIf { it.isNotBlank() }
|
||||
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
|
||||
?: "hermes-backup.zip",
|
||||
length = length,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WhatsAppSetupDialog(
|
||||
onboarding: WhatsAppOnboardingState?,
|
||||
busy: Boolean,
|
||||
onStart: (String, String) -> Unit,
|
||||
onApply: (WhatsAppOnboardingState) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var mode by remember { mutableStateOf("bot") }
|
||||
var allowedUsers by remember { mutableStateOf("") }
|
||||
val qr = remember(onboarding?.qrPayload) {
|
||||
onboarding?.qrPayload?.let { runCatching { qrBitmap(it) }.getOrNull() }
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
title = { Text(stringResource(R.string.dashboard_whatsapp_title)) },
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
if (onboarding == null) {
|
||||
Text(stringResource(R.string.dashboard_whatsapp_help), style = MaterialTheme.typography.bodySmall)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { mode = "bot" }) { Text(stringResource(R.string.dashboard_whatsapp_bot)) }
|
||||
OutlinedButton(onClick = { mode = "self-chat" }) { Text(stringResource(R.string.dashboard_whatsapp_self_chat)) }
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = allowedUsers,
|
||||
onValueChange = { allowedUsers = it },
|
||||
label = { Text(stringResource(R.string.dashboard_whatsapp_allowed_users)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(onboarding.status.replace('_', ' ').uppercase(), style = MaterialTheme.typography.labelMedium)
|
||||
qr?.let { Image(it.asImageBitmap(), contentDescription = stringResource(R.string.dashboard_whatsapp_qr), modifier = Modifier.size(280.dp)) }
|
||||
onboarding.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
if (onboarding.status !in setOf("connected", "error", "expired")) {
|
||||
Text(stringResource(R.string.dashboard_whatsapp_scan), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
if (onboarding == null) {
|
||||
Button(onClick = { onStart(mode, allowedUsers) }, enabled = !busy) { Text(stringResource(R.string.dashboard_whatsapp_start)) }
|
||||
} else if (onboarding.status == "connected") {
|
||||
Button(onClick = { onApply(onboarding) }, enabled = !busy) { Text(stringResource(R.string.dashboard_whatsapp_apply)) }
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss, enabled = !busy) { Text(stringResource(R.string.dashboard_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -4235,6 +4376,7 @@ class ChatViewModel : ViewModel() {
|
||||
HermesCardInput.Kinds.CHOICE
|
||||
},
|
||||
choices = ask.choices.orEmpty(),
|
||||
multiSelect = ask.multiSelect,
|
||||
allowFreeText = true,
|
||||
expiresAtMillis = expiresAt,
|
||||
),
|
||||
@@ -4500,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
|
||||
}
|
||||
@@ -4634,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)
|
||||
}
|
||||
@@ -4761,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(
|
||||
@@ -4777,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)
|
||||
@@ -5041,6 +5183,7 @@ class ChatViewModel : ViewModel() {
|
||||
requestId = ask.ask.requestId,
|
||||
text = ask.ask.text,
|
||||
choices = ask.ask.choices,
|
||||
multiSelect = ask.ask.multiSelect,
|
||||
smartDenied = ask.ask.smartDenied,
|
||||
envVar = ask.ask.envVar,
|
||||
timeoutSeconds = ask.ask.timeoutSeconds,
|
||||
@@ -5225,6 +5368,7 @@ class ChatViewModel : ViewModel() {
|
||||
requestId = saved.requestId,
|
||||
text = saved.text,
|
||||
choices = saved.choices,
|
||||
multiSelect = saved.multiSelect,
|
||||
smartDenied = saved.smartDenied,
|
||||
envVar = saved.envVar,
|
||||
timeoutSeconds = saved.timeoutSeconds,
|
||||
@@ -7661,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
|
||||
@@ -7826,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) {
|
||||
@@ -7894,6 +8008,7 @@ class ChatViewModel : ViewModel() {
|
||||
): String? {
|
||||
val selectedProfile = selectedProfileProvider()
|
||||
val effectiveProfile = effectiveProfileOverride
|
||||
?: openedSessionDisplayProfile
|
||||
?: displayProfileProvider()
|
||||
?: effectiveProfileProvider()
|
||||
?: selectedProfile
|
||||
@@ -7902,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]
|
||||
|
||||
+330
-266
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
+60
-1
@@ -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 {
|
||||
|
||||
+47
-24
@@ -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 ----------------------------------------------
|
||||
|
||||
@@ -3834,6 +3834,16 @@
|
||||
<string name="dashboard_tab_channels_lower">canais</string>
|
||||
<string name="dashboard_tab_operations_lower">operações</string>
|
||||
<string name="dashboard_section_action_server_backup">Criar backup do servidor</string>
|
||||
<string name="dashboard_section_action_download_backup">Salvar backup mais recente</string>
|
||||
<string name="dashboard_section_action_import_backup">Importar backup</string>
|
||||
<string name="dashboard_backup_create_first">Crie um backup nesta sessão antes de baixá-lo.</string>
|
||||
<string name="dashboard_backup_download_failed">Não foi possível baixar o backup.</string>
|
||||
<string name="dashboard_backup_saved">Backup salvo como %1$s.</string>
|
||||
<string name="dashboard_import_title">Importar backup do servidor?</string>
|
||||
<string name="dashboard_import_warning">Isso envia o ZIP selecionado ao Hermes e inicia a importação autenticada no servidor. A configuração e os dados podem ser substituídos. Primeiro, crie e salve um backup atual.</string>
|
||||
<string name="dashboard_import_confirm">Importar</string>
|
||||
<string name="dashboard_import_started">Importação do servidor iniciada. Acompanhe a conclusão em Operações antes de reiniciar o Hermes.</string>
|
||||
<string name="dashboard_import_failed">Não foi possível iniciar a importação do servidor.</string>
|
||||
<string name="dashboard_profile_mcp_servers_optional">Servidores MCP (opcional)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">Nomes de servidor separados por vírgulas ou linhas. As credenciais permanecem no servidor.</string>
|
||||
<string name="dashboard_tile_memory_title">Memória</string>
|
||||
@@ -3844,7 +3854,89 @@
|
||||
<string name="dashboard_tile_channels_sub">Status das plataformas de mensagens, incluindo WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">Operações do servidor</string>
|
||||
<string name="dashboard_tile_operations_sub">Integridade do host e backup geral do servidor</string>
|
||||
<string name="dashboard_action_configure">Configurar</string>
|
||||
<string name="dashboard_action_setup">Configurar</string>
|
||||
<string name="dashboard_action_setup_whatsapp">Configurar o WhatsApp</string>
|
||||
<string name="dashboard_learning_edit_title">Editar %1$s</string>
|
||||
<string name="dashboard_learning_edit_warning">As edições substituem todo o conteúdo do nó. As habilidades excluídas do grafo são arquivadas pelo Hermes e podem ser restauradas; a exclusão de nós de memória é permanente, então exporte um backup primeiro.</string>
|
||||
<string name="dashboard_learning_saved">Nó de aprendizado salvo.</string>
|
||||
<string name="dashboard_learning_save_failed">Não foi possível salvar o nó de aprendizado.</string>
|
||||
<string name="dashboard_learning_delete_warning">O Hermes arquiva as habilidades aprendidas para que possam ser restauradas pelo servidor. A exclusão de nós de memória é permanente. Se este conteúdo puder ser necessário depois, salve primeiro um backup do servidor.</string>
|
||||
<string name="dashboard_memory_config_title">Configurar %1$s</string>
|
||||
<string name="dashboard_memory_config_help">Os valores permanecem no perfil do Hermes selecionado. Os campos secretos são aceitos pelo servidor e nunca retornados após o salvamento. Os campos obrigatórios são marcados com *.</string>
|
||||
<string name="dashboard_memory_values_json">Valores do provedor (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">Executar configuração</string>
|
||||
<string name="dashboard_memory_invalid_json">Os valores do provedor devem formar um objeto JSON.</string>
|
||||
<string name="dashboard_memory_setup_started">A instalação do provedor em todo o host foi iniciada. Atualize após a conclusão e salve os valores deste perfil.</string>
|
||||
<string name="dashboard_memory_saved">Provedor de memória configurado e ativado.</string>
|
||||
<string name="dashboard_memory_save_failed">Não foi possível salvar a configuração do provedor de memória.</string>
|
||||
<string name="dashboard_whatsapp_title">Configurar o WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_help">O Hermes inicia uma sessão de pareamento de dez minutos limitada ao perfil. Escolha o modo bot para uma conta dedicada ou conversa própria para enviar mensagens à sua conta vinculada.</string>
|
||||
<string name="dashboard_whatsapp_bot">Conta de bot</string>
|
||||
<string name="dashboard_whatsapp_self_chat">Conversa própria</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">Números de telefone permitidos (opcional)</string>
|
||||
<string name="dashboard_whatsapp_start">Iniciar pareamento</string>
|
||||
<string name="dashboard_whatsapp_scan">Escaneie este código na tela Dispositivos conectados do WhatsApp. Mantenha esta caixa de diálogo aberta enquanto o Hermes confirma a conta.</string>
|
||||
<string name="dashboard_whatsapp_qr">Código QR de dispositivo conectado do WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_apply">Ativar o WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_start_failed">Não foi possível iniciar o pareamento do WhatsApp.</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">Não foi possível salvar a configuração do WhatsApp.</string>
|
||||
<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>
|
||||
|
||||
@@ -3932,7 +3932,97 @@
|
||||
<string name="dashboard_tile_channels_sub">消息平台状态,包括 WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">服务器运维</string>
|
||||
<string name="dashboard_tile_operations_sub">主机健康状况和服务器整体备份</string>
|
||||
<string name="dashboard_section_action_download_backup">保存最新备份</string>
|
||||
<string name="dashboard_section_action_import_backup">导入备份</string>
|
||||
<string name="dashboard_backup_create_first">请先在本次会话中创建备份,再下载。</string>
|
||||
<string name="dashboard_backup_download_failed">无法下载备份。</string>
|
||||
<string name="dashboard_backup_saved">备份已保存为 %1$s。</string>
|
||||
<string name="dashboard_import_title">导入服务器备份?</string>
|
||||
<string name="dashboard_import_warning">这会将所选 ZIP 上传到 Hermes,并启动经过身份验证的服务器导入。导入可能替换配置和数据。请先创建并保存当前备份。</string>
|
||||
<string name="dashboard_import_confirm">导入</string>
|
||||
<string name="dashboard_import_started">服务器导入已启动。请在“运维”中等待完成,然后再重启 Hermes。</string>
|
||||
<string name="dashboard_import_failed">无法启动服务器导入。</string>
|
||||
<string name="dashboard_action_configure">配置</string>
|
||||
<string name="dashboard_action_setup">设置</string>
|
||||
<string name="dashboard_action_setup_whatsapp">设置 WhatsApp</string>
|
||||
<string name="dashboard_learning_edit_title">编辑 %1$s</string>
|
||||
<string name="dashboard_learning_edit_warning">编辑会替换节点的全部内容。Hermes 会归档从图谱中删除的技能,以便从归档中恢复;删除记忆节点则无法撤销,因此请先导出备份。</string>
|
||||
<string name="dashboard_learning_saved">学习节点已保存。</string>
|
||||
<string name="dashboard_learning_save_failed">无法保存学习节点。</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes 会归档已学习技能,以便从服务器归档中恢复。删除记忆节点则无法撤销。如果以后可能需要这些内容,请先保存服务器备份。</string>
|
||||
<string name="dashboard_memory_config_title">配置 %1$s</string>
|
||||
<string name="dashboard_memory_config_help">值会保留在所选 Hermes 配置文件中。服务器接受机密字段,但保存后绝不会返回这些字段。必填字段以 * 标记。</string>
|
||||
<string name="dashboard_memory_values_json">提供商值 (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">运行设置</string>
|
||||
<string name="dashboard_memory_invalid_json">提供商值必须是 JSON 对象。</string>
|
||||
<string name="dashboard_memory_setup_started">全主机范围的提供商安装已启动。完成后请刷新,然后保存此配置文件的值。</string>
|
||||
<string name="dashboard_memory_saved">记忆提供商已配置并启用。</string>
|
||||
<string name="dashboard_memory_save_failed">无法保存记忆提供商配置。</string>
|
||||
<string name="dashboard_whatsapp_title">设置 WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes 会启动一个时长十分钟、仅限当前配置文件的配对会话。专用账号请选择机器人模式;要向自己已关联的账号发消息,请选择自聊。</string>
|
||||
<string name="dashboard_whatsapp_bot">机器人账号</string>
|
||||
<string name="dashboard_whatsapp_self_chat">自聊</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">允许的电话号码(可选)</string>
|
||||
<string name="dashboard_whatsapp_start">开始配对</string>
|
||||
<string name="dashboard_whatsapp_scan">请在 WhatsApp 的“关联设备”页面扫描此代码。Hermes 确认账号期间,请保持此对话框打开。</string>
|
||||
<string name="dashboard_whatsapp_qr">WhatsApp 关联设备二维码</string>
|
||||
<string name="dashboard_whatsapp_apply">启用 WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_start_failed">无法开始 WhatsApp 配对。</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">无法保存 WhatsApp 配置。</string>
|
||||
<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>
|
||||
|
||||
@@ -4004,7 +4004,99 @@
|
||||
<string name="dashboard_tile_channels_sub">Status der Nachrichtenplattformen einschließlich WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">Serverbetrieb</string>
|
||||
<string name="dashboard_tile_operations_sub">Hostzustand und serverweite Sicherung</string>
|
||||
<string name="dashboard_section_action_download_backup">Neueste Sicherung speichern</string>
|
||||
<string name="dashboard_section_action_import_backup">Sicherung importieren</string>
|
||||
<string name="dashboard_backup_create_first">Erstellen Sie in dieser Sitzung eine Sicherung, bevor Sie sie herunterladen.</string>
|
||||
<string name="dashboard_backup_download_failed">Die Sicherung konnte nicht heruntergeladen werden.</string>
|
||||
<string name="dashboard_backup_saved">Sicherung als %1$s gespeichert.</string>
|
||||
<string name="dashboard_import_title">Server-Sicherung importieren?</string>
|
||||
<string name="dashboard_import_warning">Dies lädt die ausgewählte ZIP-Datei zu Hermes hoch und startet den authentifizierten Serverimport. Dabei können Konfiguration und Daten ersetzt werden. Erstellen und speichern Sie zuerst eine aktuelle Sicherung.</string>
|
||||
<string name="dashboard_import_confirm">Importieren</string>
|
||||
<string name="dashboard_import_started">Serverimport gestartet. Warten Sie unter „Betrieb“ auf den Abschluss, bevor Sie Hermes neu starten.</string>
|
||||
<string name="dashboard_import_failed">Der Serverimport konnte nicht gestartet werden.</string>
|
||||
<string name="dashboard_action_configure">Konfigurieren</string>
|
||||
<string name="dashboard_action_setup">Einrichten</string>
|
||||
<string name="dashboard_action_setup_whatsapp">WhatsApp einrichten</string>
|
||||
<string name="dashboard_learning_edit_title">%1$s bearbeiten</string>
|
||||
<string name="dashboard_learning_edit_warning">Beim Bearbeiten wird der gesamte Inhalt des Knotens ersetzt. Aus dem Graphen gelöschte Skills werden von Hermes archiviert und können aus dem Archiv wiederhergestellt werden. Das Löschen von Speicherknoten ist endgültig; exportieren Sie daher zuerst eine Sicherung.</string>
|
||||
<string name="dashboard_learning_saved">Lernknoten gespeichert.</string>
|
||||
<string name="dashboard_learning_save_failed">Der Lernknoten konnte nicht gespeichert werden.</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes archiviert erlernte Skills, sodass sie aus dem Serverarchiv wiederhergestellt werden können. Das Löschen von Speicherknoten ist endgültig. Speichern Sie zuerst eine Server-Sicherung, falls dieser Inhalt später noch benötigt wird.</string>
|
||||
<string name="dashboard_memory_config_title">%1$s konfigurieren</string>
|
||||
<string name="dashboard_memory_config_help">Die Werte verbleiben im ausgewählten Hermes-Profil. Vertrauliche Felder werden vom Server akzeptiert und nach dem Speichern nie zurückgegeben. Pflichtfelder sind mit * markiert.</string>
|
||||
<string name="dashboard_memory_values_json">Anbieterwerte (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">Einrichtung starten</string>
|
||||
<string name="dashboard_memory_invalid_json">Die Anbieterwerte müssen ein JSON-Objekt sein.</string>
|
||||
<string name="dashboard_memory_setup_started">Die hostweite Anbieterinstallation wurde gestartet. Aktualisieren Sie nach Abschluss die Ansicht und speichern Sie dann die Werte dieses Profils.</string>
|
||||
<string name="dashboard_memory_saved">Speicheranbieter konfiguriert und aktiviert.</string>
|
||||
<string name="dashboard_memory_save_failed">Die Konfiguration des Speicheranbieters konnte nicht gespeichert werden.</string>
|
||||
<string name="dashboard_whatsapp_title">WhatsApp einrichten</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes startet eine zehnminütige, profilbezogene Kopplungssitzung. Wählen Sie den Bot-Modus für ein eigenes Konto oder den Selbstchat, um Nachrichten an Ihr eigenes verknüpftes Konto zu senden.</string>
|
||||
<string name="dashboard_whatsapp_bot">Bot-Konto</string>
|
||||
<string name="dashboard_whatsapp_self_chat">Selbstchat</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">Zulässige Telefonnummern (optional)</string>
|
||||
<string name="dashboard_whatsapp_start">Kopplung starten</string>
|
||||
<string name="dashboard_whatsapp_scan">Scannen Sie diesen Code unter „Verknüpfte Geräte“ in WhatsApp. Lassen Sie diesen Dialog geöffnet, während Hermes das Konto bestätigt.</string>
|
||||
<string name="dashboard_whatsapp_qr">QR-Code für ein verknüpftes WhatsApp-Gerät</string>
|
||||
<string name="dashboard_whatsapp_apply">WhatsApp aktivieren</string>
|
||||
<string name="dashboard_whatsapp_start_failed">Die WhatsApp-Kopplung konnte nicht gestartet werden.</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">Die WhatsApp-Konfiguration konnte nicht gespeichert werden.</string>
|
||||
<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>
|
||||
|
||||
@@ -3689,7 +3689,99 @@
|
||||
<string name="dashboard_tile_channels_sub">Estado de plataformas de mensajería, incluido WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">Operaciones del servidor</string>
|
||||
<string name="dashboard_tile_operations_sub">Estado del host y copia de seguridad del servidor</string>
|
||||
<string name="dashboard_section_action_download_backup">Guardar la copia más reciente</string>
|
||||
<string name="dashboard_section_action_import_backup">Importar copia de seguridad</string>
|
||||
<string name="dashboard_backup_create_first">Crea una copia de seguridad en esta sesión antes de descargarla.</string>
|
||||
<string name="dashboard_backup_download_failed">No se pudo descargar la copia de seguridad.</string>
|
||||
<string name="dashboard_backup_saved">Copia de seguridad guardada como %1$s.</string>
|
||||
<string name="dashboard_import_title">¿Importar copia de seguridad del servidor?</string>
|
||||
<string name="dashboard_import_warning">Esto sube el ZIP seleccionado a Hermes e inicia la importación autenticada del servidor. Puede reemplazar la configuración y los datos. Crea y guarda primero una copia de seguridad actual.</string>
|
||||
<string name="dashboard_import_confirm">Importar</string>
|
||||
<string name="dashboard_import_started">Se inició la importación del servidor. Espera a que termine en Operaciones antes de reiniciar Hermes.</string>
|
||||
<string name="dashboard_import_failed">No se pudo iniciar la importación del servidor.</string>
|
||||
<string name="dashboard_action_configure">Configurar</string>
|
||||
<string name="dashboard_action_setup">Configurar</string>
|
||||
<string name="dashboard_action_setup_whatsapp">Configurar WhatsApp</string>
|
||||
<string name="dashboard_learning_edit_title">Editar %1$s</string>
|
||||
<string name="dashboard_learning_edit_warning">Al editar se reemplaza todo el contenido del nodo. Hermes archiva las habilidades eliminadas del grafo y se pueden restaurar desde el archivo; eliminar un nodo de memoria es permanente, así que exporta primero una copia de seguridad.</string>
|
||||
<string name="dashboard_learning_saved">Nodo de aprendizaje guardado.</string>
|
||||
<string name="dashboard_learning_save_failed">No se pudo guardar el nodo de aprendizaje.</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes archiva las habilidades aprendidas para poder restaurarlas desde el archivo del servidor. Eliminar un nodo de memoria es permanente. Guarda primero una copia de seguridad del servidor si podrías necesitar este contenido más adelante.</string>
|
||||
<string name="dashboard_memory_config_title">Configurar %1$s</string>
|
||||
<string name="dashboard_memory_config_help">Los valores permanecen en el perfil de Hermes seleccionado. El servidor acepta los campos secretos y nunca los devuelve después de guardarlos. Los campos obligatorios están marcados con *.</string>
|
||||
<string name="dashboard_memory_values_json">Valores del proveedor (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">Ejecutar configuración</string>
|
||||
<string name="dashboard_memory_invalid_json">Los valores del proveedor deben ser un objeto JSON.</string>
|
||||
<string name="dashboard_memory_setup_started">Se inició la instalación del proveedor en todo el host. Actualiza la vista cuando termine y guarda los valores de este perfil.</string>
|
||||
<string name="dashboard_memory_saved">Proveedor de memoria configurado y activado.</string>
|
||||
<string name="dashboard_memory_save_failed">No se pudo guardar la configuración del proveedor de memoria.</string>
|
||||
<string name="dashboard_whatsapp_title">Configurar WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes inicia una sesión de vinculación de diez minutos para este perfil. Elige el modo bot para una cuenta exclusiva o el chat contigo mismo para enviar mensajes a tu propia cuenta vinculada.</string>
|
||||
<string name="dashboard_whatsapp_bot">Cuenta de bot</string>
|
||||
<string name="dashboard_whatsapp_self_chat">Chat contigo mismo</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">Números de teléfono permitidos (opcional)</string>
|
||||
<string name="dashboard_whatsapp_start">Iniciar vinculación</string>
|
||||
<string name="dashboard_whatsapp_scan">Escanea este código desde la pantalla Dispositivos vinculados de WhatsApp. Mantén abierto este cuadro mientras Hermes confirma la cuenta.</string>
|
||||
<string name="dashboard_whatsapp_qr">Código QR de dispositivo vinculado de WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_apply">Activar WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_start_failed">No se pudo iniciar la vinculación de WhatsApp.</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">No se pudo guardar la configuración de WhatsApp.</string>
|
||||
<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>
|
||||
|
||||
@@ -3993,6 +3993,16 @@
|
||||
<string name="dashboard_tab_channels_lower">チャンネル</string>
|
||||
<string name="dashboard_tab_operations_lower">運用</string>
|
||||
<string name="dashboard_section_action_server_backup">サーバーバックアップを作成</string>
|
||||
<string name="dashboard_section_action_download_backup">最新のバックアップを保存</string>
|
||||
<string name="dashboard_section_action_import_backup">バックアップをインポート</string>
|
||||
<string name="dashboard_backup_create_first">ダウンロードする前に、このセッションでバックアップを作成してください。</string>
|
||||
<string name="dashboard_backup_download_failed">バックアップをダウンロードできませんでした。</string>
|
||||
<string name="dashboard_backup_saved">バックアップを %1$s として保存しました。</string>
|
||||
<string name="dashboard_import_title">サーバーバックアップをインポートしますか?</string>
|
||||
<string name="dashboard_import_warning">選択した ZIP を Hermes にアップロードし、認証済みのサーバーインポートを開始します。設定やデータが置き換わる可能性があります。先に現在のバックアップを作成して保存してください。</string>
|
||||
<string name="dashboard_import_confirm">インポート</string>
|
||||
<string name="dashboard_import_started">サーバーのインポートを開始しました。Hermes を再起動する前に、運用画面で完了を確認してください。</string>
|
||||
<string name="dashboard_import_failed">サーバーのインポートを開始できませんでした。</string>
|
||||
<string name="dashboard_profile_mcp_servers_optional">MCP サーバー(任意)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">サーバー名をカンマまたは改行で区切ります。認証情報はサーバー側に保持されます。</string>
|
||||
<string name="dashboard_tile_memory_title">メモリ</string>
|
||||
@@ -4003,7 +4013,89 @@
|
||||
<string name="dashboard_tile_channels_sub">WhatsApp を含むメッセージプラットフォームの状態</string>
|
||||
<string name="dashboard_tile_operations_title">サーバー運用</string>
|
||||
<string name="dashboard_tile_operations_sub">ホストの状態とサーバー全体のバックアップ</string>
|
||||
<string name="dashboard_action_configure">設定</string>
|
||||
<string name="dashboard_action_setup">セットアップ</string>
|
||||
<string name="dashboard_action_setup_whatsapp">WhatsApp を設定</string>
|
||||
<string name="dashboard_learning_edit_title">%1$sを編集</string>
|
||||
<string name="dashboard_learning_edit_warning">編集するとノードの内容全体が置き換わります。グラフから削除したスキルは Hermes によってアーカイブされ、復元できます。メモリノードの削除は元に戻せないため、先にバックアップをエクスポートしてください。</string>
|
||||
<string name="dashboard_learning_saved">学習ノードを保存しました。</string>
|
||||
<string name="dashboard_learning_save_failed">学習ノードを保存できませんでした。</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes は学習済みスキルをアーカイブするため、サーバーのアーカイブから復元できます。メモリノードの削除は元に戻せません。この内容が後で必要になる可能性がある場合は、先にサーバーバックアップを保存してください。</string>
|
||||
<string name="dashboard_memory_config_title">%1$sを設定</string>
|
||||
<string name="dashboard_memory_config_help">値は選択した Hermes プロファイルに保持されます。シークレット項目はサーバーに保存されますが、保存後に返されることはありません。必須項目には * が付いています。</string>
|
||||
<string name="dashboard_memory_values_json">プロバイダーの値(JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">セットアップを実行</string>
|
||||
<string name="dashboard_memory_invalid_json">プロバイダーの値は JSON オブジェクトである必要があります。</string>
|
||||
<string name="dashboard_memory_setup_started">ホスト全体へのプロバイダーのインストールを開始しました。完了後に更新し、このプロファイルの値を保存してください。</string>
|
||||
<string name="dashboard_memory_saved">メモリプロバイダーを設定して有効にしました。</string>
|
||||
<string name="dashboard_memory_save_failed">メモリプロバイダーの設定を保存できませんでした。</string>
|
||||
<string name="dashboard_whatsapp_title">WhatsApp を設定</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes はプロファイル単位のペアリングセッションを10分間開始します。専用アカウントにはボットモード、自分のリンク済みアカウントへのメッセージにはセルフチャットを選択してください。</string>
|
||||
<string name="dashboard_whatsapp_bot">ボットアカウント</string>
|
||||
<string name="dashboard_whatsapp_self_chat">セルフチャット</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">許可する電話番号(任意)</string>
|
||||
<string name="dashboard_whatsapp_start">ペアリングを開始</string>
|
||||
<string name="dashboard_whatsapp_scan">WhatsApp の「リンク済みデバイス」画面でこのコードをスキャンしてください。Hermes がアカウントを確認するまで、このダイアログを開いたままにしてください。</string>
|
||||
<string name="dashboard_whatsapp_qr">WhatsApp リンク済みデバイスの QR コード</string>
|
||||
<string name="dashboard_whatsapp_apply">WhatsApp を有効化</string>
|
||||
<string name="dashboard_whatsapp_start_failed">WhatsApp のペアリングを開始できませんでした。</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">WhatsApp の設定を保存できませんでした。</string>
|
||||
<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>
|
||||
|
||||
@@ -3725,7 +3725,103 @@
|
||||
<string name="dashboard_tile_channels_sub">Состояние платформ сообщений, включая WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">Операции сервера</string>
|
||||
<string name="dashboard_tile_operations_sub">Состояние хоста и резервная копия всего сервера</string>
|
||||
<string name="dashboard_section_action_download_backup">Сохранить последнюю резервную копию</string>
|
||||
<string name="dashboard_section_action_import_backup">Импортировать резервную копию</string>
|
||||
<string name="dashboard_backup_create_first">Перед скачиванием создайте резервную копию в этом сеансе.</string>
|
||||
<string name="dashboard_backup_download_failed">Не удалось скачать резервную копию.</string>
|
||||
<string name="dashboard_backup_saved">Резервная копия сохранена как %1$s.</string>
|
||||
<string name="dashboard_import_title">Импортировать резервную копию сервера?</string>
|
||||
<string name="dashboard_import_warning">Выбранный ZIP-файл будет загружен в Hermes, после чего начнётся аутентифицированный импорт на сервере. Он может заменить конфигурацию и данные. Сначала создайте и сохраните актуальную резервную копию.</string>
|
||||
<string name="dashboard_import_confirm">Импортировать</string>
|
||||
<string name="dashboard_import_started">Импорт на сервере запущен. Перед перезапуском Hermes дождитесь его завершения в разделе «Операции».</string>
|
||||
<string name="dashboard_import_failed">Не удалось запустить импорт на сервере.</string>
|
||||
<string name="dashboard_action_configure">Настроить</string>
|
||||
<string name="dashboard_action_setup">Настройка</string>
|
||||
<string name="dashboard_action_setup_whatsapp">Настроить WhatsApp</string>
|
||||
<string name="dashboard_learning_edit_title">Изменить %1$s</string>
|
||||
<string name="dashboard_learning_edit_warning">Изменения заменят всё содержимое узла. Hermes архивирует навыки, удалённые из графа, чтобы их можно было восстановить из архива; удаление узла памяти необратимо, поэтому сначала экспортируйте резервную копию.</string>
|
||||
<string name="dashboard_learning_saved">Изученный узел сохранён.</string>
|
||||
<string name="dashboard_learning_save_failed">Не удалось сохранить изученный узел.</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes архивирует изученные навыки, чтобы их можно было восстановить из архива сервера. Удаление узла памяти необратимо. Если содержимое может понадобиться позже, сначала сохраните резервную копию сервера.</string>
|
||||
<string name="dashboard_memory_config_title">Настроить %1$s</string>
|
||||
<string name="dashboard_memory_config_help">Значения сохраняются в выбранном профиле Hermes. Секретные поля принимаются сервером и не возвращаются после сохранения. Обязательные поля отмечены символом *.</string>
|
||||
<string name="dashboard_memory_values_json">Значения провайдера (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">Запустить настройку</string>
|
||||
<string name="dashboard_memory_invalid_json">Значения провайдера должны быть объектом JSON.</string>
|
||||
<string name="dashboard_memory_setup_started">Установка провайдера на всём хосте запущена. После её завершения обновите данные, затем сохраните значения этого профиля.</string>
|
||||
<string name="dashboard_memory_saved">Провайдер памяти настроен и активирован.</string>
|
||||
<string name="dashboard_memory_save_failed">Не удалось сохранить конфигурацию провайдера памяти.</string>
|
||||
<string name="dashboard_whatsapp_title">Настроить WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes запускает десятиминутный сеанс привязки для выбранного профиля. Выберите режим бота для отдельной учётной записи или чат с собой, чтобы писать в собственную привязанную учётную запись.</string>
|
||||
<string name="dashboard_whatsapp_bot">Учётная запись бота</string>
|
||||
<string name="dashboard_whatsapp_self_chat">Чат с собой</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">Разрешённые номера телефонов (необязательно)</string>
|
||||
<string name="dashboard_whatsapp_start">Начать привязку</string>
|
||||
<string name="dashboard_whatsapp_scan">Отсканируйте этот код на экране «Связанные устройства» в WhatsApp. Не закрывайте это окно, пока Hermes подтверждает учётную запись.</string>
|
||||
<string name="dashboard_whatsapp_qr">QR-код связанного устройства WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_apply">Включить WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_start_failed">Не удалось начать привязку WhatsApp.</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">Не удалось сохранить конфигурацию WhatsApp.</string>
|
||||
<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>
|
||||
|
||||
@@ -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>
|
||||
@@ -1977,6 +1992,16 @@
|
||||
<string name="dashboard_section_action_browse_hub">Browse hub</string>
|
||||
<string name="dashboard_section_action_update_installed">Update installed</string>
|
||||
<string name="dashboard_section_action_server_backup">Create server backup</string>
|
||||
<string name="dashboard_section_action_download_backup">Save latest backup</string>
|
||||
<string name="dashboard_section_action_import_backup">Import backup</string>
|
||||
<string name="dashboard_backup_create_first">Create a backup in this session before downloading it.</string>
|
||||
<string name="dashboard_backup_download_failed">Backup could not be downloaded.</string>
|
||||
<string name="dashboard_backup_saved">Backup saved as %1$s.</string>
|
||||
<string name="dashboard_import_title">Import server backup?</string>
|
||||
<string name="dashboard_import_warning">This uploads the selected zip to Hermes and starts its authenticated server import. It can replace configuration and data. Create and save a current backup first.</string>
|
||||
<string name="dashboard_import_confirm">Import</string>
|
||||
<string name="dashboard_import_started">Server import started. Watch Operations for completion before restarting Hermes.</string>
|
||||
<string name="dashboard_import_failed">Server import could not be started.</string>
|
||||
<string name="dashboard_profile_mcp_servers_optional">MCP servers (optional)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">Comma or line-separated server names. Credentials remain server-owned.</string>
|
||||
<string name="dashboard_tile_memory_title">Memory</string>
|
||||
@@ -2010,6 +2035,34 @@
|
||||
<string name="dashboard_action_use">Use</string>
|
||||
<string name="dashboard_action_describe">Describe</string>
|
||||
<string name="dashboard_action_model">Model</string>
|
||||
<string name="dashboard_action_configure">Configure</string>
|
||||
<string name="dashboard_action_setup">Setup</string>
|
||||
<string name="dashboard_action_setup_whatsapp">Set up WhatsApp</string>
|
||||
<string name="dashboard_learning_edit_title">Edit %1$s</string>
|
||||
<string name="dashboard_learning_edit_warning">Edits replace the node’s complete content. Skills deleted from the graph are archived by Hermes and can be restored from the archive; memory-node deletion is permanent, so export a backup first.</string>
|
||||
<string name="dashboard_learning_saved">Learning node saved.</string>
|
||||
<string name="dashboard_learning_save_failed">Learning node could not be saved.</string>
|
||||
<string name="dashboard_learning_delete_warning">Hermes archives learned skills so they can be restored from the server archive. Memory-node deletion is permanent. Save a server backup first if this content may be needed later.</string>
|
||||
<string name="dashboard_memory_config_title">Configure %1$s</string>
|
||||
<string name="dashboard_memory_config_help">Values stay on the selected Hermes profile. Secret fields are accepted by the server and are never returned after saving. Required fields are marked with *.</string>
|
||||
<string name="dashboard_memory_values_json">Provider values (JSON)</string>
|
||||
<string name="dashboard_memory_run_setup">Run setup</string>
|
||||
<string name="dashboard_memory_invalid_json">Provider values must be a JSON object.</string>
|
||||
<string name="dashboard_memory_setup_started">Host-wide provider installation started. Refresh after it completes, then save this profile’s values.</string>
|
||||
<string name="dashboard_memory_saved">Memory provider configured and activated.</string>
|
||||
<string name="dashboard_memory_save_failed">Memory provider configuration could not be saved.</string>
|
||||
<string name="dashboard_whatsapp_title">Set up WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_help">Hermes starts a ten-minute, profile-scoped pairing session. Choose bot mode for a dedicated account or self-chat to message your own linked account.</string>
|
||||
<string name="dashboard_whatsapp_bot">Bot account</string>
|
||||
<string name="dashboard_whatsapp_self_chat">Self-chat</string>
|
||||
<string name="dashboard_whatsapp_allowed_users">Allowed phone numbers (optional)</string>
|
||||
<string name="dashboard_whatsapp_start">Start pairing</string>
|
||||
<string name="dashboard_whatsapp_scan">Scan this code from WhatsApp’s Linked devices screen. Keep this dialog open while Hermes confirms the account.</string>
|
||||
<string name="dashboard_whatsapp_qr">WhatsApp linked-device QR code</string>
|
||||
<string name="dashboard_whatsapp_apply">Enable WhatsApp</string>
|
||||
<string name="dashboard_whatsapp_start_failed">WhatsApp pairing could not be started.</string>
|
||||
<string name="dashboard_whatsapp_apply_failed">WhatsApp configuration could not be saved.</string>
|
||||
<string name="dashboard_whatsapp_saved">WhatsApp enabled; Hermes started a gateway restart.</string>
|
||||
<string name="dashboard_mcp_oauth_title">Authenticate %1$s</string>
|
||||
<string name="dashboard_mcp_oauth_body">Hermes will open the provider in your browser. Return here after approving access; credentials stay on the Hermes server.</string>
|
||||
<string name="dashboard_mcp_oauth_approved">MCP authentication approved</string>
|
||||
@@ -4010,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
|
||||
|
||||
@@ -153,11 +153,14 @@ class ChatTurnCheckpointStoreTest {
|
||||
priorUserMessageCount = 3,
|
||||
baselineAssistantCount = 3,
|
||||
pendingAsk = ChatTurnAskCheckpoint(
|
||||
kind = "APPROVAL",
|
||||
text = "Allow command?",
|
||||
kind = "CLARIFY",
|
||||
requestId = "clarify-1",
|
||||
text = "Choose environments",
|
||||
choices = listOf("dev", "prod"),
|
||||
multiSelect = true,
|
||||
timeoutSeconds = 0,
|
||||
messageId = "ask-1",
|
||||
cardKey = "approval-1",
|
||||
cardKey = "clarify-1",
|
||||
receivedAt = 1_004L,
|
||||
),
|
||||
queuedMessages = listOf(
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class HermesCardInputTest {
|
||||
|
||||
@Test
|
||||
fun `multi select answer is an exact ordered deduplicated json array`() {
|
||||
assertEquals(
|
||||
"[\"prod\",\"dev\",\"custom, value\"]",
|
||||
encodeClarifyMultiSelectAnswer(
|
||||
listOf(" prod ", "dev", "prod", "", "custom, value"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `zero multi select answers encode as an empty array`() {
|
||||
assertEquals("[]", encodeClarifyMultiSelectAnswer(emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
+169
@@ -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() })
|
||||
}
|
||||
+51
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import com.hermesandroid.relay.data.VoiceIntentTrace
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.RelayStreamEventEnvelope
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionPullRequest
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.add
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
@@ -602,6 +603,35 @@ class ChatHandlerTest {
|
||||
assertTrue(restartedHandler.sessions.value.first { it.sessionId == "archived" }.archived)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateSessions_mapsOptionalWorkspaceAndPullRequestState() {
|
||||
handler.updateSessions(
|
||||
listOf(
|
||||
SessionItem(
|
||||
id = "coding",
|
||||
cwd = "/work/repo",
|
||||
gitBranch = "feature/mobile",
|
||||
gitRepoRoot = "/work/repo",
|
||||
pullRequest = SessionPullRequest(
|
||||
number = 134,
|
||||
url = "https://github.com/example/repo/pull/134",
|
||||
state = "open",
|
||||
draft = true,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val session = handler.sessions.value.single()
|
||||
assertEquals("/work/repo", session.workingDirectory)
|
||||
assertEquals("feature/mobile", session.gitBranch)
|
||||
assertEquals("/work/repo", session.gitRepoRoot)
|
||||
assertEquals(134, session.pullRequestNumber)
|
||||
assertEquals("https://github.com/example/repo/pull/134", session.pullRequestUrl)
|
||||
assertEquals("open", session.pullRequestState)
|
||||
assertTrue(session.pullRequestDraft)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setSessionFlagsLocal_supportsOptimisticUpdateAndRollback() {
|
||||
handler.updateSessions(listOf(SessionItem(id = "s1")))
|
||||
@@ -920,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(
|
||||
|
||||
+369
@@ -14,11 +14,46 @@ import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import okio.Buffer
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
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
|
||||
@@ -864,6 +899,191 @@ class DashboardApiClientTest {
|
||||
assertEquals("Review title fallbacks", sessions[1].preview)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_enrichesWorkspaceRowsWithTranscriptBackedPullRequest() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"sessions":[{"id":"coding-1","title":"Ship it","cwd":"/work/hermes-relay","git_branch":"feature/session-context","git_repo_root":"/work/hermes-relay"}]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"pull_requests":{"coding-1":{"number":134,"url":"https://github.com/example/hermes-relay/pull/134"}},"scanned":["coding-1"]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"ghReady":true,"prs":[{"branch":"feature/session-context","draft":false,"number":134,"state":"open","title":"Session context","url":"https://github.com/example/hermes-relay/pull/134"}]}""",
|
||||
),
|
||||
)
|
||||
|
||||
val session = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.listSessions()
|
||||
.getOrThrow()
|
||||
.single()
|
||||
|
||||
assertEquals("/work/hermes-relay", session.cwd)
|
||||
assertEquals("feature/session-context", session.gitBranch)
|
||||
assertEquals("/work/hermes-relay", session.gitRepoRoot)
|
||||
assertEquals(134, session.pullRequest?.number)
|
||||
assertEquals("https://github.com/example/hermes-relay/pull/134", session.pullRequest?.url)
|
||||
assertEquals("open", session.pullRequest?.state)
|
||||
assertEquals(false, session.pullRequest?.draft)
|
||||
server.takeRequest()
|
||||
val scanRequest = server.takeRequest()
|
||||
assertEquals("POST", scanRequest.method)
|
||||
assertEquals("/api/profiles/sessions/pull-requests", scanRequest.requestUrl!!.encodedPath)
|
||||
assertEquals(
|
||||
listOf("coding-1"),
|
||||
Json.parseToJsonElement(scanRequest.body.readUtf8()).jsonObject["ids"]
|
||||
?.let { it as JsonArray }
|
||||
?.map { it.toString().trim('"') },
|
||||
)
|
||||
val stateRequest = server.takeRequest()
|
||||
assertEquals("/api/git/review/pr-list", stateRequest.requestUrl!!.encodedPath)
|
||||
val stateBody = Json.parseToJsonElement(stateRequest.body.readUtf8()).jsonObject
|
||||
assertEquals("/work/hermes-relay", stateBody["path"]?.toString()?.trim('"'))
|
||||
assertEquals(listOf("feature/session-context"), (stateBody["branches"] as JsonArray).map { it.toString().trim('"') })
|
||||
assertEquals(listOf("134"), (stateBody["numbers"] as JsonArray).map { it.toString() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_keepsWorkspaceMetadataWhenPullRequestEndpointIsUnavailable() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"sessions":[{"id":"legacy-1","git_branch":"dev","git_repo_root":"/work/legacy"}]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("not found"))
|
||||
|
||||
val session = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.listSessions()
|
||||
.getOrThrow()
|
||||
.single()
|
||||
|
||||
assertEquals("dev", session.gitBranch)
|
||||
assertEquals("/work/legacy", session.gitRepoRoot)
|
||||
assertEquals(null, session.pullRequest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_retriesActiveSessionPullRequestMissAfterBoundedTtl() = runTest {
|
||||
var now = 1_000L
|
||||
val client = DashboardApiClient(
|
||||
baseUrl = server.url("/").toString(),
|
||||
nowMillis = { now },
|
||||
)
|
||||
val sessionList = """{"sessions":[{"id":"active-1","cwd":"/work/repo"}]}"""
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"pull_requests":{},"scanned":["active-1"]}"""),
|
||||
)
|
||||
|
||||
assertEquals(null, client.listSessions().getOrThrow().single().pullRequest)
|
||||
server.takeRequest()
|
||||
server.takeRequest()
|
||||
|
||||
now += DashboardApiClient.ACTIVE_SESSION_PR_MISS_TTL_MILLIS - 1
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
|
||||
assertEquals(null, client.listSessions().getOrThrow().single().pullRequest)
|
||||
assertEquals("GET", server.takeRequest().method)
|
||||
|
||||
now += 1
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"pull_requests":{"active-1":{"number":12,"url":"https://github.com/example/repo/pull/12"}},"scanned":["active-1"]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"ghReady":false,"prs":[]}"""),
|
||||
)
|
||||
|
||||
assertEquals(12, client.listSessions().getOrThrow().single().pullRequest?.number)
|
||||
assertEquals("GET", server.takeRequest().method)
|
||||
assertEquals("/api/profiles/sessions/pull-requests", server.takeRequest().requestUrl!!.encodedPath)
|
||||
assertEquals("/api/git/review/pr-list", server.takeRequest().requestUrl!!.encodedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_performsOneFinalScanWhenAnActiveMissBecomesTerminal() = runTest {
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"sessions":[{"id":"finishing","cwd":"/work/repo"}]}"""),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"pull_requests":{},"scanned":["finishing"]}"""),
|
||||
)
|
||||
client.listSessions().getOrThrow()
|
||||
repeat(2) { server.takeRequest() }
|
||||
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"sessions":[{"id":"finishing","cwd":"/work/repo","ended_at":2000.0}]}"""),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"pull_requests":{"finishing":{"number":13,"url":"https://github.com/example/repo/pull/13"}},"scanned":["finishing"]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"ghReady":false,"prs":[]}"""),
|
||||
)
|
||||
|
||||
assertEquals(13, client.listSessions().getOrThrow().single().pullRequest?.number)
|
||||
repeat(3) { server.takeRequest() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_scopesPullRequestCacheByProfileAndSessionId() = runTest {
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
fun enqueueProfileRead(number: Int) {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"sessions":[{"id":"same","cwd":"/work/repo"}]}"""),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"pull_requests":{"same":{"number":$number,"url":"https://github.com/example/repo/pull/$number"}},"scanned":["same"]}""",
|
||||
),
|
||||
)
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"ghReady":false,"prs":[]}"""),
|
||||
)
|
||||
}
|
||||
|
||||
enqueueProfileRead(11)
|
||||
assertEquals(11, client.listSessions(profile = "alpha").getOrThrow().single().pullRequest?.number)
|
||||
repeat(3) { server.takeRequest() }
|
||||
|
||||
enqueueProfileRead(22)
|
||||
assertEquals(22, client.listSessions(profile = "beta").getOrThrow().single().pullRequest?.number)
|
||||
repeat(3) { server.takeRequest() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listAllProfileSessions_doesNotGuessAcrossDuplicateSessionIds() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"sessions":[{"id":"same","profile":"alpha","cwd":"/work/a"},{"id":"same","profile":"beta","cwd":"/work/b"}]}""",
|
||||
),
|
||||
)
|
||||
|
||||
val sessions = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.listAllProfileSessions()
|
||||
.getOrThrow()
|
||||
|
||||
assertEquals(2, sessions.size)
|
||||
assertTrue(sessions.all { it.pullRequest == null })
|
||||
assertEquals("GET", server.takeRequest().method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listAllProfileSessions_preservesOwnerAndCompositeIdentity() = runTest {
|
||||
server.enqueue(
|
||||
@@ -1372,6 +1592,155 @@ class DashboardApiClientTest {
|
||||
assertEquals(true, settings.showReasoning)
|
||||
assertEquals("off", settings.toolDisplay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverBackup_createDownloadAndImport_useUpstreamContracts() = runTest {
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"archive":"/srv/backups/a.zip"}"""))
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/zip")
|
||||
.setHeader("Content-Disposition", "attachment; filename=\"a.zip\"")
|
||||
.setBody("archive-bytes"),
|
||||
)
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"name":"import"}"""))
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"name":"import"}"""))
|
||||
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
val created = client.createServerBackup().getOrThrow()
|
||||
val downloadSink = ByteArrayOutputStream()
|
||||
val downloadedFilename = client.downloadServerBackup(created["archive"]!!.toString().trim('"')) {
|
||||
downloadSink
|
||||
}.getOrThrow()
|
||||
client.importServerBackup("/srv/backups/a.zip").getOrThrow()
|
||||
val uploadBytes = "zip-data".encodeToByteArray()
|
||||
client.uploadServerBackup(
|
||||
filename = "phone.zip",
|
||||
contentLength = uploadBytes.size.toLong(),
|
||||
openStream = { ByteArrayInputStream(uploadBytes) },
|
||||
).getOrThrow()
|
||||
|
||||
assertEquals("POST", server.takeRequest().method)
|
||||
val downloadRequest = server.takeRequest()
|
||||
assertEquals("/api/ops/backup/download", downloadRequest.requestUrl!!.encodedPath)
|
||||
assertEquals("/srv/backups/a.zip", downloadRequest.requestUrl!!.queryParameter("archive"))
|
||||
assertEquals("a.zip", downloadedFilename)
|
||||
assertEquals("archive-bytes", downloadSink.toString(Charsets.UTF_8.name()))
|
||||
val importRequest = server.takeRequest()
|
||||
assertEquals("/api/ops/import", importRequest.requestUrl!!.encodedPath)
|
||||
assertTrue(importRequest.body.readUtf8().contains(""""archive":"/srv/backups/a.zip""""))
|
||||
val upload = server.takeRequest()
|
||||
assertEquals("/api/ops/import-upload", upload.requestUrl!!.encodedPath)
|
||||
val uploadBody = upload.body.readUtf8()
|
||||
assertTrue(uploadBody.contains("filename=\"phone.zip\""))
|
||||
assertTrue(uploadBody.contains("zip-data"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun boundedStreamRequestBody_streamsAndEnforcesDeclaredAndObservedLimits() {
|
||||
val payload = "streamed-archive".encodeToByteArray()
|
||||
val sink = Buffer()
|
||||
BoundedStreamRequestBody(payload.size.toLong(), 32L) {
|
||||
ByteArrayInputStream(payload)
|
||||
}.writeTo(sink)
|
||||
assertEquals("streamed-archive", sink.readUtf8())
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
BoundedStreamRequestBody(declaredLength = 33L, limitBytes = 32L) {
|
||||
ByteArrayInputStream(byteArrayOf())
|
||||
}
|
||||
}
|
||||
|
||||
val oversizedUnknownLength = BoundedStreamRequestBody(null, 8L) {
|
||||
ByteArrayInputStream("ninebytes".encodeToByteArray())
|
||||
}
|
||||
assertThrows(IOException::class.java) { oversizedUnknownLength.writeTo(Buffer()) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun copyBounded_streamsDownloadAndRejectsDeclaredAndObservedOverflow() {
|
||||
val output = ByteArrayOutputStream()
|
||||
val copied = copyBounded(
|
||||
ByteArrayInputStream("download".encodeToByteArray()),
|
||||
output,
|
||||
declaredLength = 8L,
|
||||
limitBytes = 16L,
|
||||
)
|
||||
assertEquals(8L, copied)
|
||||
assertEquals("download", output.toString(Charsets.UTF_8.name()))
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream(), 17L, 16L)
|
||||
}
|
||||
assertThrows(IOException::class.java) {
|
||||
copyBounded(
|
||||
ByteArrayInputStream("seventeen-byte-doc".encodeToByteArray()),
|
||||
ByteArrayOutputStream(),
|
||||
declaredLength = null,
|
||||
limitBytes = 16L,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downloadServerBackup_rejectsDeclaredOversizeBeforeOpeningDestination() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/zip")
|
||||
.setHeader("Content-Length", DashboardApiClient.MAX_BACKUP_TRANSFER_BYTES + 1),
|
||||
)
|
||||
var destinationOpened = false
|
||||
val result = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.downloadServerBackup("/srv/backups/oversize.zip") {
|
||||
destinationOpened = true
|
||||
ByteArrayOutputStream()
|
||||
}
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertFalse(destinationOpened)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun learningMutations_preserveNodeIdAndProfile() = runTest {
|
||||
repeat(3) { server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"content":"body"}""")) }
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
|
||||
client.getLearningNode("memory:MEMORY.md:0", "worker").getOrThrow()
|
||||
client.updateLearningNode("memory:MEMORY.md:0", "replacement", "worker").getOrThrow()
|
||||
client.deleteLearningNode("memory:MEMORY.md:0", "worker").getOrThrow()
|
||||
|
||||
val get = server.takeRequest()
|
||||
assertEquals("memory:MEMORY.md:0", get.requestUrl!!.queryParameter("id"))
|
||||
assertEquals("worker", get.requestUrl!!.queryParameter("profile"))
|
||||
val put = server.takeRequest()
|
||||
assertEquals("PUT", put.method)
|
||||
assertTrue(put.body.readUtf8().contains(""""profile":"worker""""))
|
||||
val delete = server.takeRequest()
|
||||
assertEquals("DELETE", delete.method)
|
||||
assertTrue(delete.body.readUtf8().contains(""""id":"memory:MEMORY.md:0""""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun memoryProviderAndWhatsApp_calls_areProfileScoped() = runTest {
|
||||
repeat(5) { server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"pairing_id":"pair-1","status":"waiting"}""")) }
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
val values = Json.parseToJsonElement("""{"url":"https://memory.example"}""").jsonObject
|
||||
|
||||
client.getMemoryProviderConfig("honcho", "worker").getOrThrow()
|
||||
client.updateMemoryProviderConfig("honcho", values, "worker").getOrThrow()
|
||||
client.selectMemoryProvider("honcho").getOrThrow()
|
||||
client.startWhatsAppOnboarding("self-chat", "15551234567", "worker").getOrThrow()
|
||||
client.applyWhatsAppOnboarding("pair-1", "self-chat", "15551234567", "worker").getOrThrow()
|
||||
|
||||
assertEquals("worker", server.takeRequest().requestUrl!!.queryParameter("profile"))
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains(""""values":{"url":"https://memory.example"}"""))
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains(""""provider":"honcho""""))
|
||||
val start = server.takeRequest()
|
||||
assertEquals("/api/messaging/whatsapp/onboarding/start", start.requestUrl!!.encodedPath)
|
||||
assertTrue(start.body.readUtf8().contains(""""profile":"worker""""))
|
||||
val apply = server.takeRequest()
|
||||
assertEquals("/api/messaging/whatsapp/onboarding/pair-1/apply", apply.requestUrl!!.encodedPath)
|
||||
assertTrue(apply.body.readUtf8().contains(""""profile":"worker""""))
|
||||
}
|
||||
}
|
||||
|
||||
private fun messagePageResponse(
|
||||
|
||||
+239
-7
@@ -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
|
||||
|
||||
+63
-1
@@ -715,8 +715,44 @@ class GatewayEventMapperTest {
|
||||
assertEquals("r1", ask.requestId)
|
||||
assertEquals("Which file?", ask.text)
|
||||
assertEquals(listOf("a.txt", "b.txt"), ask.choices)
|
||||
assertFalse(ask.multiSelect)
|
||||
assertNull(ask.envVar)
|
||||
assertEquals(300, ask.timeoutSeconds)
|
||||
assertEquals(0, ask.timeoutSeconds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clarify request carries multi select only with bounded usable choices`() {
|
||||
val r = Recorder()
|
||||
mapperWith(r).onEvent(
|
||||
"clarify.request",
|
||||
obj(
|
||||
"""{"request_id":"r1","question":"Where?","multi_select":true,"choices":""" +
|
||||
"""[" dev ","prod","dev","","stage","canary","extra"]}""",
|
||||
),
|
||||
)
|
||||
|
||||
val ask = r.interactions.single()
|
||||
assertTrue(ask.multiSelect)
|
||||
assertEquals(listOf("dev", "prod", "stage", "canary"), ask.choices)
|
||||
assertEquals(0, ask.timeoutSeconds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clarify ignores malformed multi select and consumes additive timeout metadata`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
mapper.onEvent(
|
||||
"clarify.request",
|
||||
obj("""{"request_id":"r1","multi_select":true,"choices":null,"timeout_seconds":42}"""),
|
||||
)
|
||||
mapper.onEvent(
|
||||
"clarify.request",
|
||||
obj("""{"request_id":"r2","multi_select":false,"choices":["a"]}"""),
|
||||
)
|
||||
|
||||
assertFalse(r.interactions[0].multiSelect)
|
||||
assertEquals(42, r.interactions[0].timeoutSeconds)
|
||||
assertFalse(r.interactions[1].multiSelect)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -758,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()
|
||||
|
||||
+104
-1
@@ -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,54 @@ 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>(
|
||||
"""{"id":"s1","cwd":"/work/repo","git_branch":"feature/mobile","git_repo_root":"/work/repo"}""",
|
||||
)
|
||||
|
||||
assertEquals("/work/repo", item.cwd)
|
||||
assertEquals("feature/mobile", item.gitBranch)
|
||||
assertEquals("/work/repo", item.gitRepoRoot)
|
||||
assertNull(item.pullRequest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionItem_deserialization_acceptsIsoUpdatedAtFallback() {
|
||||
val jsonStr = """
|
||||
@@ -133,6 +192,10 @@ class SessionModelsTest {
|
||||
assertNull(item.outputTokens)
|
||||
assertEquals(false, item.pinned)
|
||||
assertEquals(false, item.archived)
|
||||
assertNull(item.cwd)
|
||||
assertNull(item.gitBranch)
|
||||
assertNull(item.gitRepoRoot)
|
||||
assertNull(item.pullRequest)
|
||||
}
|
||||
|
||||
// --- SessionListResponse ---
|
||||
@@ -285,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(
|
||||
|
||||
+36
-1
@@ -9,16 +9,19 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.click
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.click
|
||||
import androidx.compose.ui.test.swipeDown
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardAction
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
@@ -112,6 +115,38 @@ class HermesApprovalCardInteractionTest {
|
||||
compose.runOnIdle { assertEquals(listOf("once", "deny"), actions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multi select clarify toggles choices and submits one ordered json array`() {
|
||||
val answers = mutableListOf<String>()
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(
|
||||
card = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
|
||||
title = "Choose environments",
|
||||
input = HermesCardInput(
|
||||
kind = HermesCardInput.Kinds.CHOICE,
|
||||
choices = listOf("dev", "stage", "prod"),
|
||||
multiSelect = true,
|
||||
allowFreeText = true,
|
||||
),
|
||||
),
|
||||
cardKey = "clarify-multi",
|
||||
dispatches = emptyList(),
|
||||
onActionTap = { _, _ -> },
|
||||
onInputSubmit = { _, value -> answers += value },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Submit").assertIsNotEnabled()
|
||||
compose.onNodeWithText("prod").performTouchInput { click() }
|
||||
compose.onNodeWithText("dev").performTouchInput { click() }
|
||||
compose.onNodeWithText("Submit").assertIsEnabled().performTouchInput { click() }
|
||||
|
||||
compose.runOnIdle { assertEquals(listOf("[\"prod\",\"dev\"]"), answers) }
|
||||
}
|
||||
|
||||
private fun approvalCard() = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_APPROVAL,
|
||||
title = "Approval requested",
|
||||
|
||||
+60
@@ -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
|
||||
@@ -49,6 +54,70 @@ class SessionDrawerTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session work labels use a safe repo name branch and pull request number`() {
|
||||
val session = ChatSession(
|
||||
sessionId = "coding-1",
|
||||
title = "Ship it",
|
||||
model = null,
|
||||
gitRepoRoot = "C:\\worktrees\\hermes-relay\\",
|
||||
gitBranch = "feature/android-session-context",
|
||||
pullRequestNumber = 134,
|
||||
pullRequestUrl = "https://github.com/example/hermes-relay/pull/134",
|
||||
pullRequestState = "open",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
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
|
||||
fun `session work labels stay empty on older hosts`() {
|
||||
assertTrue(
|
||||
sessionWorkLabels(
|
||||
ChatSession(sessionId = "legacy", title = null, model = null),
|
||||
).isEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reordered leading session remains visible after drawer refresh`() {
|
||||
var sessions by mutableStateOf(
|
||||
@@ -92,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -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",
|
||||
),
|
||||
|
||||
+22
@@ -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() })
|
||||
}
|
||||
}
|
||||
+176
-30
@@ -10,7 +10,9 @@ import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
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
|
||||
@@ -26,6 +28,7 @@ import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.OkHttpClient
|
||||
@@ -146,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(
|
||||
@@ -660,6 +732,106 @@ 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")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"clarify.request",
|
||||
buildJsonObject {
|
||||
put("request_id", "clarify-1")
|
||||
put("question", "Which environments?")
|
||||
put("multi_select", true)
|
||||
put("choices", buildJsonArray {
|
||||
add(JsonPrimitive("dev"))
|
||||
add(JsonPrimitive("stage"))
|
||||
add(JsonPrimitive("prod"))
|
||||
})
|
||||
},
|
||||
"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()
|
||||
assertTrue(card.input?.multiSelect == true)
|
||||
assertEquals(listOf("dev", "stage", "prod"), card.input?.choices)
|
||||
assertEquals(null, card.input?.expiresAtMillis)
|
||||
|
||||
viewModel.answerAsk(pending.messageId, pending.cardKey, "[\"prod\",\"dev\"]")
|
||||
|
||||
val response = gatewayHarness.awaitRpc("clarify.respond")
|
||||
assertEquals(JsonPrimitive("clarify-1"), response["request_id"])
|
||||
assertEquals(JsonPrimitive("[\"prod\",\"dev\"]"), response["answer"])
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun authoritativeClarifyExpiryCollapsesCardAndRejectsLateAction() {
|
||||
viewModel.sendMessage("Ask a question")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"clarify.request",
|
||||
buildJsonObject {
|
||||
put("request_id", "clarify-expired")
|
||||
put("question", "Still there?")
|
||||
put("choices", buildJsonArray { add(JsonPrimitive("yes")) })
|
||||
},
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { viewModel.pendingAsk.value != null }
|
||||
val pending = requireNotNull(viewModel.pendingAsk.value)
|
||||
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"clarify.expire",
|
||||
buildJsonObject { put("request_id", "clarify-expired") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
val cardMessage = handler.messages.value.single { it.id == pending.messageId }
|
||||
assertEquals(
|
||||
HermesCardDispatch.EXPIRED_STAMP,
|
||||
cardMessage.cardDispatches.single().actionValue,
|
||||
)
|
||||
viewModel.answerAsk(pending.messageId, pending.cardKey, "yes")
|
||||
Thread.sleep(100)
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "clarify.respond" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitDenialActionEmitsResponseAndCollapsesCard() {
|
||||
viewModel.sendMessage("Run the guarded command")
|
||||
@@ -1281,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
|
||||
|
||||
+144
@@ -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
|
||||
}
|
||||
}
|
||||
+29
@@ -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
-1
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
1.3.14
|
||||
+176
-30
@@ -32,41 +32,74 @@ binary and one set of state files; the tray does not bundle a private sidecar.
|
||||
|
||||
Clicking the tray icon toggles the management popup. Paired Hermes instances are
|
||||
shown as **Hosts**; clients authenticated to the selected host appear separately
|
||||
under Settings and can be deauthorized there. **Pair another host...** is the
|
||||
in that host's detail page and can be deauthorized there. **Pair another host...** is the
|
||||
last host-selector option, or the selector's only action when no hosts exist.
|
||||
|
||||
The tray cross-checks the daemon heartbeat and PID, labels the account as
|
||||
**User** or **Administrator**, and disables lifecycle actions that do not apply
|
||||
to the current state. **Start/Restart daemon as Administrator...** uses the
|
||||
standard Windows UAC prompt; the tray itself stays unelevated. Settings can
|
||||
check the Desktop release channel and self-update the CLI and management UI
|
||||
together. The installer download is verified against the release
|
||||
to the current state. **Restart as Administrator...** uses the standard Windows
|
||||
UAC prompt; the tray itself stays unelevated. **Return to user mode** stops the
|
||||
elevated daemon once and starts it again with normal user privileges. Because
|
||||
every approved command and input action inherits the daemon's privilege,
|
||||
Administrator mode is an explicit action rather than a persistent toggle.
|
||||
|
||||
Settings is reserved for this PC. **Start UI at sign-in** controls only the tray
|
||||
startup entry; the separate **Start daemon with UI** preference decides whether
|
||||
opening the tray also connects remote access. Automatic daemon startup is off
|
||||
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. 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.
|
||||
|
||||
Access is selected per host. **Ask** keeps the connection available but attaches
|
||||
no desktop tools. **Trusted** enables command and file tools while screen/input
|
||||
still uses task grants. **Full Access** also allows screen, keyboard, and mouse
|
||||
without task grants for that host; authentication, audit, deauthorization,
|
||||
emergency stop, and UAC boundaries still apply.
|
||||
Access is selected per host. **Restricted** keeps the connection available but
|
||||
attaches no desktop tools. **Ask Every Time** advertises available command, file,
|
||||
screen/input, and USB operations but requires local approval for each one. It is
|
||||
the default for newly paired hosts; existing hosts retain their stored policy.
|
||||
**Standard** enables typed operations while withholding
|
||||
raw terminal, PowerShell, detached-process, and command-job launch. **Full Access**
|
||||
allows every available capability without task grants for that host;
|
||||
authentication, audit, deauthorization, emergency stop, and UAC boundaries
|
||||
still apply. Commands, Files, Screen & Input, Raw USB, Microphone, and Camera
|
||||
form one per-host capability ledger. Changing an individual gate selects an exact
|
||||
preset when the resulting combination matches one and otherwise creates a
|
||||
**Custom** policy. Existing `ask`, `structured`, and `trusted` CLI values remain
|
||||
accepted as compatibility aliases; legacy `ask` still means Restricted, while
|
||||
the new preset is `ask-every-time`. Raw USB gates direct native/vendor USB utility
|
||||
execution plus secondary services such as ADB. Microphone and camera remain
|
||||
unavailable until their controlled paths exist.
|
||||
|
||||
The tray's **Activity** section is a live, local view of recent remote actions
|
||||
and management events such as daemon, host-access, grant, client, and update
|
||||
changes.
|
||||
It groups events into commands, files, screen, and input; highlights failures,
|
||||
It groups events into commands, files, screen, input, and connected devices; highlights failures,
|
||||
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 detail page for wrapped filters and expandable
|
||||
records. 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 can set a local display name and has an
|
||||
explicit connect action. Local names are stored in `desktop-control.json` and
|
||||
do not rename the remote Hermes instance.
|
||||
the active connection. The detail page is the per-host hub for its local display
|
||||
name, connection state, Relay address and version, pairing/session details,
|
||||
access, capabilities, and authorized clients. It also provides explicit connect,
|
||||
re-pair, deauthorize-client, and guarded **Forget host** actions. Local names are
|
||||
stored in `desktop-control.json` and do not rename the remote Hermes instance.
|
||||
Forgetting removes the local session, alias, and access policy; deauthorization
|
||||
is the separate action that removes a server-side client session.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -241,6 +274,13 @@ relay one-shot code.
|
||||
|
||||
Now subsequent `hermes-relay ...` calls reuse the stored session token. Tokens live at `~/.hermes/remote-sessions.json` (mode 0600) — same file the Ink TUI uses, so pairing once from either surface works for both.
|
||||
|
||||
Each desktop installation also keeps a private stable identifier in
|
||||
`~/.hermes/desktop-device-id`. This lets several PCs retain independent paired
|
||||
sessions on one Relay. Re-pairing one PC replaces only that installation's old
|
||||
credential. Every desktop RPC accepts a stable device ID or unambiguous computer
|
||||
name. With several connected daemons the target is required, preventing an
|
||||
agent command from silently following the most recent connection.
|
||||
|
||||
### Terminal plugins
|
||||
|
||||
The `hermes-relay plugins` command exposes optional terminal surfaces. The first
|
||||
@@ -260,13 +300,18 @@ Herm uses `bun add -g herm-tui` when Bun is available and falls back to
|
||||
### Host access and daemon bring-up
|
||||
|
||||
Starting the daemon no longer grants tools and no longer requires a tool grant.
|
||||
With a paired host in **Ask**, it connects in locked mode with zero desktop tools.
|
||||
With a paired host in **Restricted**, it connects in locked mode with zero desktop tools.
|
||||
Select a host policy from the tray or use the CLI:
|
||||
|
||||
```sh
|
||||
hermes-relay hosts list --json
|
||||
hermes-relay hosts select ws://192.168.1.100:8767
|
||||
hermes-relay hosts access trusted --remote ws://192.168.1.100:8767
|
||||
hermes-relay hosts access ask-every-time --remote ws://192.168.1.100:8767
|
||||
hermes-relay hosts access standard --remote ws://192.168.1.100:8767
|
||||
hermes-relay hosts capability commands allow --remote ws://192.168.1.100:8767 --yes
|
||||
hermes-relay hosts capability files ask --remote ws://192.168.1.100:8767
|
||||
hermes-relay hosts capability screen-input ask --remote ws://192.168.1.100:8767
|
||||
hermes-relay hosts capability usb ask --remote ws://192.168.1.100:8767
|
||||
hermes-relay daemon start
|
||||
```
|
||||
|
||||
@@ -336,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:
|
||||
@@ -385,7 +436,7 @@ overrides. The per-host policy is stored separately in
|
||||
`~/.hermes/desktop-host-access.json`; Full Access enables this surface for its
|
||||
host without an expiring task grant.
|
||||
|
||||
In Ask or Trusted mode, observe grants allow screenshots;
|
||||
When Screen & Input is set to Ask, observe grants allow screenshots;
|
||||
assist/control grants require explicit local approval before host input can run.
|
||||
The daemon writes pending requests to `~/.hermes/grant-bridge`; review them with
|
||||
`hermes-relay grants` or the tray's focused approval dialog. Grants
|
||||
@@ -396,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
|
||||
@@ -504,7 +630,7 @@ hermes-relay audit --json
|
||||
```
|
||||
|
||||
```
|
||||
Desktop-tool activity (4 most recent)
|
||||
Desktop-tool activity (3 most recent)
|
||||
|
||||
WHEN TOOL STATUS DETAIL
|
||||
12s ago desktop_read_file ● ok path=C:\src\app.ts
|
||||
@@ -531,6 +657,8 @@ hermes-relay relay security # runtime auth toggles (run on the relay host)
|
||||
hermes-relay daemon start # run in the background (no console window)
|
||||
hermes-relay daemon status # state + uptime of the running daemon
|
||||
hermes-relay daemon restart # restart with the caller's current privileges
|
||||
hermes-relay daemon restart --administrator # Windows: request UAC and run elevated
|
||||
hermes-relay daemon restart --user # Windows: return to normal user mode
|
||||
hermes-relay daemon stop # stop it
|
||||
hermes-relay daemon # run in the FOREGROUND (current console)
|
||||
```
|
||||
@@ -553,15 +681,18 @@ hermes-relay daemon
|
||||
`status` reads the heartbeat file a running daemon maintains and cross-checks that the pid is alive — it exits non-zero (and says "not running") when the daemon is gone, so scripts can branch on it.
|
||||
|
||||
On Windows, keep the tray and normal daemon unelevated for routine operation.
|
||||
Use **Start/Restart daemon as Administrator...** only when a desktop action
|
||||
requires administrator access. Windows displays UAC consent, and the elevated
|
||||
daemon records its privilege level in the same status file so later stop and
|
||||
restart actions preserve the required elevation.
|
||||
Use **Restart as Administrator...** only when a desktop action requires
|
||||
administrator access. Windows displays UAC consent, and the elevated daemon
|
||||
records its privilege level in the same status file so the UI can label it
|
||||
clearly. Use **Return to user mode** to stop it once and start a normal daemon.
|
||||
The equivalent CLI actions are `daemon restart --administrator` and `daemon
|
||||
restart --user`; both are Windows-only and mutually exclusive.
|
||||
|
||||
> **Auto-start on boot/login:** the Windows menu can start the tray at user
|
||||
> sign-in; it intentionally does not auto-elevate or silently start an
|
||||
> Administrator daemon. Starting the daemon itself as a service still needs an
|
||||
> OS service, systemd user unit, or launchd agent.
|
||||
> **Auto-start on boot/login:** **Start UI at sign-in** registers the tray at
|
||||
> user sign-in. **Start daemon with UI** is a separate opt-in and remains off
|
||||
> for existing installs until enabled. Neither option auto-elevates or starts
|
||||
> an Administrator daemon. Starting the daemon itself as a machine service
|
||||
> still needs an OS service, systemd user unit, or launchd agent.
|
||||
|
||||
## Flags and environment
|
||||
|
||||
@@ -583,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.
|
||||
|
||||
Generated
+2
-2
@@ -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,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": {
|
||||
@@ -49,7 +49,7 @@
|
||||
"dev:install": "node scripts/dev-install.mjs",
|
||||
"dev:install:tray": "npm run dev:install && node scripts/dev-install-tray.mjs",
|
||||
"type-check": "tsc --noEmit -p tsconfig.json",
|
||||
"test": "tsx --test tests/**/*.test.ts",
|
||||
"test": "tsx --test --test-concurrency=1 tests/**/*.test.ts",
|
||||
"clean": "rimraf dist"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user