Compare commits
119
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d9624e2ef | ||
|
|
4b063d3fd7 | ||
|
|
9b9d7b654c | ||
|
|
a26e17e72c | ||
|
|
a3a6a9bb13 | ||
|
|
169bd09559 | ||
|
|
45d631e7ac | ||
|
|
eb6a6c95d2 | ||
|
|
3b102663c2 | ||
|
|
0e5fc4c606 | ||
|
|
c3189f2cbb | ||
|
|
06d88ad40a | ||
|
|
8ae5b3fbc2 | ||
|
|
39b7a8f108 | ||
|
|
af6e167692 | ||
|
|
274bd6ae98 | ||
|
|
9fc55b379a | ||
|
|
559a0ffdc8 | ||
|
|
75bcd9180f | ||
|
|
9c995a443d | ||
|
|
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 | ||
|
|
7ef2420c85 | ||
|
|
6a810c850b | ||
|
|
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 | ||
|
|
4605b87c10 | ||
|
|
6a91d6ee7e | ||
|
|
95a2813efe | ||
|
|
2ecf521c8c | ||
|
|
7752c5c404 | ||
|
|
e1d3764cd2 | ||
|
|
e34171b5ad | ||
|
|
8040cac39a | ||
|
|
aab70520ca | ||
|
|
5a0cd8123c | ||
|
|
4370d9a925 | ||
|
|
726308d2ef | ||
|
|
1acc3a4c80 | ||
|
|
11ccbd6e5c | ||
|
|
d13af35357 | ||
|
|
e3752d43f3 | ||
|
|
97293b62c3 | ||
|
|
454e770648 | ||
|
|
e18572e8e3 | ||
|
|
83f69725b9 | ||
|
|
72aa7c3046 | ||
|
|
3995c64493 | ||
|
|
ce538ced3d | ||
|
|
352bc5b439 | ||
|
|
9ec163b27b | ||
|
|
7a3efa2c4d | ||
|
|
c28be7c92e | ||
|
|
8d1758ec8b | ||
|
|
ce8b8702c3 | ||
|
|
ca0a9eb524 | ||
|
|
b91d8c9a09 | ||
|
|
bebd327816 | ||
|
|
8fa97e0b46 | ||
|
|
45dc82e573 | ||
|
|
48b23f4d9e | ||
|
|
f708ef3353 | ||
|
|
3224595a46 | ||
|
|
c0453f040d | ||
|
|
33a0ea3216 | ||
|
|
cec05ceec2 | ||
|
|
0e30699fff | ||
|
|
d4041e4528 | ||
|
|
c5ae402cd7 |
@@ -63,7 +63,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
@@ -95,7 +95,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
@@ -139,7 +139,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
@@ -203,7 +203,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
|
||||
@@ -100,13 +100,15 @@ jobs:
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: desktop/package-lock.json
|
||||
cache-dependency-path: |
|
||||
desktop/package-lock.json
|
||||
desktop/tray/package-lock.json
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
- name: Check tray formatting
|
||||
run: npm run tray:fmt
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6.2.0
|
||||
uses: gradle/actions/setup-gradle@v6.3.0
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
|
||||
@@ -168,7 +168,9 @@ jobs:
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: desktop/package-lock.json
|
||||
cache-dependency-path: |
|
||||
desktop/package-lock.json
|
||||
desktop/tray/package-lock.json
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -179,7 +181,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
- name: Type-check
|
||||
run: npm run type-check
|
||||
@@ -213,12 +215,153 @@ jobs:
|
||||
$proc = Start-Process -FilePath tray/target/release/hermes-relay-tray.exe -WindowStyle Hidden -PassThru
|
||||
Start-Sleep -Seconds 5
|
||||
if ($proc.HasExited) { throw "tray app exited early with code $($proc.ExitCode)" }
|
||||
$proc.Refresh()
|
||||
if ($proc.MainWindowHandle -ne 0) { throw 'menu-only systray created an application window' }
|
||||
$traySize = (Get-Item tray/target/release/hermes-relay-tray.exe).Length
|
||||
if ($traySize -gt 5242880) { throw "tray executable exceeds 5 MiB: $traySize bytes" }
|
||||
if ($traySize -le 0) { throw 'tray executable is empty' }
|
||||
Stop-Process -Id $proc.Id -Force
|
||||
Write-Host "menu-only tray launch smoke OK pid=$($proc.Id) bytes=$traySize"
|
||||
Write-Host "management tray launch smoke OK pid=$($proc.Id) bytes=$traySize"
|
||||
|
||||
- name: Smoke-test packaged installer lifecycle
|
||||
shell: pwsh
|
||||
env:
|
||||
EXPECTED_DESKTOP_VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Normalize-UserPath([string]$Value) {
|
||||
return (@($Value -split ';' | Where-Object { $_ }) -join ';')
|
||||
}
|
||||
|
||||
function Get-RawUserPath {
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
|
||||
if ($null -eq $environmentKey) { return '' }
|
||||
try {
|
||||
return [string]$environmentKey.GetValue(
|
||||
'Path',
|
||||
'',
|
||||
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
|
||||
)
|
||||
} finally {
|
||||
$environmentKey.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$setup = (Resolve-Path 'dist/tray/hermes-relay-windows-x64-setup.exe').Path
|
||||
$smokeRoot = Join-Path $env:RUNNER_TEMP 'hermes-installer-lifecycle-smoke'
|
||||
$smokeProfile = Join-Path $smokeRoot 'profile'
|
||||
$installDir = Join-Path $smokeRoot 'installed files'
|
||||
$sessionDir = Join-Path $smokeProfile '.hermes'
|
||||
$sessionSentinel = Join-Path $sessionDir 'remote-sessions.json'
|
||||
$uninstaller = Join-Path $installDir 'uninstall-hermes-relay.exe'
|
||||
$uninstallKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\HermesRelay'
|
||||
$productKey = 'HKCU:\Software\HermesRelay'
|
||||
$startupKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
|
||||
$startMenuDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Hermes-Relay CLI'
|
||||
$oldUserProfile = $env:USERPROFILE
|
||||
$oldHomeEnv = $env:HOME
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$hadUserPath = $environmentKey.GetValueNames() -contains 'Path'
|
||||
$originalUserPath = Get-RawUserPath
|
||||
$originalUserPathKind = if ($hadUserPath) { $environmentKey.GetValueKind('Path') } else { $null }
|
||||
$userPathBefore = 'C:\Windows\System32'
|
||||
$environmentKey.Dispose()
|
||||
$startupBefore = (Get-ItemProperty -Path $startupKey -Name HermesRelayTray -ErrorAction SilentlyContinue).HermesRelayTray
|
||||
|
||||
if (Test-Path $uninstallKey) { throw 'installer smoke requires a clean HermesRelay uninstall registry key' }
|
||||
if (Test-Path $productKey) { throw 'installer smoke requires a clean HermesRelay product registry key' }
|
||||
if (Test-Path $smokeRoot) { Remove-Item -LiteralPath $smokeRoot -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $sessionDir | Out-Null
|
||||
Set-Content -LiteralPath $sessionSentinel -Value '{"sentinel":"preserve-me"}' -Encoding UTF8
|
||||
|
||||
$env:USERPROFILE = $smokeProfile
|
||||
$env:HOME = $smokeProfile
|
||||
try {
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$environmentKey.SetValue('Path', $userPathBefore, [Microsoft.Win32.RegistryValueKind]::String)
|
||||
$environmentKey.Dispose()
|
||||
|
||||
$installProcess = Start-Process -FilePath $setup -ArgumentList @('/S', "/D=$installDir") -Wait -PassThru
|
||||
if ($installProcess.ExitCode -ne 0) { throw "installer exited with code $($installProcess.ExitCode)" }
|
||||
|
||||
$expectedFiles = @(
|
||||
'hermes-relay.exe',
|
||||
'hermes-relay-tray.exe',
|
||||
'hermes-relay-ui.cmd',
|
||||
'hermes-relay-path.ps1',
|
||||
'uninstall-hermes-relay.exe'
|
||||
)
|
||||
foreach ($name in $expectedFiles) {
|
||||
$path = Join-Path $installDir $name
|
||||
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
|
||||
throw "packaged installer did not create $path"
|
||||
}
|
||||
}
|
||||
|
||||
$cli = Join-Path $installDir 'hermes-relay.exe'
|
||||
$versionOutput = (& $cli --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw "installed CLI --version exited with code $LASTEXITCODE" }
|
||||
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
||||
throw "installed CLI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$versionOutput'"
|
||||
}
|
||||
$helpOutput = (& $cli --help | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
|
||||
throw 'installed CLI --help smoke failed'
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $sessionSentinel -PathType Leaf)) {
|
||||
throw 'installer removed profile session data'
|
||||
}
|
||||
|
||||
$uninstallProcess = Start-Process -FilePath $uninstaller -ArgumentList '/S' -Wait -PassThru
|
||||
if ($uninstallProcess.ExitCode -ne 0) { throw "uninstaller exited with code $($uninstallProcess.ExitCode)" }
|
||||
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(20)
|
||||
while ((Test-Path -LiteralPath $uninstaller) -and [DateTime]::UtcNow -lt $deadline) {
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
foreach ($name in $expectedFiles) {
|
||||
$path = Join-Path $installDir $name
|
||||
if (Test-Path -LiteralPath $path) { throw "uninstaller left owned artifact $path" }
|
||||
}
|
||||
if (Test-Path $uninstallKey) { throw 'uninstaller left the Installed Apps registry key' }
|
||||
if (Test-Path $productKey) { throw 'uninstaller left the HermesRelay product registry key' }
|
||||
if (Test-Path -LiteralPath $startMenuDir) { throw "uninstaller left Start-menu artifacts at $startMenuDir" }
|
||||
if (-not (Test-Path -LiteralPath $sessionSentinel -PathType Leaf)) {
|
||||
throw 'uninstaller removed preserved profile session data'
|
||||
}
|
||||
if ((Get-Content -LiteralPath $sessionSentinel -Raw) -notmatch 'preserve-me') {
|
||||
throw 'installer lifecycle modified preserved profile session data'
|
||||
}
|
||||
|
||||
# Compare the raw registry value so expandable entries such as
|
||||
# %USERPROFILE% are not resolved against the isolated smoke profile.
|
||||
$userPathAfter = Normalize-UserPath (Get-RawUserPath)
|
||||
if ($userPathAfter -ne $userPathBefore) {
|
||||
throw "uninstaller did not restore user PATH (before='$userPathBefore', after='$userPathAfter')"
|
||||
}
|
||||
$startupAfter = (Get-ItemProperty -Path $startupKey -Name HermesRelayTray -ErrorAction SilentlyContinue).HermesRelayTray
|
||||
if ($startupAfter -ne $startupBefore) {
|
||||
throw "installer lifecycle changed the pre-existing tray startup preference"
|
||||
}
|
||||
|
||||
Write-Host "packaged installer lifecycle smoke OK version=$versionOutput install=$installDir"
|
||||
} finally {
|
||||
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
|
||||
Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
if (Test-Path -LiteralPath $uninstaller) {
|
||||
Start-Process -FilePath $uninstaller -ArgumentList '/S' -Wait | Out-Null
|
||||
}
|
||||
$env:USERPROFILE = $oldUserProfile
|
||||
$env:HOME = $oldHomeEnv
|
||||
$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
if ($hadUserPath) {
|
||||
$environmentKey.SetValue('Path', $originalUserPath, $originalUserPathKind)
|
||||
} else {
|
||||
$environmentKey.DeleteValue('Path', $false)
|
||||
}
|
||||
$environmentKey.Dispose()
|
||||
if (Test-Path -LiteralPath $smokeRoot) {
|
||||
Remove-Item -LiteralPath $smokeRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
- name: Upload Windows tray release asset
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
+157
-2
@@ -6,11 +6,166 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **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
|
||||
|
||||
- **Issue area labels require maintainer review.** The unreliable keyword-based auto-labeling workflow no longer assigns ownership from ambiguous issue text.
|
||||
- **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.
|
||||
|
||||
## [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
|
||||
|
||||
### Added
|
||||
|
||||
- **Desktop tools support explicit host targeting.** Every client-routed desktop tool accepts a stable device ID or unambiguous computer name, and `/desktop/health` enumerates connected targets and their advertised tools.
|
||||
- **USB operations retain both routing scopes.** Raw USB and ADB tools use `device` to select the desktop PC, while ADB operations continue to use `serial` to select hardware attached to that PC.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Multiple desktop clients remain connected simultaneously.** The Relay no longer replaces the previous desktop when another heartbeat arrives; concurrent requests are bound to their selected WebSockets, responses from another PC are ignored, and an untargeted call fails closed when several desktops are online.
|
||||
- **Pairing another desktop preserves existing credentials.** Legacy placeholder device identifiers are treated as absent instead of shared ownership, preventing an unrelated PC from revoking the first desktop's session.
|
||||
|
||||
## [1.6.3] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay diagnostics distinguish a prior clean stop from a crash.** Doctor and `/relay/info` expose only bounded clean, unclean, or unknown gateway-exit state with an optional suspected out-of-memory hint, without returning raw log evidence.
|
||||
- **Relay reconnects spread out after shared gateway restarts.** Ordinary exponential reconnect delays use full jitter while explicit reconnects and server-directed retry timing retain their exact behavior.
|
||||
|
||||
## [0.4.0-alpha.7] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installer lifecycle validation uses an isolated Windows PATH fixture.** Release smoke tests now verify add/remove cleanup against a fixed registry value and restore the runner's original value afterward, independently of the temporary profile used for session-preservation checks.
|
||||
|
||||
## [0.4.0-alpha.6] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installer cleanup validation compares the unexpanded Windows PATH.** Release smoke tests now read the raw user registry value, ensuring `%USERPROFILE%` entries are verified without temporary-profile expansion changing their apparent value.
|
||||
|
||||
## [0.4.0-alpha.5] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installer cleanup validation handles expandable Windows PATH entries.** Release smoke tests restore the original profile environment before comparing user PATH, avoiding false failures when unchanged `%USERPROFILE%` entries are expanded inside an isolated test profile.
|
||||
|
||||
## [0.4.0-alpha.4] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows release validation waits for installer processes.** The packaged install/uninstall lifecycle smoke now captures GUI-subsystem process exit codes reliably before validating installed files, preserved sessions, registry state, and cleanup.
|
||||
|
||||
## [0.4.0-alpha.3] - 2026-08-11
|
||||
|
||||
### Added
|
||||
|
||||
- **Windows tray provides focused remote-access management.** The compact host-aware popup covers connection state, per-host Ask/Trusted/Full Access, pending grant dialogs, authorized-client revocation, activity, daemon controls, and settings without adding chat, terminal, plugin, voice, or session surfaces.
|
||||
- **Desktop access policy is isolated per Hermes host.** `hermes-relay hosts` lists and selects local pairings and stores fail-closed access modes independently for each canonical relay URL.
|
||||
- **Windows CLI installations can add or open the management UI directly.** `hermes-relay ui install|open|status` and the installed UI shim provide a supported lifecycle for optional UI setup, discovery, and activation.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Daemon connectivity no longer requires a tool grant.** Ask mode can keep an authenticated daemon connected with zero desktop tools attached; Trusted enables command/file tools with task-scoped screen/input grants, while Full Access removes those task prompts only for the selected host.
|
||||
- **Windows bundle updates preserve the desktop lifecycle.** The CLI and tray coordinate one verified installer launch, restore the daemon and UI after setup, and permit same-version UI add or repair without silently downgrading a newer CLI.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Background daemon start reports real readiness.** Detached startup now waits for the spawned process to authenticate and connect, and returns actionable log evidence for configuration, authentication, early-exit, and timeout failures.
|
||||
- **Local and release tray builds embed the packaged UI.** Development installs use Tauri's production protocol instead of attempting to load a missing localhost development server, and release CI exercises a silent install/uninstall lifecycle.
|
||||
- **Windows-trusted certificates work in the desktop CLI.** The packaged Windows binary and newer Node runtimes add the Windows certificate store without dropping bundled or operator-supplied roots, while TLS verification and Relay certificate pinning remain enforced.
|
||||
|
||||
## [1.6.2] - 2026-08-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Paired sessions use recognizable device identities.** Relay sessions preserve a client-provided hostname as the primary name, retain model and platform details, and enrich valid reconnects without requiring users to pair again.
|
||||
- **Long-lived session expiry is readable.** The Dashboard presents paired-session lifetime in days or weeks with the exact local deadline available in the detail view instead of accumulating hundreds of hours.
|
||||
|
||||
## [Android 1.8.1] - 2026-08-09
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android preserves complete long-session transcripts.** API-server and profile-scoped Dashboard history reads now use explicit bounded pagination, retain compatibility with older unpaginated responses, and keep edit, retry, sharing, and recovery anchors stable beyond Hermes' latest-500 default window.
|
||||
- **Android follows authoritative Gateway turn contracts.** Submit rejections retain the server's message without silently falling through to SSE, event envelopes reconcile consistently, and edit-and-regenerate requests send the required truncation confirmation.
|
||||
|
||||
## [Android 1.8.0] - 2026-08-09
|
||||
|
||||
### Added
|
||||
@@ -517,7 +672,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.
|
||||
|
||||
+15
-19
@@ -1,35 +1,31 @@
|
||||
# Hermes-Relay-CLI v__VERSION__
|
||||
# Hermes-Relay CLI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-07-13
|
||||
**Release Date:** 2026-08-14
|
||||
|
||||
This alpha makes the desktop direction explicit: Hermes-Relay is a real CLI/TUI with an optional Windows right-click systray—not a second desktop application. The old Tauri/WebView dashboard and its embedded windows are gone. The installed CLI remains the single source of behavior for pairing, TUI, daemon management, grants, audit, diagnostics, chat, voice, and tools.
|
||||
This beta makes connection recovery and Activity evidence inspectable in the compact management UI, and keeps the preferred CUA control engine usable when its upstream whole-desktop accessibility probe times out.
|
||||
|
||||
**Experimental phase.** Assets are 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 optional native systray 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
|
||||
|
||||
- **Persistent desktop-use control.** `hermes-relay computer-use status|enable|disable|cancel` stores one local preference, reports daemon privilege and active/pending grants, and can end an active task-scoped grant without relying on a GUI.
|
||||
- **Headless grant review.** `hermes-relay grants` lists pending local computer-use requests and supports interactive review plus explicit `approve`, `reject`, and JSON forms for scripts.
|
||||
- **Typed Relay chat option.** `chat --relay-chat` sends `chat.send` over WSS and renders typed `stream.event` v1 assistant, tool, artifact, memory, skill, and error lifecycles while preserving the existing gateway path as the default.
|
||||
- **Release-parity verification.** One version contract now keeps the npm package, compiled CLI, Rust tray, lockfile, and installer metadata aligned. The Windows verification target covers TypeScript, compiled-binary smoke tests, Rust formatting/lint/check/tests, and installer packaging.
|
||||
- **Inspectable Activity evidence.** Commands, files, device work, connection lifecycle, and computer control share a consistent event stepper with dedicated failure details.
|
||||
- **Optional screenshot retention.** Screenshot events can keep bounded local PNG evidence for Off, 1 day, 7 days, or 30 days and open it in a larger borderless viewer. Evidence stays outside the JSON activity log.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Menu-only Windows systray.** The optional tray is a small native Rust process with no application window, WebView, overlay, embedded terminal, chat view, voice view, or settings dashboard. Interactive actions open the installed CLI in a normal terminal.
|
||||
- **State- and privilege-aware daemon control.** The menu reports PID-backed daemon state and User/Administrator privilege, disables invalid lifecycle actions, and requests UAC only when **Start/Restart daemon as Administrator…** is explicitly chosen. The tray itself remains unprivileged.
|
||||
- **Visible desktop-use safety.** The tray shows enablement, active grant mode and expiry, warns when an Administrator control grant is active, raises a native alert for pending approvals, opens CLI grant review, and provides immediate cancellation and emergency stop.
|
||||
- **Per-user Windows installation.** The default PowerShell installer downloads the checksum-verified NSIS package, installs the CLI and optional tray under `~/.hermes/bin`, adds Start-menu shortcuts and user PATH, and can start the tray at sign-in. CLI-only installation remains available with `HERMES_RELAY_INSTALL_SURFACE=cli`.
|
||||
- **Connection state is live and actionable.** The UI distinguishes connected, reconnecting, and stopped states, shows retry timing, and offers Retry now without freezing the popup.
|
||||
- **Connection notices stay out of the way.** Compact connect, disconnect, and reconnect cards appear only while the main management UI is hidden.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Installed-binary diagnostics.** `hermes-relay doctor` reports the physical Bun-compiled executable instead of a virtual embedded-module path, so PATH and install-directory checks describe the binary that actually launched.
|
||||
- **Release guardrails.** CLI tag automation rejects version drift, tags not contained in `main`, oversized tray binaries, or a tray process that creates an application window.
|
||||
- **CUA readiness no longer depends on the flaky global accessibility scan.** Hermes verifies the canonical runtime, required tools, daemon, and safe permission mode before structured control; explicit accessibility health remains available for diagnosis and individual actions still fail closed.
|
||||
- **Connection errors retain useful context.** Activity records bounded retry and recovery evidence without flooding one event per backoff attempt.
|
||||
|
||||
## Install
|
||||
|
||||
**Windows CLI + optional systray (PowerShell):**
|
||||
**Windows CLI + management tray (PowerShell):**
|
||||
|
||||
```powershell
|
||||
irm https://raw.githubusercontent.com/Codename-11/hermes-relay/main/desktop/scripts/install.ps1 | iex
|
||||
@@ -53,11 +49,11 @@ Pin this release with `HERMES_RELAY_VERSION=__TAG__`.
|
||||
|
||||
```text
|
||||
hermes-relay --version
|
||||
hermes-relay pair --remote ws://<host>:8767 --grant-tools
|
||||
hermes-relay hosts list --json
|
||||
hermes-relay daemon start
|
||||
hermes-relay daemon status
|
||||
hermes-relay daemon status --json
|
||||
```
|
||||
|
||||
On Windows, open **Hermes Relay Systray** from the Start menu and right-click its notification-area icon. No separate desktop window is installed.
|
||||
On Windows, click the Hermes-Relay CLI UI notification-area icon to open the management popup directly above it.
|
||||
|
||||
See the [CLI and systray guide](https://hermes-relay.dev/docs/desktop/) for installation, commands, desktop-use safety, and troubleshooting.
|
||||
See the [CLI and tray guide](https://hermes-relay.dev/docs/desktop/) for installation, access modes, grants, and troubleshooting.
|
||||
|
||||
+11
-5
@@ -1,17 +1,22 @@
|
||||
# Hermes-Relay-Server v__VERSION__
|
||||
|
||||
**Release Date:** August 8, 2026
|
||||
**Release Date:** August 14, 2026
|
||||
|
||||
This patch makes the optional Dashboard plugin's Android setup handoff reliable for hosted Hermes connections.
|
||||
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
|
||||
### Added
|
||||
|
||||
- **Canonical hosted-Hermes setup handoff.** The Dashboard plugin supplies the verified Dashboard address Android needs to continue through the official system-browser authentication flow.
|
||||
- **Contained dialog focus behavior.** Mobile setup dialogs retain their own focus and keyboard handling without disrupting the surrounding Dashboard.
|
||||
- **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
|
||||
|
||||
@@ -26,6 +31,7 @@ Standard chat, session history, and Vanilla Hermes voice remain upstream-owned a
|
||||
## Verify
|
||||
|
||||
hermes relay doctor
|
||||
# Agent/tool callers can use desktop_health to list desktop targets.
|
||||
python scripts/check-plugin-version-sync.py --expect __VERSION__
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
@@ -186,7 +201,7 @@ tracked independently so community corrections remain easy to contribute.
|
||||
|
||||
## Hands on any machine — the Hermes-Relay CLI <sub>(alpha)</sub>
|
||||
|
||||
> **Alpha.** Self-contained CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64 — no Node required. Windows also has an optional native, menu-only systray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
|
||||
> **Alpha.** Self-contained CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64 — no Node required. Windows also has an optional compact management tray. Assets are unsigned during the experimental phase, so SmartScreen / Gatekeeper warnings are expected.
|
||||
|
||||
The agent's brain stays on the host; the CLI lets it call tools **on your machine** over the same WSS relay — `read_file`, `write_file`, `terminal`, `search_files`, `screenshot`, `clipboard`, `open_in_editor`, and more — behind a one-time consent gate, interactive diff approval for patches, and a `--no-tools` kill-switch.
|
||||
|
||||
@@ -202,7 +217,15 @@ hermes-relay update # self-update via GitHub Releases
|
||||
|
||||
It pairs against the **same relay and credential store** as the Android app — pair once from either, both work. Tagged on the `desktop-v*` [release track](https://github.com/Codename-11/hermes-relay/releases?q=desktop), with historical releases still visible under `cli-v*`.
|
||||
|
||||
On Windows, the default installer adds the optional right-click-only systray: no dashboard or app window, just TUI launch, User/Administrator-aware daemon controls, pairing, local grant review, audit, diagnostics, logs, desktop-use status/cancellation, sign-in startup, and emergency stop.
|
||||
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`
|
||||
|
||||
+6
-3
@@ -119,9 +119,9 @@ artifacts.
|
||||
### CLI / tray versioning
|
||||
|
||||
`desktop/package.json` is the Desktop/CLI release track's source of truth. Its version
|
||||
must match the generated CLI and native Windows systray metadata. The systray is
|
||||
a menu-only controller for the installed CLI; it has no application window,
|
||||
WebView, embedded terminal, or separate desktop product surface. The public
|
||||
must match the generated CLI and Windows tray metadata. The tray is a compact
|
||||
management popup over the installed CLI and shared state; it has no chat,
|
||||
embedded terminal, plugins, voice, or separate desktop product surface. The public
|
||||
release remains one `Hermes-Relay-Desktop` track containing CLI binaries plus the
|
||||
optional Windows installer.
|
||||
|
||||
@@ -132,6 +132,9 @@ optional Windows installer.
|
||||
| `desktop/src/version.ts` | compiled CLI runtime version |
|
||||
| `desktop/tray/Cargo.toml` | native systray package version |
|
||||
| `desktop/tray/Cargo.lock` | locked systray package version |
|
||||
| `desktop/tray/tauri.conf.json` | tray application and bundle version |
|
||||
| `desktop/tray/package.json` | tray UI package version |
|
||||
| `desktop/tray/package-lock.json` | locked tray UI package version |
|
||||
|
||||
Prepare a new CLI version on `dev` without creating a tag or npm-generated
|
||||
commit:
|
||||
|
||||
+12
-32
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay-Android v1.8.0
|
||||
# Hermes-Relay-Android v1.8.1
|
||||
|
||||
**Release Date:** August 9, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.8.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).
|
||||
> 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).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,42 +12,22 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This release makes mobile conversations calmer and more capable: richer message
|
||||
actions and attachments, concise reasoning and tool activity, immediate profile
|
||||
switching, and deeper appearance customization without mixing session identity.
|
||||
|
||||
## Added
|
||||
|
||||
- Quote or edit a message, attach and reorder files with previews, search the
|
||||
conversation, and jump between prompt turns without losing session context.
|
||||
- Switch agents from the compact Profile Shelf while preserving each profile's
|
||||
last session and the server-default identity.
|
||||
- Share text from another Android app into a fresh reviewed Chat draft.
|
||||
- Customize theme accents and shapes, import Sphere skins, and create or install
|
||||
pets from one live-preview Appearance workflow.
|
||||
|
||||
## Changed
|
||||
|
||||
- Live reasoning opens inline and settles to a compact Thought disclosure.
|
||||
Routine tool work groups into a concise activity surface, while approvals,
|
||||
failures, generated media, edits, risks, and delegated work stay distinct.
|
||||
- Agent Passport controls remain session-scoped: model and reasoning choices no
|
||||
longer overwrite server defaults merely by inspecting or switching profiles.
|
||||
This patch keeps long Hermes conversations complete and aligns Android's
|
||||
Gateway behavior with current upstream turn contracts.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Configured voice can speak any completed assistant message without requiring
|
||||
Voice Mode, and the same message menu exposes Stop during playback.
|
||||
- Quotes remain readable inside bubbles, portrait images honor EXIF rotation,
|
||||
and keyboard controls follow standard capitalization and Enter behavior.
|
||||
- Persisted Gateway history recovers missing structured tool activity without
|
||||
republishing healthy transcript state or duplicating cards.
|
||||
- Floating pets avoid chat identity rows and controls while scrolling, remain
|
||||
touchable for their menu, and Appearance stays clear of system status bars.
|
||||
- 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.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.8.0** (versionCode **41**).
|
||||
- App version: **1.8.1** (versionCode **42**).
|
||||
- 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,6 +6,40 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Certify the official Desktop Relay plugin
|
||||
|
||||
The unified `plugin/desktop/plugin.js` implementation is covered by source-level
|
||||
SDK contract, packaging, explicit-open, no-auto-open, close, unload, and profile
|
||||
cache-isolation tests. A physical official Hermes Desktop session is still
|
||||
required before calling the UX live-certified:
|
||||
|
||||
- Test default and named local profiles, ordinary authenticated remote mode,
|
||||
and SSH mode with differently named local/remote profile mapping.
|
||||
- In two full app windows, prove enabling, registration, explicit open,
|
||||
requests, close/reopen, hot reload, and disable/unload remain window-local.
|
||||
- Prove startup, reconnect, profile change, layout restore/reset, update, and
|
||||
background events never open or focus Relay.
|
||||
- Drag and dock the pane across native zones, close it, reopen it from all three
|
||||
labeled actions, and verify no private-hook fallback is needed.
|
||||
- Exercise Relay running/unreachable, zero/one/multiple devices, pairing,
|
||||
revocation, bridge activity, media, remote access, and renderer error logging
|
||||
without exposing credentials, pairing payloads, filesystem paths, or tokens.
|
||||
|
||||
---
|
||||
|
||||
## Structured desktop hardware capabilities
|
||||
|
||||
Structured access and per-host USB policy now ship with typed, serial-bound ADB
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Android Plugin Studio protocol follow-ups
|
||||
|
||||
The first live declarative Plugin lane is host-local: Relay tools create bounded
|
||||
@@ -909,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)
|
||||
@@ -922,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).
|
||||
@@ -942,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
|
||||
@@ -951,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.
|
||||
|
||||
@@ -1217,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)
|
||||
@@ -370,8 +371,8 @@ dependencies {
|
||||
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
|
||||
// Renders real composables on the JVM at an exact canvas — no device, no
|
||||
// status bar, no clipping. See StoreScreenshotTest.
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.70.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.70.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.71.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.71.0")
|
||||
testImplementation(libs.compose.ui.test.junit4)
|
||||
testImplementation(libs.compose.ui.test.manifest)
|
||||
testImplementation("androidx.test.ext:junit:1.3.0")
|
||||
|
||||
@@ -1 +1 @@
|
||||
Quote, edit, search, and attach files without losing chat context. Switch profiles from Chat while each agent keeps its own session. Thinking and routine tool activity are cleaner, message actions can speak or stop completed replies, Appearance adds live theme and companion previews, and floating pets avoid controls while scrolling.
|
||||
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.
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.8.1",
|
||||
"title": "Complete, reliable transcripts",
|
||||
"date": "2026-08-09",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Keep long sessions complete",
|
||||
"bullets": [
|
||||
"Android pages explicitly through complete API-server and profile-scoped Dashboard history instead of silently stopping at Hermes' latest-500 default.",
|
||||
"Sharing, retry, edit, and recovery retain stable transcript anchors while bounded safety limits keep unusually large reads controlled."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Follow Gateway truth",
|
||||
"bullets": [
|
||||
"Authoritative submit rejections preserve the server's message without an unintended SSE fallback.",
|
||||
"Gateway event envelopes and edit-and-regenerate truncation confirmation now follow current upstream contracts."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.8.0",
|
||||
"title": "Conversations with more context",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
v1.8.0 - Conversations with more context
|
||||
v1.8.1 - Complete, reliable transcripts
|
||||
|
||||
* Quote, edit, search, and attach files without losing the active chat context.
|
||||
* Switch profiles quickly from Chat while each agent keeps its own session.
|
||||
* Read quieter thinking and grouped tool activity, with important actions kept distinct.
|
||||
* Speak or stop completed replies directly from message actions.
|
||||
* Customize themes, Sphere skins, and pets from a live Appearance preview.
|
||||
* 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.
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
package com.hermesandroid.relay.auth
|
||||
|
||||
import android.content.Context
|
||||
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
|
||||
@@ -14,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
|
||||
@@ -557,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
|
||||
@@ -631,7 +643,7 @@ class AuthManager(
|
||||
val now = System.currentTimeMillis() / 1000L
|
||||
val defaults = PairedSession(
|
||||
token = token,
|
||||
deviceName = android.os.Build.MODEL,
|
||||
deviceName = relayDeviceName(),
|
||||
expiresAt = null,
|
||||
grants = emptyMap(),
|
||||
transportHint = null,
|
||||
@@ -651,7 +663,7 @@ class AuthManager(
|
||||
val transportHint = obj["transport_hint"]?.jsonPrimitive?.contentOrNull
|
||||
val firstSeen = obj["first_seen"]?.jsonPrimitive?.longOrNull ?: now
|
||||
val deviceName = obj["device_name"]?.jsonPrimitive?.contentOrNull
|
||||
?: android.os.Build.MODEL
|
||||
?: relayDeviceName()
|
||||
|
||||
PairedSession(
|
||||
token = token,
|
||||
@@ -750,6 +762,26 @@ class AuthManager(
|
||||
})
|
||||
}
|
||||
|
||||
private fun JsonObjectBuilder.putRelayDeviceIdentity() {
|
||||
val model = android.os.Build.MODEL.orEmpty().ifBlank { "Android device" }
|
||||
val deviceName = relayDeviceName()
|
||||
put("device_name", deviceName)
|
||||
put("device_hostname", deviceName)
|
||||
put("device_model", model)
|
||||
put("device_platform", "Android ${android.os.Build.VERSION.RELEASE}")
|
||||
put("client_surface", "android")
|
||||
put("device_form_factor", "phone")
|
||||
}
|
||||
|
||||
private fun relayDeviceName(): String {
|
||||
val configured = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "device_name")
|
||||
}.getOrNull()?.trim().orEmpty()
|
||||
return configured.ifBlank {
|
||||
android.os.Build.MODEL.orEmpty().ifBlank { "Android device" }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send auth envelope when connection is established.
|
||||
*
|
||||
@@ -784,7 +816,7 @@ class AuthManager(
|
||||
put("refresh_token", refreshToken)
|
||||
}
|
||||
put("device_id", deviceId)
|
||||
put("device_name", android.os.Build.MODEL)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
}
|
||||
}
|
||||
@@ -800,7 +832,7 @@ class AuthManager(
|
||||
buildJsonObject {
|
||||
put("pairing_code", codeToSend)
|
||||
put("device_id", deviceId)
|
||||
put("device_name", android.os.Build.MODEL)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
pendingTtlSeconds?.let { put("ttl_seconds", it) }
|
||||
pendingGrants?.let { grants ->
|
||||
@@ -1021,6 +1053,7 @@ class AuthManager(
|
||||
}
|
||||
|
||||
if (token != null) {
|
||||
applyBrokerRouteCredential(payload)
|
||||
val s = store()
|
||||
s.putString(KEY_SESSION_TOKEN, token)
|
||||
val refreshToken = payload["refresh_token"]
|
||||
@@ -1066,7 +1099,7 @@ class AuthManager(
|
||||
|
||||
val paired = PairedSession(
|
||||
token = token,
|
||||
deviceName = android.os.Build.MODEL,
|
||||
deviceName = relayDeviceName(),
|
||||
expiresAt = expiresAt,
|
||||
grants = grantsMap,
|
||||
transportHint = transportHint,
|
||||
@@ -1129,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
|
||||
|
||||
@@ -74,6 +74,14 @@ data class PairedDeviceInfo(
|
||||
val deviceName: String = "",
|
||||
@SerialName("device_id")
|
||||
val deviceId: String = "",
|
||||
@SerialName("device_model")
|
||||
val deviceModel: String = "",
|
||||
@SerialName("device_platform")
|
||||
val devicePlatform: String = "",
|
||||
@SerialName("client_surface")
|
||||
val clientSurface: String = "",
|
||||
@SerialName("device_form_factor")
|
||||
val deviceFormFactor: String = "",
|
||||
@SerialName("created_at")
|
||||
val createdAt: Double? = null,
|
||||
@SerialName("last_seen")
|
||||
|
||||
@@ -141,6 +141,12 @@ 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,
|
||||
/**
|
||||
* Mixture-of-Agents advisor responses surfaced during the live turn.
|
||||
* Unavailable advisors retain only neutral state, never their raw failure
|
||||
@@ -366,6 +372,8 @@ data class ToolCall(
|
||||
* header can render without a separate lane registry.
|
||||
*/
|
||||
val taskLabel: String? = null,
|
||||
/** Live upstream child id used by subagent.steer while this lane runs. */
|
||||
val subagentId: String? = null,
|
||||
/** Deterministic non-low output risk reported by upstream for this call. */
|
||||
val outputRisk: String? = null,
|
||||
/** Human-readable deterministic findings; rendered as untrusted metadata. */
|
||||
@@ -419,6 +427,14 @@ 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 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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -19,6 +20,7 @@ import com.hermesandroid.relay.diagnostics.NetworkDiagnosticGuidance
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import com.hermesandroid.relay.network.shared.EndpointResolver
|
||||
import com.hermesandroid.relay.network.shared.EndpointSurface
|
||||
import com.hermesandroid.relay.network.shared.fullJitterDelayMs
|
||||
import com.hermesandroid.relay.network.shutdownOffMainThread
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -76,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,
|
||||
/**
|
||||
@@ -139,6 +144,10 @@ class ConnectionManager(
|
||||
* non-null — the manager falls back to the single-URL path.
|
||||
*/
|
||||
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,
|
||||
) {
|
||||
private val supervisorJob = SupervisorJob()
|
||||
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
|
||||
@@ -148,7 +157,7 @@ class ConnectionManager(
|
||||
encodeDefaults = true
|
||||
}
|
||||
|
||||
private fun buildClient(): OkHttpClient {
|
||||
private fun buildClient(url: String? = null): OkHttpClient {
|
||||
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
|
||||
@@ -162,7 +171,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)
|
||||
@@ -221,10 +232,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
|
||||
@@ -345,11 +358,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} " +
|
||||
@@ -376,7 +392,7 @@ class ConnectionManager(
|
||||
Log.i(
|
||||
TAG,
|
||||
"connect: relay resolver picked role=${relayRoute.role} " +
|
||||
"url=${relayRoute.relay?.url}",
|
||||
"url=${relayRoute.relayWebSocketUrl()}",
|
||||
)
|
||||
}
|
||||
if (targetUrl != null) {
|
||||
@@ -531,7 +547,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,
|
||||
@@ -609,7 +626,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
|
||||
@@ -618,8 +637,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
|
||||
@@ -656,7 +676,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
|
||||
@@ -665,6 +687,7 @@ class ConnectionManager(
|
||||
return _activeEndpoint.value
|
||||
}
|
||||
_activeEndpoint.value = resolved
|
||||
_activeApiEndpoint.value = apiResolved
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -681,7 +704,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)")
|
||||
}
|
||||
@@ -707,7 +730,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
|
||||
@@ -744,6 +769,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
|
||||
@@ -753,8 +779,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,
|
||||
@@ -899,7 +925,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()
|
||||
}
|
||||
|
||||
@@ -979,7 +1006,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) {
|
||||
@@ -1213,8 +1251,9 @@ class ConnectionManager(
|
||||
SLOW_POLL_BACKOFF_MS
|
||||
}
|
||||
else -> {
|
||||
val ms = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
|
||||
val capMs = (BASE_BACKOFF_MS * (1L shl minOf(reconnectAttempt - 1, 4)))
|
||||
.coerceAtMost(MAX_BACKOFF_MS)
|
||||
val ms = fullJitterDelayMs(capMs, reconnectJitterUnit())
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
severity = DiagnosticSeverity.Info,
|
||||
@@ -1236,7 +1275,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
|
||||
@@ -1244,7 +1283,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
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import kotlin.random.Random
|
||||
|
||||
/** Full-jitter retry delay in the inclusive range 0..[capMs]. */
|
||||
internal fun fullJitterDelayMs(
|
||||
capMs: Long,
|
||||
unit: Double = Random.nextDouble(),
|
||||
): Long {
|
||||
if (capMs <= 0L) return 0L
|
||||
val boundedUnit = unit.coerceIn(0.0, Math.nextDown(1.0))
|
||||
return (boundedUnit * (capMs + 1.0)).toLong().coerceAtMost(capMs)
|
||||
}
|
||||
@@ -90,12 +90,9 @@ class ChatHandler {
|
||||
// Fallback form (no relay): `MEDIA:/absolute/path` — relay wasn't
|
||||
// reachable when the tool fired, so we render an "unavailable"
|
||||
// placeholder instead of attempting a fetch.
|
||||
private val mediaRelayRegex = Regex("""MEDIA:hermes-relay://([A-Za-z0-9_-]+)""")
|
||||
// `/.+?` (not `/\S+`) so absolute paths containing spaces — e.g.
|
||||
// `MEDIA:/mnt/media/Coralee Adshade/undressher.jpg` — still match. The
|
||||
// trailing `\s*$` trims any trailing whitespace; non-greedy keeps the
|
||||
// capture to the path. OkHttp re-encodes the space for /media/by-path.
|
||||
private val mediaBarePathRegex = Regex("""^\s*MEDIA:(/.+?)\s*$""")
|
||||
private val mediaRelayPayloadRegex = Regex("""^hermes-relay://([A-Za-z0-9_-]+)$""")
|
||||
private val mediaMarkerPrefixRegex = Regex("MEDIA:")
|
||||
private val windowsAbsoluteMediaPathRegex = Regex("""^[A-Za-z]:[\\/].+""")
|
||||
// Rich card marker — single line, full JSON object payload.
|
||||
//
|
||||
// Agents emit:
|
||||
@@ -188,6 +185,7 @@ class ChatHandler {
|
||||
* post-stream finalize reconciliation pass.
|
||||
*/
|
||||
private var mediaLineBuffer = StringBuilder()
|
||||
private var mediaFenceDelimiter: String? = null
|
||||
private val dispatchedMediaMarkers = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
@@ -526,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 ->
|
||||
@@ -1176,12 +1197,14 @@ class ChatHandler {
|
||||
// Drop any pending line buffers / dedupe state so a fresh session
|
||||
// doesn't inherit leftovers from the previous one.
|
||||
mediaLineBuffer.clear()
|
||||
mediaFenceDelimiter = null
|
||||
dispatchedMediaMarkers.clear()
|
||||
annotationLineBuffer.clear()
|
||||
activeAnnotationTools.clear()
|
||||
cardLineBuffer.clear()
|
||||
dispatchedCardMarkers.clear()
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1497,6 +1520,7 @@ class ChatHandler {
|
||||
// this as the same visible row across the post-turn reload.
|
||||
prior.copy(
|
||||
id = messageId,
|
||||
rowId = item.rowId,
|
||||
role = role,
|
||||
content = cleanedContent,
|
||||
attachments = carriedAttachments,
|
||||
@@ -1527,6 +1551,7 @@ class ChatHandler {
|
||||
// nothing local to carry).
|
||||
ChatMessage(
|
||||
id = messageId,
|
||||
rowId = item.rowId,
|
||||
role = role,
|
||||
content = cleanedContent,
|
||||
attachments = carriedAttachments,
|
||||
@@ -1771,7 +1796,7 @@ class ChatHandler {
|
||||
for (line in text.lines()) {
|
||||
val t = line.trim()
|
||||
if (t.isEmpty()) continue
|
||||
if (mediaRelayRegex.containsMatchIn(t) || mediaBarePathRegex.containsMatchIn(t)) continue
|
||||
if (parseMediaMarkerLine(t).isNotEmpty()) continue
|
||||
if (PersistedImageReferenceParser.parse(t).paths.isNotEmpty()) continue
|
||||
if (cardMarkerRegex.containsMatchIn(t)) continue
|
||||
if (sb.isNotEmpty()) sb.append('\n')
|
||||
@@ -1788,6 +1813,51 @@ class ChatHandler {
|
||||
data class BarePath(val path: String) : MediaMarkerHit
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one marker-only line using upstream-compatible wrappers and
|
||||
* boundaries. Prose and malformed examples remain ordinary text; a whole
|
||||
* inline-code or emphasis wrapper is accepted, as are adjacent markers,
|
||||
* sentence-final punctuation, POSIX paths, and Windows absolute paths.
|
||||
*/
|
||||
private fun parseMediaMarkerLine(line: String): List<MediaMarkerHit> {
|
||||
val trimmed = line.trim()
|
||||
if (trimmed.isEmpty() || trimmed.startsWith("```") || trimmed.startsWith("~~~")) {
|
||||
return emptyList()
|
||||
}
|
||||
val starts = mediaMarkerPrefixRegex.findAll(trimmed).map { it.range.first }.toList()
|
||||
if (starts.isEmpty()) return emptyList()
|
||||
val prefix = trimmed.substring(0, starts.first())
|
||||
if (prefix.any { !it.isWhitespace() && it !in "`*_~" }) return emptyList()
|
||||
|
||||
val hits = ArrayList<MediaMarkerHit>(starts.size)
|
||||
for ((index, start) in starts.withIndex()) {
|
||||
val payloadStart = start + "MEDIA:".length
|
||||
val payloadEnd = starts.getOrNull(index + 1) ?: trimmed.length
|
||||
val payload = trimmed.substring(payloadStart, payloadEnd)
|
||||
.trim()
|
||||
.trimEnd { it in "`*_~.,;:)}]" }
|
||||
.trim()
|
||||
if (payload.isEmpty()) return emptyList()
|
||||
val relay = mediaRelayPayloadRegex.matchEntire(payload)
|
||||
when {
|
||||
relay != null -> hits += MediaMarkerHit.RelayToken(relay.groupValues[1])
|
||||
payload.startsWith("/") || windowsAbsoluteMediaPathRegex.matches(payload) ->
|
||||
hits += MediaMarkerHit.BarePath(payload)
|
||||
else -> return emptyList()
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
private fun fenceDelimiter(line: String): String? {
|
||||
val trimmed = line.trimStart()
|
||||
return when {
|
||||
trimmed.startsWith("```") -> "```"
|
||||
trimmed.startsWith("~~~") -> "~~~"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan loaded (non-streaming) message content line-by-line for media
|
||||
* markers, append hits to [out], and return the content with matched
|
||||
@@ -1800,24 +1870,20 @@ class ChatHandler {
|
||||
out: MutableList<Pair<String, MediaMarkerHit>>,
|
||||
): String {
|
||||
var cleaned = content
|
||||
var openFence: String? = null
|
||||
for (rawLine in content.lines()) {
|
||||
val trimmed = rawLine.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
|
||||
val relayMatch = mediaRelayRegex.find(trimmed)
|
||||
if (relayMatch != null) {
|
||||
out.add(messageId to MediaMarkerHit.RelayToken(relayMatch.groupValues[1]))
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
.replace("\n$rawLine", "")
|
||||
.replace("$rawLine\n", "")
|
||||
.replace(rawLine, "")
|
||||
val delimiter = fenceDelimiter(rawLine)
|
||||
if (delimiter != null) {
|
||||
openFence = if (openFence == delimiter) null else if (openFence == null) delimiter else openFence
|
||||
continue
|
||||
}
|
||||
if (openFence != null) continue
|
||||
|
||||
val bareMatch = mediaBarePathRegex.find(trimmed)
|
||||
if (bareMatch != null) {
|
||||
out.add(messageId to MediaMarkerHit.BarePath(bareMatch.groupValues[1]))
|
||||
val hits = parseMediaMarkerLine(trimmed)
|
||||
if (hits.isNotEmpty()) {
|
||||
hits.forEach { out.add(messageId to it) }
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
.replace("\n$rawLine", "")
|
||||
@@ -1995,6 +2061,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
|
||||
@@ -2265,6 +2338,18 @@ class ChatHandler {
|
||||
val trimmed = line.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
|
||||
fenceDelimiter(line)?.let { delimiter ->
|
||||
mediaFenceDelimiter = if (mediaFenceDelimiter == delimiter) {
|
||||
null
|
||||
} else if (mediaFenceDelimiter == null) {
|
||||
delimiter
|
||||
} else {
|
||||
mediaFenceDelimiter
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (mediaFenceDelimiter != null) continue
|
||||
|
||||
if (tryDispatchMediaMarker(messageId, trimmed)) {
|
||||
stripLineFromContent(messageId, trimmed)
|
||||
}
|
||||
@@ -2394,29 +2479,26 @@ class ChatHandler {
|
||||
* Returns true when a marker was matched so the caller can strip the line.
|
||||
*/
|
||||
private fun tryDispatchMediaMarker(messageId: String, line: String): Boolean {
|
||||
val relayMatch = mediaRelayRegex.find(line)
|
||||
if (relayMatch != null) {
|
||||
val token = relayMatch.groupValues[1]
|
||||
val dedupeKey = "$messageId:relay:$token"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (relay): token=$token")
|
||||
onMediaAttachmentRequested(messageId, token)
|
||||
val hits = parseMediaMarkerLine(line)
|
||||
for (hit in hits) {
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (relay): token=${hit.token}")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
val bareMatch = mediaBarePathRegex.find(line)
|
||||
if (bareMatch != null) {
|
||||
val path = bareMatch.groupValues[1]
|
||||
val dedupeKey = "$messageId:bare:$path"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path, unavailable): $path")
|
||||
onMediaBarePathRequested(messageId, path)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
return hits.isNotEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2555,10 +2637,11 @@ class ChatHandler {
|
||||
if (mediaLineBuffer.isNotEmpty()) {
|
||||
val remaining = mediaLineBuffer.toString().trim()
|
||||
mediaLineBuffer.clear()
|
||||
if (remaining.isNotEmpty() && tryDispatchMediaMarker(messageId, remaining)) {
|
||||
if (mediaFenceDelimiter == null && remaining.isNotEmpty() && tryDispatchMediaMarker(messageId, remaining)) {
|
||||
stripLineFromContent(messageId, remaining)
|
||||
}
|
||||
}
|
||||
mediaFenceDelimiter = null
|
||||
|
||||
// Post-stream reconciliation: re-scan the final content for markers
|
||||
// that raced with stripLineFromContent during streaming.
|
||||
@@ -2567,12 +2650,16 @@ class ChatHandler {
|
||||
if (!msg.matchesIdentity(messageId) || msg.role != MessageRole.ASSISTANT) return@map msg
|
||||
var cleaned = msg.content
|
||||
var changed = false
|
||||
var openFence: String? = null
|
||||
for (rawLine in msg.content.lines()) {
|
||||
val trimmed = rawLine.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
if (mediaRelayRegex.containsMatchIn(trimmed) ||
|
||||
mediaBarePathRegex.containsMatchIn(trimmed)
|
||||
) {
|
||||
val delimiter = fenceDelimiter(rawLine)
|
||||
if (delimiter != null) {
|
||||
openFence = if (openFence == delimiter) null else if (openFence == null) delimiter else openFence
|
||||
continue
|
||||
}
|
||||
if (openFence == null && parseMediaMarkerLine(trimmed).isNotEmpty()) {
|
||||
tryDispatchMediaMarker(messageId, trimmed)
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
@@ -2903,6 +2990,7 @@ class ChatHandler {
|
||||
* [onStreamComplete] / [clearMessages].
|
||||
*/
|
||||
private val subagentLabels = mutableMapOf<Int, String>()
|
||||
private val subagentIds = mutableMapOf<Int, String>()
|
||||
|
||||
/**
|
||||
* Apply one gateway `subagent.*` lifecycle event to the streaming
|
||||
@@ -2918,6 +3006,9 @@ class ChatHandler {
|
||||
when (event.phase) {
|
||||
GatewaySubagentEvent.Phase.START -> {
|
||||
if (label != null) subagentLabels[event.taskIndex] = label
|
||||
event.subagentId?.takeIf(String::isNotBlank)?.let {
|
||||
subagentIds[event.taskIndex] = it
|
||||
}
|
||||
}
|
||||
|
||||
GatewaySubagentEvent.Phase.TOOL -> {
|
||||
@@ -2932,6 +3023,8 @@ class ChatHandler {
|
||||
isComplete = false,
|
||||
taskIndex = event.taskIndex,
|
||||
taskLabel = laneLabel,
|
||||
subagentId = event.subagentId?.takeIf(String::isNotBlank)
|
||||
?: subagentIds[event.taskIndex],
|
||||
)
|
||||
_messages.update { messages ->
|
||||
val target = messages.findLast {
|
||||
@@ -2971,6 +3064,7 @@ class ChatHandler {
|
||||
// "interrupted" lanes never finished — not a success either.
|
||||
val failed = event.status == "failed" || event.status == "interrupted"
|
||||
val laneLabel = subagentLabels.remove(event.taskIndex) ?: label
|
||||
val subagentId = subagentIds.remove(event.taskIndex) ?: event.subagentId
|
||||
val summaryId = "subagent-${event.taskIndex}-${syntheticToolSeq++}"
|
||||
_messages.update { messages ->
|
||||
messages.map { msg ->
|
||||
@@ -3003,6 +3097,7 @@ class ChatHandler {
|
||||
completedAt = System.currentTimeMillis(),
|
||||
taskIndex = event.taskIndex,
|
||||
taskLabel = laneLabel,
|
||||
subagentId = subagentId,
|
||||
)
|
||||
}
|
||||
msg.copy(toolCalls = withSummary)
|
||||
@@ -3260,6 +3355,7 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
fun onStreamError(message: String) {
|
||||
@@ -3289,6 +3385,7 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
subagentLabels.clear()
|
||||
subagentIds.clear()
|
||||
}
|
||||
|
||||
fun onThinkingDelta(messageId: String, delta: String) {
|
||||
|
||||
+473
-10
@@ -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
|
||||
@@ -500,6 +596,7 @@ class DashboardApiClient(
|
||||
name: String,
|
||||
cloneFromDefault: Boolean = true,
|
||||
description: String? = null,
|
||||
mcpServers: List<String> = emptyList(),
|
||||
): Result<JsonObject> =
|
||||
postJsonObject(
|
||||
path = "/api/profiles",
|
||||
@@ -507,9 +604,167 @@ class DashboardApiClient(
|
||||
put("name", name)
|
||||
put("clone_from_default", cloneFromDefault)
|
||||
if (!description.isNullOrBlank()) put("description", description)
|
||||
if (mcpServers.isNotEmpty()) {
|
||||
put("mcp_servers", JsonArray(mcpServers.map(::JsonPrimitive)))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/** Create a host-owned Hermes backup, distinct from Android settings export. */
|
||||
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",
|
||||
@@ -605,15 +860,16 @@ class DashboardApiClient(
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getCustomEndpoints(): Result<DashboardCustomEndpoints> =
|
||||
getJsonObject("/api/providers/custom-endpoints")
|
||||
suspend fun getCustomEndpoints(profile: String? = null): Result<DashboardCustomEndpoints> =
|
||||
getJsonObject("/api/providers/custom-endpoints${profileQuery(profile)}")
|
||||
.mapCatching(::parseCustomEndpoints)
|
||||
|
||||
suspend fun saveCustomEndpoint(
|
||||
draft: DashboardCustomEndpointDraft,
|
||||
profile: String? = null,
|
||||
): Result<DashboardCustomEndpoints> =
|
||||
postJsonObject(
|
||||
"/api/providers/custom-endpoints",
|
||||
"/api/providers/custom-endpoints${profileQuery(profile)}",
|
||||
customEndpointPayload(draft),
|
||||
).mapCatching(::parseCustomEndpoints)
|
||||
|
||||
@@ -634,13 +890,19 @@ class DashboardApiClient(
|
||||
|
||||
suspend fun activateCustomEndpoint(
|
||||
id: String,
|
||||
profile: String? = null,
|
||||
): Result<JsonObject> =
|
||||
postJsonObject("/api/providers/custom-endpoints/${pathSegment(id)}/activate")
|
||||
postJsonObject(
|
||||
"/api/providers/custom-endpoints/${pathSegment(id)}/activate${profileQuery(profile)}",
|
||||
)
|
||||
|
||||
suspend fun deleteCustomEndpoint(
|
||||
id: String,
|
||||
profile: String? = null,
|
||||
): Result<DashboardCustomEndpoints> =
|
||||
deleteJsonObject("/api/providers/custom-endpoints/${pathSegment(id)}")
|
||||
deleteJsonObject(
|
||||
"/api/providers/custom-endpoints/${pathSegment(id)}${profileQuery(profile)}",
|
||||
)
|
||||
.mapCatching(::parseCustomEndpoints)
|
||||
|
||||
suspend fun installMcpCatalogEntry(
|
||||
@@ -749,9 +1011,157 @@ 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,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the bounded, authoritative session window across every profile.
|
||||
* Every usable row must retain its owning profile; rows without one are
|
||||
* skipped rather than risking a cross-profile transcript or mutation.
|
||||
*/
|
||||
suspend fun listAllProfileSessions(
|
||||
limit: Int = SESSION_LIST_WINDOW_LIMIT,
|
||||
): Result<List<SessionItem>> = withContext(Dispatchers.IO) {
|
||||
val boundedLimit = limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)
|
||||
val result = getJson(
|
||||
"/api/profiles/sessions?limit=$boundedLimit&offset=0&order=recent" +
|
||||
"&min_messages=1&archived=include&profile=all",
|
||||
).mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(SessionListResponse.serializer(), root)
|
||||
(parsed.sessions ?: parsed.items ?: parsed.data ?: emptyList())
|
||||
.filter { it.id.isNotBlank() && !it.profile.isNullOrBlank() }
|
||||
.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]:
|
||||
@@ -763,12 +1173,24 @@ class DashboardApiClient(
|
||||
suspend fun getSessionMessages(
|
||||
sessionId: String,
|
||||
profile: String? = null,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
||||
val name = profile?.trim().orEmpty()
|
||||
val query = if (name.isNotBlank()) "?profile=${pathSegment(name)}" else ""
|
||||
getJson("/api/sessions/${pathSegment(sessionId)}/messages$query").mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(MessageListResponse.serializer(), root)
|
||||
parsed.messages ?: parsed.data ?: parsed.items ?: emptyList()
|
||||
loadSessionMessages(mode) { page ->
|
||||
val query = buildList {
|
||||
add("limit=${page.limit}")
|
||||
add("offset=${page.offset}")
|
||||
add("order=${page.order}")
|
||||
if (name.isNotBlank()) add("profile=${pathSegment(name)}")
|
||||
}.joinToString(prefix = "?", separator = "&")
|
||||
getJson("/api/sessions/${pathSegment(sessionId)}/messages$query").mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(MessageListResponse.serializer(), root)
|
||||
SessionMessagePage(
|
||||
messages = parsed.messages ?: parsed.data ?: parsed.items ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = root.toString().length,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1062,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")
|
||||
@@ -1121,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()
|
||||
|
||||
+286
-12
@@ -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
|
||||
@@ -18,10 +26,12 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import com.hermesandroid.relay.network.shared.fullJitterDelayMs
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
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
|
||||
@@ -86,9 +96,13 @@ class GatewayChatClient(
|
||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
|
||||
) {
|
||||
/** 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"
|
||||
|
||||
@@ -509,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
|
||||
@@ -526,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))
|
||||
@@ -548,21 +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)
|
||||
truncateBeforeUserOrdinal?.let { put("truncate_before_user_ordinal", it) }
|
||||
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
|
||||
@@ -588,7 +629,7 @@ class GatewayChatClient(
|
||||
if (activeTurn === turn) activeTurn = null
|
||||
turn.disarmWatchdog()
|
||||
val submitError = submitted.exceptionOrNull()
|
||||
if ((submitError as? GatewayRpcException)?.code == ACTIVE_SESSION_CAP_REJECTION) {
|
||||
if (submitError.isAuthoritativePromptSubmitRejection()) {
|
||||
// Authoritative policy rejection: the gateway received
|
||||
// the prompt and deliberately refused to create the
|
||||
// first turn. Falling back to SSE would bypass the cap
|
||||
@@ -597,7 +638,7 @@ class GatewayChatClient(
|
||||
// through the normal failed-turn callback instead.
|
||||
turn.tracer.done("submit-rejected")
|
||||
turn.callbacks.onError(
|
||||
submitError.message ?: "Hermes rejected the new session",
|
||||
submitError?.message ?: "Hermes rejected the new session",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
@@ -605,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) {
|
||||
@@ -1099,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,
|
||||
@@ -1220,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.
|
||||
*
|
||||
@@ -1482,6 +1656,43 @@ class GatewayChatClient(
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* React to the newest message for a role without guessing a transcript row
|
||||
* 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> {
|
||||
require(role == "user" || role == "assistant") { "unsupported reaction role" }
|
||||
val sid = liveSessionId
|
||||
?: return Result.failure(GatewayRpcException("no live session"))
|
||||
return rpc(
|
||||
"message.react",
|
||||
buildJsonObject {
|
||||
put("session_id", sid)
|
||||
put("newest_role", role)
|
||||
if (emoji == null) put("emoji", JsonNull) else put("emoji", emoji)
|
||||
put("author", "user")
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** Redirect one running child agent without interrupting the parent turn. */
|
||||
suspend fun steerSubagent(subagentId: String, text: String): Result<JsonObject> {
|
||||
val sessionId = liveSessionId
|
||||
?: return Result.failure(IllegalStateException("No live gateway session"))
|
||||
if (subagentId.isBlank() || text.isBlank()) {
|
||||
return Result.failure(IllegalArgumentException("Subagent and instruction are required"))
|
||||
}
|
||||
return rpc(
|
||||
"subagent.steer",
|
||||
buildJsonObject {
|
||||
put("session_id", sessionId)
|
||||
put("subagent_id", subagentId)
|
||||
put("text", text.trim())
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** Fetch the session/global reasoning effort and display mode. */
|
||||
suspend fun getReasoningSettings(): Result<GatewayReasoningSettings> {
|
||||
if (webSocket == null || readySignal?.isCompleted != true) {
|
||||
@@ -1948,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
|
||||
@@ -2090,6 +2307,42 @@ class GatewayChatClient(
|
||||
return
|
||||
}
|
||||
|
||||
// Upstream emits session.reclaimed process-wide, so it is identified
|
||||
// by payload rather than params.session_id. Retire only an exact live
|
||||
// runtime we own; preserve the durable id so the next send resumes it.
|
||||
if (type == "session.reclaimed") {
|
||||
val reclaimedLiveId = payload?.stringField("session_id")
|
||||
val reclaimedStoredId = payload?.stringField("stored_session_id")
|
||||
val reason = payload?.stringField("reason")
|
||||
val supportedReason = reason in setOf("idle_timeout", "lru_evict", "ws_orphan_reap")
|
||||
if (!reclaimedLiveId.isNullOrBlank() && supportedReason) {
|
||||
val background = backgroundTurns.remove(reclaimedLiveId)
|
||||
if (background != null) {
|
||||
callbackDispatcher {
|
||||
unmatchedTurnCompleteListener?.invoke(
|
||||
GatewayBackgroundTurnCompletion(
|
||||
storedSessionId = reclaimedStoredId?.takeIf(String::isNotBlank)
|
||||
?: background.storedSessionId,
|
||||
liveSessionId = reclaimedLiveId,
|
||||
profile = background.profile,
|
||||
expectedAssistantText = null,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (reclaimedLiveId == liveSessionId) {
|
||||
liveSessionId = null
|
||||
reclaimedStoredId?.takeIf(String::isNotBlank)?.let { storedSessionId = it }
|
||||
val turn = activeTurn
|
||||
if (turn != null && !turn.ended) {
|
||||
activeTurn = null
|
||||
turn.failFromTransport("Gateway reclaimed the inactive session")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// read_terminal is a renderer query, not a user decision. Android has
|
||||
// no xterm pane on the Gateway chat surface, so mirror upstream
|
||||
// desktop's no-live-pane behavior and answer with empty text instead
|
||||
@@ -2408,7 +2661,7 @@ class GatewayChatClient(
|
||||
Log.i(TAG, "Gateway socket rejoined for ${backgroundTurns.size} detached turn(s)")
|
||||
return
|
||||
}
|
||||
delay(backoffMs)
|
||||
delay(fullJitterDelayMs(backoffMs, reconnectJitterUnit()))
|
||||
backoffMs = (backoffMs * 2).coerceAtMost(5_000L)
|
||||
}
|
||||
}
|
||||
@@ -2501,7 +2754,7 @@ class GatewayChatClient(
|
||||
)
|
||||
return
|
||||
}
|
||||
delay(backoffMs)
|
||||
delay(fullJitterDelayMs(backoffMs, reconnectJitterUnit()))
|
||||
backoffMs = (backoffMs * 2).coerceAtMost(5_000L)
|
||||
}
|
||||
if (activeTurn === turn) activeTurn = null
|
||||
@@ -2602,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
|
||||
@@ -3080,11 +3338,24 @@ 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 const val ACTIVE_SESSION_CAP_REJECTION = 4090
|
||||
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
|
||||
)
|
||||
private const val MAX_RECOVERED_CORRECTIONS = 32
|
||||
private const val MAX_RECOVERED_CORRECTION_CHARS = 32_768
|
||||
private const val PET_THUMB_DATA_PREFIX = "data:image/png;base64,"
|
||||
@@ -3140,6 +3411,9 @@ private fun Throwable?.isMethodNotFound(): Boolean {
|
||||
msg.contains("unknown method", ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun Throwable?.isAuthoritativePromptSubmitRejection(): Boolean =
|
||||
(this as? GatewayRpcException)?.code in AUTHORITATIVE_PROMPT_SUBMIT_REJECTIONS
|
||||
|
||||
private fun Throwable?.isApprovalModeUnsupported(): Boolean {
|
||||
val rpcError = this as? GatewayRpcException ?: return false
|
||||
val message = rpcError.message.orEmpty()
|
||||
|
||||
+35
-13
@@ -207,7 +207,11 @@ class GatewayEventMapper(
|
||||
}
|
||||
else -> syntheticToolId(name)
|
||||
}
|
||||
val argsPreview = payload.string("args_text")
|
||||
val argsPreview = payload?.get("args")
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
?: payload.string("args_text")
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: payload.string("context")?.takeIf { it.isNotBlank() }
|
||||
callbacks.onToolCallStart(toolId, name, argsPreview)
|
||||
@@ -294,6 +298,7 @@ class GatewayEventMapper(
|
||||
// text; thinking/progress carry text only.
|
||||
preview = payload.string("tool_preview") ?: payload.string("text"),
|
||||
durationSeconds = payload.double("duration_seconds"),
|
||||
subagentId = payload.string("subagent_id"),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -439,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,
|
||||
@@ -556,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
|
||||
|
||||
@@ -578,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,
|
||||
) {
|
||||
@@ -270,6 +272,7 @@ data class GatewaySubagentEvent(
|
||||
val toolName: String? = null,
|
||||
val preview: String? = null,
|
||||
val durationSeconds: Double? = null,
|
||||
val subagentId: String? = null,
|
||||
) {
|
||||
enum class Phase { START, THINKING, TOOL, PROGRESS, COMPLETE }
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import com.hermesandroid.relay.network.upstream.models.SkillListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
import com.hermesandroid.relay.util.TurnLatencyTracer
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.Serializable
|
||||
@@ -431,6 +432,7 @@ private class RetryingEventSource(
|
||||
class HermesApiClient(
|
||||
baseUrl: String,
|
||||
private val apiKey: String,
|
||||
httpClient: OkHttpClient? = null,
|
||||
private val json: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
@@ -478,7 +480,7 @@ class HermesApiClient(
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private val client: OkHttpClient = OkHttpClient.Builder()
|
||||
private val client: OkHttpClient = httpClient ?: OkHttpClient.Builder()
|
||||
.readTimeout(5, TimeUnit.MINUTES)
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
@@ -713,19 +715,34 @@ class HermesApiClient(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getMessages(sessionId: String): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val request = authRequest("$baseUrl/api/sessions/$sessionId/messages")
|
||||
.get()
|
||||
.build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return@withContext emptyList()
|
||||
val body = response.body?.string() ?: return@withContext emptyList()
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
parsed.data ?: parsed.items ?: parsed.messages ?: emptyList()
|
||||
suspend fun getMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
loadSessionMessages(mode) { page ->
|
||||
runCatching {
|
||||
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("limit", page.limit.toString())
|
||||
?.addQueryParameter("offset", page.offset.toString())
|
||||
?.addQueryParameter("order", page.order)
|
||||
?.build()
|
||||
?: error("invalid session messages URL")
|
||||
val request = authRequest(url.toString()).get().build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) error("HTTP ${response.code}")
|
||||
val body = response.body?.string() ?: error("empty response body")
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
SessionMessagePage(
|
||||
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = body.length,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to get messages: ${e.message}")
|
||||
}.getOrElse { error ->
|
||||
if (error is CancellationException) throw error
|
||||
Log.w(TAG, "Failed to get messages: ${error.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessagePagination
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** Explicit transcript read intent for Hermes' bounded messages endpoint. */
|
||||
enum class SessionMessageLoadMode {
|
||||
/** One bounded newest-first window, returned in chronological order. */
|
||||
LATEST,
|
||||
|
||||
/** Every page, oldest first, subject to Android memory safety bounds. */
|
||||
COMPLETE,
|
||||
}
|
||||
|
||||
internal const val SESSION_MESSAGE_PAGE_SIZE = 500
|
||||
private const val MAX_COMPLETE_TRANSCRIPT_MESSAGES = 50_000
|
||||
private const val MAX_COMPLETE_TRANSCRIPT_PAYLOAD_CHARS = 32_000_000
|
||||
|
||||
internal data class SessionMessagePageRequest(
|
||||
val limit: Int = SESSION_MESSAGE_PAGE_SIZE,
|
||||
val offset: Int = 0,
|
||||
val order: String,
|
||||
)
|
||||
|
||||
internal data class SessionMessagePage(
|
||||
val messages: List<MessageItem>,
|
||||
val pagination: MessagePagination?,
|
||||
val payloadChars: Int,
|
||||
)
|
||||
|
||||
internal class SessionTranscriptTooLargeException(message: String) : IllegalStateException(message)
|
||||
|
||||
/** Shared API-server/dashboard pagination contract. Legacy unpaginated envelopes remain valid. */
|
||||
internal suspend fun loadSessionMessages(
|
||||
mode: SessionMessageLoadMode,
|
||||
fetchPage: suspend (SessionMessagePageRequest) -> Result<SessionMessagePage>,
|
||||
): Result<List<MessageItem>> {
|
||||
return try {
|
||||
val order = if (mode == SessionMessageLoadMode.LATEST) "latest" else "oldest"
|
||||
val collected = ArrayList<MessageItem>()
|
||||
var offset = 0
|
||||
var payloadChars = 0L
|
||||
|
||||
while (true) {
|
||||
val request = SessionMessagePageRequest(offset = offset, order = order)
|
||||
val page = fetchPage(request).getOrThrow()
|
||||
payloadChars += page.payloadChars
|
||||
if (payloadChars > MAX_COMPLETE_TRANSCRIPT_PAYLOAD_CHARS) {
|
||||
throw SessionTranscriptTooLargeException(
|
||||
"Session transcript exceeds Android's 32 MB safe-load limit",
|
||||
)
|
||||
}
|
||||
if (collected.size + page.messages.size > MAX_COMPLETE_TRANSCRIPT_MESSAGES) {
|
||||
throw SessionTranscriptTooLargeException(
|
||||
"Session transcript exceeds Android's 50,000-message safe-load limit",
|
||||
)
|
||||
}
|
||||
collected += page.messages
|
||||
|
||||
if (mode == SessionMessageLoadMode.LATEST) break
|
||||
// Older Hermes returned one unpaginated complete envelope. Never issue
|
||||
// a speculative second request against that contract.
|
||||
val pagination = page.pagination ?: break
|
||||
val returned = pagination.returned ?: page.messages.size
|
||||
if (page.messages.isEmpty() || returned < request.limit || page.messages.size < request.limit) break
|
||||
|
||||
val nextOffset = offset + page.messages.size
|
||||
if (nextOffset <= offset) break
|
||||
offset = nextOffset
|
||||
}
|
||||
Result.success(collected)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
+64
-1
@@ -16,6 +16,7 @@ import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.Instant
|
||||
|
||||
/**
|
||||
@@ -76,6 +77,26 @@ 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()
|
||||
}
|
||||
}
|
||||
|
||||
/** Timestamp serializer for Hermes session metadata.
|
||||
*
|
||||
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
|
||||
@@ -142,6 +163,8 @@ data class SessionItem(
|
||||
val preview: String? = null,
|
||||
val model: String? = null,
|
||||
val source: String? = null,
|
||||
/** Owning profile on the cross-profile `/api/profiles/sessions` endpoint. */
|
||||
val profile: String? = null,
|
||||
@SerialName("started_at")
|
||||
@Serializable(with = FlexibleTimestampSerializer::class)
|
||||
val startedAt: Double? = null,
|
||||
@@ -168,11 +191,39 @@ data class SessionItem(
|
||||
/** Durable flags returned by current Dashboard and API-server session resources. */
|
||||
val pinned: Boolean = false,
|
||||
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,
|
||||
@@ -244,7 +295,16 @@ data class MessageListResponse(
|
||||
val items: List<MessageItem>? = null,
|
||||
val messages: List<MessageItem>? = null, // alternate key
|
||||
val data: List<MessageItem>? = null, // upstream /api/sessions/{id}/messages list envelope
|
||||
val total: Int? = null
|
||||
val total: Int? = null,
|
||||
val pagination: MessagePagination? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessagePagination(
|
||||
val limit: Int? = null,
|
||||
val offset: Int? = null,
|
||||
val order: String? = null,
|
||||
val returned: Int? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -254,6 +314,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,
|
||||
|
||||
+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,7 @@ internal class HermesRuntimeBinder(
|
||||
chat.setDisplayProfileProvider { connection.effectiveDisplayProfile.value }
|
||||
chat.setDisplayAliasProvider { connection.profileDisplayAlias.value }
|
||||
chat.setProfileSessionLister { connection.listProfileScopedSessions() }
|
||||
chat.setProfileMessageLoader(connection::loadProfileScopedMessages)
|
||||
chat.setProfileMessageLoaderWithMode(connection::loadProfileScopedMessages)
|
||||
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 —
|
||||
|
||||
@@ -64,6 +64,10 @@ data class SlashCommand(
|
||||
* instead of plain text.
|
||||
*/
|
||||
val source: String? = null,
|
||||
/** Bounded server-recorded skill usage; zero for non-skill commands. */
|
||||
val usageRank: Int = 0,
|
||||
/** Sanitized server skill origin such as local or bundled. */
|
||||
val origin: String? = null,
|
||||
) {
|
||||
companion object {
|
||||
const val SOURCE_SERVER = "server"
|
||||
|
||||
@@ -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 -> {
|
||||
|
||||
@@ -46,6 +46,7 @@ import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -113,6 +114,10 @@ fun MessageBubble(
|
||||
onQuoteMessage: ((ChatMessage) -> Unit)? = null,
|
||||
/** Navigate a rendered quote chip to its original message id. */
|
||||
onNavigateToMessage: ((String) -> Unit)? = null,
|
||||
/** Open an upstream @session:<profile>/<id> reference in app. */
|
||||
onSessionReference: ((SessionReference) -> Unit)? = null,
|
||||
/** React to the newest message for this role; null removes the reaction. */
|
||||
onReact: ((String?) -> Unit)? = null,
|
||||
/**
|
||||
* Reads a completed assistant response through the active voice renderer.
|
||||
* Null hides the entry; the owning screen uses that to limit the action to
|
||||
@@ -170,6 +175,7 @@ fun MessageBubble(
|
||||
) {
|
||||
val isUser = message.role == MessageRole.USER
|
||||
val isSystem = message.role == MessageRole.SYSTEM
|
||||
val sessionReferences = remember(message.content) { parseSessionReferences(message.content) }
|
||||
|
||||
// Phone/voice-origin action bubble marker.
|
||||
//
|
||||
@@ -449,7 +455,7 @@ fun MessageBubble(
|
||||
val showEditAction = onEditMessage != null && isUser
|
||||
val showSpeakAction = shouldShowSpeakResponseAction(message, onSpeakMessage != null)
|
||||
val showStopSpeakingAction = shouldShowStopSpeakingAction(message, onStopSpeaking != null)
|
||||
if (onQuoteMessage != null || showEditAction || showSpeakAction || showStopSpeakingAction) {
|
||||
if (onQuoteMessage != null || onReact != null || showEditAction || showSpeakAction || showStopSpeakingAction) {
|
||||
DropdownMenu(
|
||||
expanded = showMessageActions,
|
||||
onDismissRequest = { showMessageActions = false },
|
||||
@@ -639,6 +645,35 @@ 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(
|
||||
onClick = { onSessionReference(reference) },
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
) {
|
||||
Text("Open ${reference.label}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inline generated images (assistant only) — rendered OUTSIDE
|
||||
// the SelectionContainer (they're not selectable text). Remote
|
||||
|
||||
@@ -99,6 +99,39 @@ internal enum class SessionDrawerFilter {
|
||||
internal const val SESSION_DRAWER_LIST_TAG = "session-drawer-list"
|
||||
internal const val UNPINNED_STAR_ALPHA = 0.45f
|
||||
|
||||
data class ProfileSessionRow(
|
||||
val profile: String,
|
||||
val session: ChatSession,
|
||||
)
|
||||
|
||||
data class ProvisionalThreadRow(
|
||||
val chatId: String,
|
||||
val title: String,
|
||||
val messageCount: Int,
|
||||
val lastActivityAt: Long,
|
||||
)
|
||||
|
||||
private const val PROVISIONAL_THREAD_PREFIX = "proactive:"
|
||||
|
||||
internal fun sessionWorkLabels(session: ChatSession): List<String> = buildList {
|
||||
val repo = (session.gitRepoRoot ?: session.workingDirectory)
|
||||
?.trimEnd('/', '\\')
|
||||
?.substringAfterLast('/')
|
||||
?.substringAfterLast('\\')
|
||||
?.takeIf { it.isNotBlank() }
|
||||
repo?.let(::add)
|
||||
session.gitBranch?.trim()?.takeIf { it.isNotBlank() }?.let(::add)
|
||||
session.pullRequestNumber?.takeIf { it > 0 }?.let { number ->
|
||||
val status = when {
|
||||
session.pullRequestDraft -> "Draft"
|
||||
!session.pullRequestState.isNullOrBlank() ->
|
||||
session.pullRequestState.lowercase().replaceFirstChar { it.uppercaseChar() }
|
||||
else -> null
|
||||
}
|
||||
add(listOfNotNull("PR #$number", status).joinToString(" · "))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun sessionPinIcon(pinned: Boolean) =
|
||||
if (pinned) Icons.Filled.Star else Icons.Outlined.StarBorder
|
||||
|
||||
@@ -145,10 +178,16 @@ fun SessionDrawerContent(
|
||||
* filter view. The first message the user types opens the conversation.
|
||||
*/
|
||||
onNewThread: ((String) -> Unit)? = null,
|
||||
provisionalThreads: List<ProvisionalThreadRow> = emptyList(),
|
||||
onSelectProvisionalThread: ((String) -> Unit)? = null,
|
||||
/** Gateway sources currently hidden from the drawer (default: cron+webhook). */
|
||||
hiddenSources: Set<String> = emptySet(),
|
||||
/** Toggle a source's visibility (persisted). Null hides the source filter. */
|
||||
onToggleSourceHidden: ((String, Boolean) -> Unit)? = null,
|
||||
allProfileSessions: List<ProfileSessionRow> = emptyList(),
|
||||
allProfileSessionsLoading: Boolean = false,
|
||||
onRefreshAllProfiles: (() -> Unit)? = null,
|
||||
onSelectProfileSession: ((String, String) -> Unit)? = null,
|
||||
) {
|
||||
var renameDialogSession by remember { mutableStateOf<ChatSession?>(null) }
|
||||
var newThreadDialog by remember { mutableStateOf(false) }
|
||||
@@ -157,12 +196,26 @@ fun SessionDrawerContent(
|
||||
var query by remember { mutableStateOf("") }
|
||||
var searchExpanded by remember { mutableStateOf(false) }
|
||||
var filter by remember { mutableStateOf(SessionDrawerFilter.All) }
|
||||
var allProfilesOpen by remember { mutableStateOf(false) }
|
||||
val listState = rememberLazyListState()
|
||||
val trimmedQuery = query.trim()
|
||||
// Threads affordance shows when the capability is active OR there's already at least one
|
||||
// agent Thread (source=phone) in the list. If the filter is on Threads but they've
|
||||
// vanished, fall back to All so the drawer never gets stuck on an empty hidden filter.
|
||||
val showThreads = threadsCapabilityActive || sessions.any { isThreadSource(it.source) }
|
||||
val provisionalSessions = provisionalThreads.map { thread ->
|
||||
ChatSession(
|
||||
sessionId = "$PROVISIONAL_THREAD_PREFIX${thread.chatId}",
|
||||
title = thread.title,
|
||||
model = null,
|
||||
messageCount = thread.messageCount,
|
||||
updatedAt = thread.lastActivityAt,
|
||||
startedAt = thread.lastActivityAt,
|
||||
lastActivityAt = thread.lastActivityAt,
|
||||
source = "phone",
|
||||
)
|
||||
}
|
||||
val allSessions = sessions + provisionalSessions
|
||||
val showThreads = threadsCapabilityActive || allSessions.any { isThreadSource(it.source) }
|
||||
val activeFilter = resolveSessionDrawerFilter(filter, showThreads, archiveSupported)
|
||||
// External gateway sources present (discord/telegram/cron/…) for the source
|
||||
// filter dropdown. Own chats (tui/api_server) + phone Threads aren't listed.
|
||||
@@ -171,7 +224,7 @@ fun SessionDrawerContent(
|
||||
.distinct()
|
||||
.filter { sourceBadge(it) != null }
|
||||
.sorted()
|
||||
val visibleSessions = sessions
|
||||
val visibleSessions = allSessions
|
||||
.asSequence()
|
||||
.filter { session ->
|
||||
when (activeFilter) {
|
||||
@@ -196,7 +249,8 @@ fun SessionDrawerContent(
|
||||
needle.isBlank() ||
|
||||
session.sessionId.contains(needle, ignoreCase = true) ||
|
||||
session.title.orEmpty().contains(needle, ignoreCase = true) ||
|
||||
session.model.orEmpty().contains(needle, ignoreCase = true)
|
||||
session.model.orEmpty().contains(needle, ignoreCase = true) ||
|
||||
sessionWorkLabels(session).any { it.contains(needle, ignoreCase = true) }
|
||||
}
|
||||
.sortedWith(
|
||||
compareByDescending<ChatSession> { it.pinned }
|
||||
@@ -355,6 +409,16 @@ fun SessionDrawerContent(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (onRefreshAllProfiles != null && onSelectProfileSession != null) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
allProfilesOpen = true
|
||||
onRefreshAllProfiles()
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.drawer_all_profiles))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
@@ -489,7 +553,7 @@ fun SessionDrawerContent(
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = if (sessions.isEmpty()) stringResource(R.string.drawer_no_sessions) else stringResource(R.string.drawer_no_matching_sessions),
|
||||
text = if (allSessions.isEmpty()) stringResource(R.string.drawer_no_sessions) else stringResource(R.string.drawer_no_matching_sessions),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -513,7 +577,16 @@ fun SessionDrawerContent(
|
||||
pinned = session.pinned,
|
||||
archived = session.archived,
|
||||
archiveSupported = archiveSupported,
|
||||
onClick = { onSelectSession(session.sessionId) },
|
||||
onClick = {
|
||||
if (session.sessionId.startsWith(PROVISIONAL_THREAD_PREFIX)) {
|
||||
onSelectProvisionalThread?.invoke(
|
||||
session.sessionId.removePrefix(PROVISIONAL_THREAD_PREFIX),
|
||||
)
|
||||
} else {
|
||||
onSelectSession(session.sessionId)
|
||||
}
|
||||
},
|
||||
actionsEnabled = !session.sessionId.startsWith(PROVISIONAL_THREAD_PREFIX),
|
||||
onTogglePinned = {
|
||||
onSetSessionPinned(session.sessionId, !session.pinned)
|
||||
},
|
||||
@@ -620,6 +693,82 @@ fun SessionDrawerContent(
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (allProfilesOpen) {
|
||||
var allQuery by remember { mutableStateOf("") }
|
||||
val needle = allQuery.trim()
|
||||
val rows = allProfileSessions.filter { row ->
|
||||
needle.isBlank() ||
|
||||
row.profile.contains(needle, ignoreCase = true) ||
|
||||
row.session.title.orEmpty().contains(needle, ignoreCase = true) ||
|
||||
row.session.sessionId.contains(needle, ignoreCase = true) ||
|
||||
sessionWorkLabels(row.session).any { it.contains(needle, ignoreCase = true) }
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = { allProfilesOpen = false },
|
||||
title = { Text(stringResource(R.string.drawer_all_profiles)) },
|
||||
text = {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
OutlinedTextField(
|
||||
value = allQuery,
|
||||
onValueChange = { allQuery = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||
placeholder = { Text(stringResource(R.string.drawer_search_placeholder)) },
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
when {
|
||||
allProfileSessionsLoading && allProfileSessions.isEmpty() ->
|
||||
CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))
|
||||
rows.isEmpty() -> Text(
|
||||
stringResource(R.string.drawer_no_profile_sessions),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
else -> LazyColumn(modifier = Modifier.height(420.dp)) {
|
||||
items(rows, key = { "${it.profile}:${it.session.sessionId}" }) { row ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
allProfilesOpen = false
|
||||
onSelectProfileSession?.invoke(row.profile, row.session.sessionId)
|
||||
}
|
||||
.padding(vertical = 10.dp, horizontal = 4.dp),
|
||||
) {
|
||||
Text(
|
||||
row.session.title?.takeIf { it.isNotBlank() }
|
||||
?: stringResource(R.string.drawer_untitled),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
row.profile,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Relay,
|
||||
)
|
||||
sessionWorkLabels(row.session).takeIf { it.isNotEmpty() }?.let { labels ->
|
||||
Text(
|
||||
labels.joinToString(" • "),
|
||||
style = relayMetadataStyle(),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { allProfilesOpen = false }) {
|
||||
Text(stringResource(R.string.drawer_close))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -632,6 +781,7 @@ private fun SessionItem(
|
||||
archived: Boolean,
|
||||
archiveSupported: Boolean,
|
||||
onClick: () -> Unit,
|
||||
actionsEnabled: Boolean = true,
|
||||
onTogglePinned: () -> Unit,
|
||||
onToggleArchived: () -> Unit,
|
||||
onRename: () -> Unit,
|
||||
@@ -685,6 +835,28 @@ private fun SessionItem(
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
}
|
||||
)
|
||||
val workLabels = sessionWorkLabels(session)
|
||||
if (workLabels.isNotEmpty()) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier
|
||||
.padding(top = 4.dp)
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
workLabels.forEach { label ->
|
||||
Text(
|
||||
text = label,
|
||||
style = relayMetadataStyle(),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant)
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -750,7 +922,7 @@ private fun SessionItem(
|
||||
}
|
||||
}
|
||||
|
||||
Box {
|
||||
if (actionsEnabled) Box {
|
||||
IconButton(
|
||||
onClick = { menuOpen = true },
|
||||
modifier = Modifier.size(36.dp),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
data class SessionReference(val profile: String, val sessionId: String) {
|
||||
val label: String
|
||||
get() = "$profile · ${sessionId.takeLast(10)}"
|
||||
}
|
||||
|
||||
private val SESSION_REFERENCE = Regex("@session:([A-Za-z0-9_.-]{1,64})/([A-Za-z0-9_.:-]{1,160})")
|
||||
|
||||
/** Find session references outside fenced and inline code. */
|
||||
internal fun parseSessionReferences(markdown: String): List<SessionReference> {
|
||||
val visible = buildString(markdown.length) {
|
||||
var fenced = false
|
||||
markdown.lineSequence().forEach { line ->
|
||||
if (line.trimStart().startsWith("```")) {
|
||||
fenced = !fenced
|
||||
appendLine()
|
||||
} else if (fenced) {
|
||||
appendLine()
|
||||
} else {
|
||||
var inline = false
|
||||
line.forEach { char ->
|
||||
if (char == '`') inline = !inline
|
||||
append(if (inline || char == '`') ' ' else char)
|
||||
}
|
||||
appendLine()
|
||||
}
|
||||
}
|
||||
}
|
||||
return SESSION_REFERENCE.findAll(visible)
|
||||
.map {
|
||||
SessionReference(
|
||||
it.groupValues[1],
|
||||
it.groupValues[2].trimEnd('.', ',', ';', '!', '?', ')', ']', '}'),
|
||||
)
|
||||
}
|
||||
.filter { it.sessionId.isNotBlank() }
|
||||
.distinct()
|
||||
.take(16)
|
||||
.toList()
|
||||
}
|
||||
@@ -25,8 +25,11 @@ import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -73,11 +76,13 @@ fun SubagentLane(
|
||||
taskIndex: Int,
|
||||
calls: List<ToolCall>,
|
||||
modifier: Modifier = Modifier,
|
||||
onSteer: ((subagentId: String, instruction: String) -> Unit)? = null,
|
||||
) {
|
||||
val anyRunning = calls.any { !it.isComplete }
|
||||
val allComplete = calls.isNotEmpty() && calls.all { it.isComplete }
|
||||
val anyFailed = calls.any { it.isComplete && it.success == false }
|
||||
val runningCount = calls.count { !it.isComplete }
|
||||
val steerableId = calls.firstNotNullOfOrNull { it.subagentId?.takeIf(String::isNotBlank) }
|
||||
|
||||
val laneLabel = calls.firstNotNullOfOrNull { call ->
|
||||
call.taskLabel?.takeIf { it.isNotBlank() }
|
||||
@@ -106,6 +111,8 @@ fun SubagentLane(
|
||||
val failureLabel = stringResource(R.string.cd_subagent_failed)
|
||||
|
||||
var expanded by remember { mutableStateOf(!allComplete) }
|
||||
var showSteerDialog by remember { mutableStateOf(false) }
|
||||
var steerText by remember { mutableStateOf("") }
|
||||
|
||||
// Auto-collapse when the last child completes — same pattern as
|
||||
// ToolProgressCard's LaunchedEffect(toolCall.isComplete).
|
||||
@@ -162,6 +169,12 @@ fun SubagentLane(
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
|
||||
if (anyRunning && steerableId != null && onSteer != null) {
|
||||
TextButton(onClick = { showSteerDialog = true }) {
|
||||
Text("Redirect")
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = statusMeta,
|
||||
style = relayMetadataStyle(),
|
||||
@@ -202,4 +215,33 @@ fun SubagentLane(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showSteerDialog && steerableId != null && onSteer != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showSteerDialog = false },
|
||||
title = { Text("Redirect subagent") },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = steerText,
|
||||
onValueChange = { steerText = it },
|
||||
label = { Text("New instruction") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val instruction = steerText.trim()
|
||||
showSteerDialog = false
|
||||
steerText = ""
|
||||
onSteer(steerableId, instruction)
|
||||
},
|
||||
enabled = steerText.isNotBlank(),
|
||||
) { Text("Redirect") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showSteerDialog = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -231,6 +232,8 @@ import com.hermesandroid.relay.ui.components.ThinkingIndicatorStyle
|
||||
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
|
||||
@@ -743,6 +746,13 @@ fun ChatScreen(
|
||||
|
||||
|
||||
val messages by chatViewModel.messages.collectAsState()
|
||||
val messageReactionsSupported by chatViewModel.messageReactionsSupported.collectAsState()
|
||||
val newestReactableMessageKeys = remember(messages) {
|
||||
setOfNotNull(
|
||||
messages.lastOrNull { it.role == MessageRole.USER }?.uiKey,
|
||||
messages.lastOrNull { it.role == MessageRole.ASSISTANT }?.uiKey,
|
||||
)
|
||||
}
|
||||
val isStreaming by chatViewModel.isStreaming.collectAsState()
|
||||
// Keep the screen on for the two "actively engaged, hands-off-keyboard"
|
||||
// cases: voice mode is a call-like continuous session (mirrors Assistant/
|
||||
@@ -1128,6 +1138,8 @@ 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(
|
||||
@@ -2056,6 +2068,22 @@ 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,
|
||||
@@ -2102,10 +2130,76 @@ 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)
|
||||
},
|
||||
allProfileSessions = allProfileSessions,
|
||||
allProfileSessionsLoading = allProfileSessionsLoading,
|
||||
onRefreshAllProfiles = {
|
||||
if (!allProfileSessionsLoading) scope.launch {
|
||||
allProfileSessionsLoading = true
|
||||
val result = connectionViewModel.listAllProfileSessions()
|
||||
result?.fold(
|
||||
onSuccess = { items ->
|
||||
allProfileSessions = items.mapNotNull { item ->
|
||||
val owner = item.profile?.takeIf { it.isNotBlank() }
|
||||
?: return@mapNotNull null
|
||||
ProfileSessionRow(
|
||||
profile = owner,
|
||||
session = com.hermesandroid.relay.data.ChatSession(
|
||||
sessionId = item.id,
|
||||
title = item.title ?: item.preview,
|
||||
model = item.model,
|
||||
messageCount = item.messageCount ?: 0,
|
||||
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,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
onFailure = { error ->
|
||||
snackbarHostState.showSnackbar(
|
||||
"Couldn't load all profiles: ${error.message ?: "unsupported"}",
|
||||
)
|
||||
},
|
||||
)
|
||||
allProfileSessionsLoading = false
|
||||
}
|
||||
},
|
||||
onSelectProfileSession = { profileName, sessionId ->
|
||||
val target = agentProfiles.firstOrNull {
|
||||
it.name.equals(profileName, ignoreCase = true)
|
||||
}
|
||||
if (target != null || profileName.equals("default", ignoreCase = true)) {
|
||||
connectionViewModel.selectProfile(target)
|
||||
chatViewModel.activateGatewayProfile(target)
|
||||
chatViewModel.switchSession(sessionId)
|
||||
scope.launch { drawerState.close() }
|
||||
} else {
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar("Profile $profileName is not available.")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
) {
|
||||
@@ -3023,6 +3117,33 @@ fun ChatScreen(
|
||||
},
|
||||
onCardAction = handleCardAction,
|
||||
onCardInput = handleCardInput,
|
||||
onSessionReference = { reference ->
|
||||
val target = agentProfiles.firstOrNull {
|
||||
it.name.equals(reference.profile, ignoreCase = true)
|
||||
}
|
||||
if (target != null) {
|
||||
connectionViewModel.selectProfile(target)
|
||||
chatViewModel.activateGatewayProfile(target)
|
||||
chatViewModel.switchSession(reference.sessionId)
|
||||
} else {
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(
|
||||
message = "Profile ${reference.profile} is not available.",
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
onReact = if (
|
||||
isGatewayTransport &&
|
||||
messageReactionsSupported &&
|
||||
!message.isStreaming &&
|
||||
message.uiKey in newestReactableMessageKeys
|
||||
) {
|
||||
{ emoji -> chatViewModel.reactToNewest(message.role, emoji) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onEditMessage = if (
|
||||
isGatewayTransport &&
|
||||
!isStreaming &&
|
||||
@@ -3156,6 +3277,7 @@ fun ChatScreen(
|
||||
SubagentLane(
|
||||
taskIndex = taskIndex,
|
||||
calls = laneGroups.getValue(taskIndex),
|
||||
onSteer = chatViewModel::steerSubagent,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4134,6 +4256,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.
|
||||
|
||||
+708
-19
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -572,6 +574,18 @@ private fun DeviceCard(
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
val deviceDetail = listOf(device.deviceModel, device.devicePlatform)
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.joinToString(" · ")
|
||||
if (deviceDetail.isNotBlank()) {
|
||||
Text(
|
||||
text = deviceDetail,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (device.deviceId.isNotBlank()) {
|
||||
Text(
|
||||
text = device.deviceId,
|
||||
@@ -927,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
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
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 +93,8 @@ 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.SESSION_MESSAGE_PAGE_SIZE
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SkillInfo
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
@@ -132,6 +135,7 @@ import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import okhttp3.sse.EventSource
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
@@ -1227,10 +1231,16 @@ class ChatViewModel : ViewModel() {
|
||||
// Pill update is the confirmation — no system bubble.
|
||||
// Surface only a server warning, ephemerally.
|
||||
warning?.let { _transientNotice.tryEmit(it) }
|
||||
gateway.modelOptions().onSuccess {
|
||||
_modelProviders.value = it.providers
|
||||
_gatewayCurrentModel.value = it.currentModel
|
||||
_gatewayCurrentProvider.value = it.currentProvider
|
||||
// Current upstream may defer the switch until the turn
|
||||
// boundary. Keep the optimistic requested identity; an
|
||||
// immediate model.options read still reports the old
|
||||
// model and would visibly snap the picker backward.
|
||||
if (!isDeferredConfigResult(result)) {
|
||||
gateway.modelOptions().onSuccess {
|
||||
_modelProviders.value = it.providers
|
||||
_gatewayCurrentModel.value = it.currentModel
|
||||
_gatewayCurrentProvider.value = it.currentProvider
|
||||
}
|
||||
}
|
||||
},
|
||||
onFailure = { e ->
|
||||
@@ -1614,6 +1624,9 @@ class ChatViewModel : ViewModel() {
|
||||
val backgroundProcessesLoading: StateFlow<Boolean> = gatewayProcessController.loading
|
||||
val stoppingProcessIds: StateFlow<Set<String>> = gatewayProcessController.stoppingProcessIds
|
||||
|
||||
private val _messageReactionsSupported = MutableStateFlow(true)
|
||||
val messageReactionsSupported: StateFlow<Boolean> = _messageReactionsSupported.asStateFlow()
|
||||
|
||||
fun refreshBackgroundProcesses() {
|
||||
gatewayProcessController.refresh()
|
||||
}
|
||||
@@ -1640,6 +1653,7 @@ class ChatViewModel : ViewModel() {
|
||||
gatewayClient = client
|
||||
if (changed) {
|
||||
resetApprovalModeState()
|
||||
_messageReactionsSupported.value = true
|
||||
gatewayProcessSource = client?.let(::GatewayChatProcessSource)
|
||||
gatewayProcessController.bind(
|
||||
newSource = gatewayProcessSource,
|
||||
@@ -2309,6 +2323,45 @@ class ChatViewModel : ViewModel() {
|
||||
private val _transientNotice = MutableSharedFlow<String>(extraBufferCapacity = 8)
|
||||
val transientNotice: SharedFlow<String> = _transientNotice.asSharedFlow()
|
||||
|
||||
fun reactToNewest(role: MessageRole, emoji: String?) {
|
||||
val gateway = gatewayClient ?: return
|
||||
if (role != MessageRole.USER && role != MessageRole.ASSISTANT) return
|
||||
viewModelScope.launch {
|
||||
gateway.reactToNewest(role.name.lowercase(), emoji).fold(
|
||||
onSuccess = {
|
||||
_transientNotice.tryEmit(if (emoji == null) "Reaction removed." else "Reaction added.")
|
||||
},
|
||||
onFailure = { error ->
|
||||
if ((error as? GatewayRpcException)?.code == -32601) {
|
||||
_messageReactionsSupported.value = false
|
||||
_transientNotice.tryEmit("Message reactions aren't supported by this gateway.")
|
||||
} else {
|
||||
_transientNotice.tryEmit("Couldn't update reaction: ${error.message ?: "unknown error"}")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun steerSubagent(subagentId: String, instruction: String) {
|
||||
val gateway = gatewayClient ?: return
|
||||
if (subagentId.isBlank() || instruction.isBlank()) return
|
||||
viewModelScope.launch {
|
||||
gateway.steerSubagent(subagentId, instruction).fold(
|
||||
onSuccess = { result ->
|
||||
val status = result.stringValue("status") ?: "queued"
|
||||
_transientNotice.tryEmit(
|
||||
if (status == "rejected") "Subagent redirect was rejected."
|
||||
else "Subagent redirect queued.",
|
||||
)
|
||||
},
|
||||
onFailure = { error ->
|
||||
_transientNotice.tryEmit("Couldn't redirect subagent: ${error.message ?: "unknown error"}")
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer prefill requests from server command dispatch
|
||||
* (`{type:"prefill"}` — e.g. `/undo`). ChatScreen collects and sets the
|
||||
@@ -2390,7 +2443,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
|
||||
@@ -2536,9 +2594,16 @@ class ChatViewModel : ViewModel() {
|
||||
* once the drawer lists a non-default profile's sessions, opening one must
|
||||
* read that profile's own DB. Returns `null` off the dashboard surface.
|
||||
*/
|
||||
private var profileMessageLoader: (suspend (String) -> Result<List<MessageItem>>?)? = null
|
||||
private var profileMessageLoader:
|
||||
(suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?)? = null
|
||||
|
||||
fun setProfileMessageLoader(loader: suspend (String) -> Result<List<MessageItem>>?) {
|
||||
profileMessageLoader = { sessionId, _ -> loader(sessionId) }
|
||||
}
|
||||
|
||||
fun setProfileMessageLoaderWithMode(
|
||||
loader: suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?,
|
||||
) {
|
||||
profileMessageLoader = loader
|
||||
}
|
||||
|
||||
@@ -2551,11 +2616,12 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadSessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> {
|
||||
if (streamingEndpoint == "gateway") {
|
||||
return loadGatewaySessionHistory(sessionId, requireProfileScope)
|
||||
return loadGatewaySessionHistory(sessionId, requireProfileScope, mode)
|
||||
}
|
||||
return apiClient?.getMessages(sessionId) ?: emptyList()
|
||||
return apiClient?.getMessages(sessionId, mode) ?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2567,15 +2633,16 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadGatewaySessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> {
|
||||
val scoped = profileMessageLoader?.invoke(sessionId)
|
||||
val scoped = profileMessageLoader?.invoke(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
|
||||
// empty/default transcript is not authoritative for this session.
|
||||
return if (requireProfileScope) scoped.getOrThrow() else scoped.getOrElse { emptyList() }
|
||||
}
|
||||
return apiClient?.getMessages(sessionId) ?: emptyList()
|
||||
return apiClient?.getMessages(sessionId, mode) ?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2866,6 +2933,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
|
||||
@@ -3164,7 +3237,7 @@ class ChatViewModel : ViewModel() {
|
||||
selectedReasoningEffortConfirmedIdentity = null
|
||||
_reasoningDisplay.value = null
|
||||
_selectedPersonality.value = "default"
|
||||
pendingTruncateOrdinal = null
|
||||
pendingGatewayTruncation = null
|
||||
chatHandler?.let { handler ->
|
||||
handler.clearMessages()
|
||||
handler.clearSessions()
|
||||
@@ -3257,7 +3330,7 @@ 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()
|
||||
@@ -3484,6 +3557,8 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
fun createNewChat() {
|
||||
val handler = chatHandler ?: return
|
||||
pendingThread = null
|
||||
creatingThread = null
|
||||
|
||||
// Gateway turns continue as detached siblings; SSE remains exclusive.
|
||||
releaseTurnForNavigation(handler)
|
||||
@@ -3600,6 +3675,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
|
||||
@@ -3645,6 +3757,8 @@ class ChatViewModel : ViewModel() {
|
||||
fun switchSession(sessionId: String) {
|
||||
val handler = chatHandler ?: return
|
||||
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.
|
||||
@@ -4174,6 +4288,7 @@ class ChatViewModel : ViewModel() {
|
||||
HermesCardInput.Kinds.CHOICE
|
||||
},
|
||||
choices = ask.choices.orEmpty(),
|
||||
multiSelect = ask.multiSelect,
|
||||
allowFreeText = true,
|
||||
expiresAtMillis = expiresAt,
|
||||
),
|
||||
@@ -4439,7 +4554,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
|
||||
}
|
||||
@@ -4573,7 +4688,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)
|
||||
}
|
||||
@@ -4980,6 +5095,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,
|
||||
@@ -5164,6 +5280,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,
|
||||
@@ -5498,9 +5615,24 @@ class ChatViewModel : ViewModel() {
|
||||
detail = cause,
|
||||
)
|
||||
|
||||
// A short transcript fits in Hermes' explicit latest window and can be
|
||||
// polled with one bounded request. Long transcripts retain complete
|
||||
// oldest-first pagination so the positional user anchor and visible
|
||||
// history cannot silently shift when the oldest rows fall outside 500.
|
||||
val recoveryLoadMode = if (handler.messages.value.size < SESSION_MESSAGE_PAGE_SIZE) {
|
||||
SessionMessageLoadMode.LATEST
|
||||
} else {
|
||||
SessionMessageLoadMode.COMPLETE
|
||||
}
|
||||
val recovery = ChatStreamRecovery(
|
||||
scope = viewModelScope,
|
||||
fetchHistory = { loadSessionHistory(checkpoint.sessionId, requireProfileScope = true) },
|
||||
fetchHistory = {
|
||||
loadSessionHistory(
|
||||
checkpoint.sessionId,
|
||||
requireProfileScope = true,
|
||||
mode = recoveryLoadMode,
|
||||
)
|
||||
},
|
||||
timing = recoveryTimingOverride ?: ChatStreamRecovery.Timing(),
|
||||
)
|
||||
streamRecovery = recovery
|
||||
@@ -5676,9 +5808,20 @@ class ChatViewModel : ViewModel() {
|
||||
val priorUserCount = (
|
||||
handler.messages.value.count { it.role == MessageRole.USER } - 1
|
||||
).coerceAtLeast(0)
|
||||
val recoveryLoadMode = if (handler.messages.value.size < SESSION_MESSAGE_PAGE_SIZE) {
|
||||
SessionMessageLoadMode.LATEST
|
||||
} else {
|
||||
SessionMessageLoadMode.COMPLETE
|
||||
}
|
||||
val recovery = ChatStreamRecovery(
|
||||
scope = viewModelScope,
|
||||
fetchHistory = { loadSessionHistory(sessionId, requireProfileScope = true) },
|
||||
fetchHistory = {
|
||||
loadSessionHistory(
|
||||
sessionId,
|
||||
requireProfileScope = true,
|
||||
mode = recoveryLoadMode,
|
||||
)
|
||||
},
|
||||
timing = recoveryTimingOverride ?: ChatStreamRecovery.Timing(),
|
||||
)
|
||||
streamRecovery = recovery
|
||||
@@ -7574,8 +7717,8 @@ 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
|
||||
@@ -7739,8 +7882,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) {
|
||||
@@ -8589,6 +8734,19 @@ internal fun parseCommandsCatalog(catalog: JsonObject): List<SlashCommand> {
|
||||
}
|
||||
val seen = mutableSetOf<String>()
|
||||
val out = mutableListOf<SlashCommand>()
|
||||
val skillMetadata = (catalog["skills"] as? JsonObject)
|
||||
?.entries
|
||||
?.take(MAX_CATALOG_SKILLS)
|
||||
?.associate { (rawName, element) ->
|
||||
val normalized = if (rawName.startsWith("/")) rawName.lowercase() else "/${rawName.lowercase()}"
|
||||
val metadata = element as? JsonObject
|
||||
val usage = (metadata?.get("usage") as? JsonPrimitive)?.intOrNull
|
||||
?.coerceIn(0, MAX_SKILL_USAGE) ?: 0
|
||||
val origin = metadata?.stringValue("origin")
|
||||
?.trim()?.take(MAX_SKILL_ORIGIN_CHARS)?.takeIf { it.isNotBlank() }
|
||||
normalized to (usage to origin)
|
||||
}
|
||||
.orEmpty()
|
||||
(catalog["pairs"] as? JsonArray)?.forEach { pairElement ->
|
||||
val pair = pairElement as? JsonArray ?: return@forEach
|
||||
val rawName = (pair.getOrNull(0) as? JsonPrimitive)?.contentOrNull?.trim()
|
||||
@@ -8597,16 +8755,35 @@ internal fun parseCommandsCatalog(catalog: JsonObject): List<SlashCommand> {
|
||||
if (isUnsupportedMobileCommand(name, pair)) return@forEach
|
||||
if (!seen.add(name.lowercase())) return@forEach
|
||||
val description = (pair.getOrNull(1) as? JsonPrimitive)?.contentOrNull?.trim().orEmpty()
|
||||
val skill = skillMetadata[name.lowercase()]
|
||||
out += SlashCommand(
|
||||
command = name,
|
||||
description = description.ifBlank { "Server command" },
|
||||
category = categoryByName[name.lowercase()] ?: SlashCommand.CATEGORY_SERVER,
|
||||
source = SlashCommand.SOURCE_SERVER,
|
||||
usageRank = skill?.first ?: 0,
|
||||
origin = skill?.second,
|
||||
)
|
||||
}
|
||||
return out
|
||||
// Preserve every non-skill command's exact catalog position. Rank only
|
||||
// entries occupying skill slots, so built-ins and quick commands do not
|
||||
// jump around when usage changes.
|
||||
val rankedSkills = out.filter { skillMetadata.containsKey(it.command.lowercase()) }
|
||||
.sortedWith(compareByDescending<SlashCommand> { it.usageRank }.thenBy { it.command })
|
||||
.iterator()
|
||||
return out.map { command ->
|
||||
if (skillMetadata.containsKey(command.command.lowercase())) rankedSkills.next() else command
|
||||
}
|
||||
}
|
||||
|
||||
private const val MAX_CATALOG_SKILLS = 512
|
||||
private const val MAX_SKILL_USAGE = 1_000_000_000
|
||||
private const val MAX_SKILL_ORIGIN_CHARS = 32
|
||||
|
||||
internal fun isDeferredConfigResult(result: JsonObject): Boolean =
|
||||
(result["deferred"] as? JsonPrimitive)?.contentOrNull
|
||||
?.trim()?.lowercase() in setOf("true", "1", "yes")
|
||||
|
||||
/** Dashboard `/api/config` response -> the same personality catalog as API mode. */
|
||||
internal fun parseDashboardPersonalityConfig(
|
||||
root: JsonObject,
|
||||
|
||||
@@ -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
|
||||
@@ -76,14 +77,20 @@ import com.hermesandroid.relay.network.relay.ConnectionState
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardChatDisplaySettings
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
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
|
||||
@@ -237,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 }
|
||||
@@ -259,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
|
||||
}
|
||||
|
||||
@@ -607,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,
|
||||
)
|
||||
|
||||
@@ -617,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.
|
||||
@@ -712,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
|
||||
@@ -783,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(
|
||||
@@ -861,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
|
||||
@@ -1126,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, "")
|
||||
@@ -1492,8 +1568,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
suspend fun listProfileScopedSessions(limit: Int = 200): Result<List<SessionItem>>? =
|
||||
profileController.listProfileScopedSessions(limit)
|
||||
|
||||
suspend fun loadProfileScopedMessages(sessionId: String): Result<List<MessageItem>>? =
|
||||
profileController.loadProfileScopedMessages(sessionId)
|
||||
suspend fun listAllProfileSessions(limit: Int = 200): Result<List<SessionItem>>? =
|
||||
profileController.listAllProfileSessions(limit)
|
||||
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
|
||||
|
||||
/**
|
||||
* Delete a session scoped to the ACTIVE PROFILE via the dashboard
|
||||
@@ -1851,6 +1932,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 {
|
||||
@@ -2280,6 +2362,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
text = msg.text,
|
||||
receivedAt = msg.sentAt ?: System.currentTimeMillis(),
|
||||
chatId = msg.chatId,
|
||||
connectionId = connectionStore.activeConnectionId.value,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -2455,6 +2538,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.
|
||||
@@ -4553,14 +4637,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
|
||||
@@ -4605,6 +4689,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)
|
||||
@@ -5171,6 +5256,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
gatewayTicketAvailable = gatewayTicketAvailable,
|
||||
message = message,
|
||||
gatewayMode = status?.gatewayMode,
|
||||
servedProfiles = status?.multiplexServedProfiles().orEmpty(),
|
||||
profiles = status?.profiles.orEmpty(),
|
||||
),
|
||||
)
|
||||
@@ -5205,6 +5291,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(),
|
||||
),
|
||||
)
|
||||
@@ -5611,7 +5698,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(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5736,7 +5823,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()
|
||||
@@ -5768,7 +5861,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,
|
||||
@@ -5815,7 +5908,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
|
||||
@@ -5864,7 +5963,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
fun connectRelay() {
|
||||
connectRelayInternal(effectiveRelayUrlSnapshot())
|
||||
connectRelayInternal(effectiveRelayWebSocketUrlSnapshot())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -6267,6 +6366,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"
|
||||
}
|
||||
}
|
||||
|
||||
+12
-2
@@ -18,6 +18,7 @@ import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardProfileScope
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -343,17 +344,26 @@ class ProfileController(
|
||||
.listSessions(profile = profileName, limit = limit, archived = "include")
|
||||
}
|
||||
|
||||
suspend fun listAllProfileSessions(limit: Int = 200): Result<List<SessionItem>>? {
|
||||
val connectionId = activeConnectionId.value ?: return null
|
||||
val dashboardUrl = activeDashboardUrlProvider() ?: return null
|
||||
return dashboardClientFactory(connectionId, dashboardUrl).listAllProfileSessions(limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* A session's transcript, scoped to the active profile via the dashboard
|
||||
* `/api/sessions/{id}/messages?profile=`. Returns `null` off the dashboard
|
||||
* surface so the caller falls back to the api_server transcript.
|
||||
*/
|
||||
suspend fun loadProfileScopedMessages(sessionId: String): Result<List<MessageItem>>? {
|
||||
suspend fun loadProfileScopedMessages(
|
||||
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)
|
||||
.getSessionMessages(sessionId, profileName, mode)
|
||||
}
|
||||
|
||||
suspend fun deleteProfileScopedSession(sessionId: String): Boolean {
|
||||
|
||||
+34
-18
@@ -77,6 +77,9 @@ 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 },
|
||||
) {
|
||||
|
||||
// --- Per-connection dashboard cookie stores ----------------------------
|
||||
@@ -147,30 +150,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 = DashboardApiClient.defaultClient(
|
||||
cookieStore = dashboardCookieStoreFor(connectionId),
|
||||
bearerAuth = 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 = DashboardApiClient.defaultClient(
|
||||
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
|
||||
bearerAuth = 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 +197,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 +219,14 @@ class UpstreamTransportController(
|
||||
disposeDashboardHttpClient(client)
|
||||
dashboardHttpClientCache = null
|
||||
}
|
||||
return DashboardApiClient.defaultClient(
|
||||
val base = DashboardApiClient.defaultClient(
|
||||
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
|
||||
bearerAuth = activeConnectionIdProvider()?.let { activeId ->
|
||||
bearerAuthForTrustedDashboard(activeId, dashboardUrl)
|
||||
},
|
||||
).also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
|
||||
)
|
||||
return (pinnedClientProvider(dashboardUrl, base) ?: base)
|
||||
.also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
|
||||
@@ -3825,4 +3825,89 @@
|
||||
<string name="pet_creator_step_review">Revisar e importar</string>
|
||||
<string name="pet_creator_review_desc">Inspecione primeiro a imagem ou o ZIP retornado. A importação copia os arquivos validados para o armazenamento do app; ela não os publica.</string>
|
||||
<string name="pet_creator_import">Importar pet concluído</string>
|
||||
<string name="dashboard_tab_memory">Memória</string>
|
||||
<string name="dashboard_tab_learning">Aprendizado</string>
|
||||
<string name="dashboard_tab_channels">Canais</string>
|
||||
<string name="dashboard_tab_operations">Operações</string>
|
||||
<string name="dashboard_tab_memory_lower">memória</string>
|
||||
<string name="dashboard_tab_learning_lower">aprendizado</string>
|
||||
<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>
|
||||
<string name="dashboard_tile_memory_sub">Status do provedor e configuração de memória do servidor</string>
|
||||
<string name="dashboard_tile_learning_title">Grafo de aprendizado</string>
|
||||
<string name="dashboard_tile_learning_sub">Inspecione os nós aprendidos do perfil ativo</string>
|
||||
<string name="dashboard_tile_channels_title">Canais</string>
|
||||
<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_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>
|
||||
|
||||
@@ -3913,4 +3913,89 @@
|
||||
<string name="pet_creator_step_review">检查并导入</string>
|
||||
<string name="pet_creator_review_desc">请先检查返回的图片或 ZIP。导入会将经过验证的文件复制到应用专属存储空间,不会发布它们。</string>
|
||||
<string name="pet_creator_import">导入完成的宠物</string>
|
||||
<string name="dashboard_tab_memory">记忆</string>
|
||||
<string name="dashboard_tab_learning">学习</string>
|
||||
<string name="dashboard_tab_channels">频道</string>
|
||||
<string name="dashboard_tab_operations">运维</string>
|
||||
<string name="dashboard_tab_memory_lower">记忆</string>
|
||||
<string name="dashboard_tab_learning_lower">学习</string>
|
||||
<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_profile_mcp_servers_optional">MCP 服务器(可选)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">用逗号或换行分隔服务器名称。凭据仍由服务器保管。</string>
|
||||
<string name="dashboard_tile_memory_title">记忆</string>
|
||||
<string name="dashboard_tile_memory_sub">提供商状态和服务器端记忆配置</string>
|
||||
<string name="dashboard_tile_learning_title">学习图谱</string>
|
||||
<string name="dashboard_tile_learning_sub">查看当前配置文件的已学习节点</string>
|
||||
<string name="dashboard_tile_channels_title">频道</string>
|
||||
<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_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>
|
||||
|
||||
@@ -3985,4 +3985,89 @@
|
||||
<string name="pet_creator_step_review">Prüfen und importieren</string>
|
||||
<string name="pet_creator_review_desc">Prüfen Sie zuerst das zurückgegebene Bild oder ZIP. Beim Import werden die validierten Dateien in den App-Speicher kopiert; sie werden nicht veröffentlicht.</string>
|
||||
<string name="pet_creator_import">Fertiges Pet importieren</string>
|
||||
<string name="dashboard_tab_memory">Speicher</string>
|
||||
<string name="dashboard_tab_learning">Lernen</string>
|
||||
<string name="dashboard_tab_channels">Kanäle</string>
|
||||
<string name="dashboard_tab_operations">Betrieb</string>
|
||||
<string name="dashboard_tab_memory_lower">Speicher</string>
|
||||
<string name="dashboard_tab_learning_lower">Lernen</string>
|
||||
<string name="dashboard_tab_channels_lower">Kanäle</string>
|
||||
<string name="dashboard_tab_operations_lower">Betrieb</string>
|
||||
<string name="dashboard_section_action_server_backup">Server-Sicherung erstellen</string>
|
||||
<string name="dashboard_profile_mcp_servers_optional">MCP-Server (optional)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">Komma- oder zeilengetrennte Servernamen. Anmeldedaten verbleiben auf dem Server.</string>
|
||||
<string name="dashboard_tile_memory_title">Speicher</string>
|
||||
<string name="dashboard_tile_memory_sub">Anbieterstatus und servereigene Speicherkonfiguration</string>
|
||||
<string name="dashboard_tile_learning_title">Lerngraph</string>
|
||||
<string name="dashboard_tile_learning_sub">Gelernte Knoten des aktiven Profils prüfen</string>
|
||||
<string name="dashboard_tile_channels_title">Kanäle</string>
|
||||
<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_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>
|
||||
|
||||
@@ -3670,4 +3670,89 @@
|
||||
<string name="pet_creator_step_review">Revisar e importar</string>
|
||||
<string name="pet_creator_review_desc">Inspecciona primero la imagen o el ZIP recibido. Al importar se copian los archivos validados al almacenamiento de la aplicación; no se publican.</string>
|
||||
<string name="pet_creator_import">Importar mascota terminada</string>
|
||||
<string name="dashboard_tab_memory">Memoria</string>
|
||||
<string name="dashboard_tab_learning">Aprendizaje</string>
|
||||
<string name="dashboard_tab_channels">Canales</string>
|
||||
<string name="dashboard_tab_operations">Operaciones</string>
|
||||
<string name="dashboard_tab_memory_lower">memoria</string>
|
||||
<string name="dashboard_tab_learning_lower">aprendizaje</string>
|
||||
<string name="dashboard_tab_channels_lower">canales</string>
|
||||
<string name="dashboard_tab_operations_lower">operaciones</string>
|
||||
<string name="dashboard_section_action_server_backup">Crear copia del servidor</string>
|
||||
<string name="dashboard_profile_mcp_servers_optional">Servidores MCP (opcional)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">Nombres de servidor separados por comas o líneas. Las credenciales permanecen en el servidor.</string>
|
||||
<string name="dashboard_tile_memory_title">Memoria</string>
|
||||
<string name="dashboard_tile_memory_sub">Estado del proveedor y configuración de memoria del servidor</string>
|
||||
<string name="dashboard_tile_learning_title">Grafo de aprendizaje</string>
|
||||
<string name="dashboard_tile_learning_sub">Inspecciona los nodos aprendidos del perfil activo</string>
|
||||
<string name="dashboard_tile_channels_title">Canales</string>
|
||||
<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_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>
|
||||
|
||||
@@ -3984,4 +3984,89 @@
|
||||
<string name="pet_creator_step_review">確認してインポート</string>
|
||||
<string name="pet_creator_review_desc">返された画像またはZIPを最初に確認してください。インポートすると検証済みファイルがアプリ専用ストレージにコピーされますが、公開はされません。</string>
|
||||
<string name="pet_creator_import">完成したペットをインポート</string>
|
||||
<string name="dashboard_tab_memory">メモリ</string>
|
||||
<string name="dashboard_tab_learning">学習</string>
|
||||
<string name="dashboard_tab_channels">チャンネル</string>
|
||||
<string name="dashboard_tab_operations">運用</string>
|
||||
<string name="dashboard_tab_memory_lower">メモリ</string>
|
||||
<string name="dashboard_tab_learning_lower">学習</string>
|
||||
<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>
|
||||
<string name="dashboard_tile_memory_sub">プロバイダーの状態とサーバー側のメモリ設定</string>
|
||||
<string name="dashboard_tile_learning_title">学習グラフ</string>
|
||||
<string name="dashboard_tile_learning_sub">アクティブなプロファイルの学習済みノードを確認</string>
|
||||
<string name="dashboard_tile_channels_title">チャンネル</string>
|
||||
<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_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>
|
||||
|
||||
@@ -3706,4 +3706,89 @@
|
||||
<string name="pet_creator_step_review">Проверить и импортировать</string>
|
||||
<string name="pet_creator_review_desc">Сначала проверьте полученное изображение или ZIP. При импорте проверенные файлы копируются в хранилище приложения и не публикуются.</string>
|
||||
<string name="pet_creator_import">Импортировать готового питомца</string>
|
||||
<string name="dashboard_tab_memory">Память</string>
|
||||
<string name="dashboard_tab_learning">Обучение</string>
|
||||
<string name="dashboard_tab_channels">Каналы</string>
|
||||
<string name="dashboard_tab_operations">Операции</string>
|
||||
<string name="dashboard_tab_memory_lower">память</string>
|
||||
<string name="dashboard_tab_learning_lower">обучение</string>
|
||||
<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_profile_mcp_servers_optional">Серверы MCP (необязательно)</string>
|
||||
<string name="dashboard_profile_mcp_servers_help">Имена серверов через запятую или с новой строки. Учётные данные остаются на сервере.</string>
|
||||
<string name="dashboard_tile_memory_title">Память</string>
|
||||
<string name="dashboard_tile_memory_sub">Состояние провайдера и серверная настройка памяти</string>
|
||||
<string name="dashboard_tile_learning_title">Граф обучения</string>
|
||||
<string name="dashboard_tile_learning_sub">Просмотр изученных узлов активного профиля</string>
|
||||
<string name="dashboard_tile_channels_title">Каналы</string>
|
||||
<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_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>
|
||||
@@ -1862,6 +1877,10 @@
|
||||
<string name="dashboard_tab_models">Models</string>
|
||||
<string name="dashboard_tab_keys">Keys</string>
|
||||
<string name="dashboard_tab_config">Config</string>
|
||||
<string name="dashboard_tab_memory">Memory</string>
|
||||
<string name="dashboard_tab_learning">Learning</string>
|
||||
<string name="dashboard_tab_channels">Channels</string>
|
||||
<string name="dashboard_tab_operations">Operations</string>
|
||||
<!-- Lowercase tab labels for compact UI surfaces (KPI strip) -->
|
||||
<string name="dashboard_tab_skills_lower">skills</string>
|
||||
<string name="dashboard_tab_cron_lower">cron</string>
|
||||
@@ -1872,6 +1891,10 @@
|
||||
<string name="dashboard_tab_models_lower">models</string>
|
||||
<string name="dashboard_tab_keys_lower">keys</string>
|
||||
<string name="dashboard_tab_config_lower">config</string>
|
||||
<string name="dashboard_tab_memory_lower">memory</string>
|
||||
<string name="dashboard_tab_learning_lower">learning</string>
|
||||
<string name="dashboard_tab_channels_lower">channels</string>
|
||||
<string name="dashboard_tab_operations_lower">operations</string>
|
||||
|
||||
<!-- Tile titles + subtitles -->
|
||||
<string name="dashboard_tile_profiles_title">Profiles</string>
|
||||
@@ -1968,6 +1991,27 @@
|
||||
<string name="dashboard_section_action_new_profile">New profile</string>
|
||||
<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>
|
||||
<string name="dashboard_tile_memory_sub">Provider status and host-owned memory configuration</string>
|
||||
<string name="dashboard_tile_learning_title">Learning graph</string>
|
||||
<string name="dashboard_tile_learning_sub">Inspect learned nodes for the active profile</string>
|
||||
<string name="dashboard_tile_channels_title">Channels</string>
|
||||
<string name="dashboard_tile_channels_sub">Messaging platform status, including WhatsApp</string>
|
||||
<string name="dashboard_tile_operations_title">Server operations</string>
|
||||
<string name="dashboard_tile_operations_sub">Host health and server-wide backup</string>
|
||||
|
||||
<!-- Action labels (rendered via kind → string) -->
|
||||
<string name="dashboard_action_set">Set</string>
|
||||
@@ -1991,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>
|
||||
@@ -3991,4 +4063,17 @@
|
||||
<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_no_profile_sessions">No matching profile sessions.</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>
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ReconnectBackoffTest {
|
||||
@Test
|
||||
fun `full jitter stays within the cap`() {
|
||||
assertEquals(0L, fullJitterDelayMs(1_000L, 0.0))
|
||||
assertEquals(500L, fullJitterDelayMs(1_000L, 0.5))
|
||||
assertEquals(1_000L, fullJitterDelayMs(1_000L, 1.0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non-positive caps are immediate`() {
|
||||
assertEquals(0L, fullJitterDelayMs(0L, 0.5))
|
||||
assertEquals(0L, fullJitterDelayMs(-1L, 0.5))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -144,6 +145,43 @@ class ChatHandlerTest {
|
||||
assertEquals("ABC", messages[0].content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaMarkers_acceptUpstreamWrappersPunctuationAdjacentAndWindowsPaths() {
|
||||
val paths = mutableListOf<String>()
|
||||
handler.onMediaBarePathRequested = { _, path -> paths += path }
|
||||
|
||||
handler.onTextDelta("assist-1", "`MEDIA:/tmp/report.csv.`\n")
|
||||
handler.onTextDelta(
|
||||
"assist-1",
|
||||
"**MEDIA:C:\\exports\\shot.png**, MEDIA:/tmp/other report.pdf\n",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
"/tmp/report.csv",
|
||||
"C:\\exports\\shot.png",
|
||||
"/tmp/other report.pdf",
|
||||
),
|
||||
paths,
|
||||
)
|
||||
assertEquals("", handler.messages.value.single().content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaMarkers_preserveFencedAndProseExamples() {
|
||||
val paths = mutableListOf<String>()
|
||||
handler.onMediaBarePathRequested = { _, path -> paths += path }
|
||||
|
||||
handler.onTextDelta(
|
||||
"assist-1",
|
||||
"```text\nMEDIA:/tmp/example.png\n```\nExample: `MEDIA:/tmp/example.pdf`\n",
|
||||
)
|
||||
|
||||
assertTrue(paths.isEmpty())
|
||||
assertTrue(handler.messages.value.single().content.contains("MEDIA:/tmp/example.png"))
|
||||
assertTrue(handler.messages.value.single().content.contains("MEDIA:/tmp/example.pdf"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onTextDelta_setsStreamingFlag() {
|
||||
handler.onTextDelta("assist-1", "delta")
|
||||
@@ -565,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")))
|
||||
@@ -883,6 +950,50 @@ 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 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(
|
||||
|
||||
+479
-8
@@ -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
|
||||
@@ -690,24 +725,30 @@ class DashboardApiClientTest {
|
||||
apiKey = "never-persist-this",
|
||||
)
|
||||
|
||||
val listed = client.getCustomEndpoints().getOrThrow()
|
||||
client.saveCustomEndpoint(draft).getOrThrow()
|
||||
val listed = client.getCustomEndpoints("work profile").getOrThrow()
|
||||
client.saveCustomEndpoint(draft, "work profile").getOrThrow()
|
||||
val validation = client.validateCustomEndpoint(draft).getOrThrow()
|
||||
client.activateCustomEndpoint("local").getOrThrow()
|
||||
client.deleteCustomEndpoint("local").getOrThrow()
|
||||
client.activateCustomEndpoint("local", "work profile").getOrThrow()
|
||||
client.deleteCustomEndpoint("local", "work profile").getOrThrow()
|
||||
|
||||
assertEquals("local", listed.currentProvider)
|
||||
assertTrue(listed.endpoints.single().hasApiKey)
|
||||
assertEquals(listOf("qwen"), validation.models)
|
||||
assertEquals("/api/providers/custom-endpoints", server.takeRequest().path)
|
||||
assertEquals("/api/providers/custom-endpoints?profile=work%20profile", server.takeRequest().path)
|
||||
val save = server.takeRequest()
|
||||
assertEquals("/api/providers/custom-endpoints", save.path)
|
||||
assertEquals("/api/providers/custom-endpoints?profile=work%20profile", save.path)
|
||||
val saveBody = save.body.readUtf8()
|
||||
assertTrue(saveBody.contains("never-persist-this"))
|
||||
assertTrue(saveBody.contains(""""models":["qwen","qwen-vl"]"""))
|
||||
assertEquals("/api/providers/custom-endpoints/validate", server.takeRequest().path)
|
||||
assertEquals("/api/providers/custom-endpoints/local/activate", server.takeRequest().path)
|
||||
assertEquals("/api/providers/custom-endpoints/local", server.takeRequest().path)
|
||||
assertEquals(
|
||||
"/api/providers/custom-endpoints/local/activate?profile=work%20profile",
|
||||
server.takeRequest().path,
|
||||
)
|
||||
assertEquals(
|
||||
"/api/providers/custom-endpoints/local?profile=work%20profile",
|
||||
server.takeRequest().path,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -733,6 +774,30 @@ class DashboardApiClientTest {
|
||||
assertEquals("/api/profiles/old%20profile", delete.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun profileCreationCarriesMcpServersAndServerBackupIsDistinct() = runTest {
|
||||
repeat(2) {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true}"""),
|
||||
)
|
||||
}
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
|
||||
client.createProfile(
|
||||
name = "research",
|
||||
description = "Deep work",
|
||||
mcpServers = listOf("github", "memory"),
|
||||
).getOrThrow()
|
||||
client.createServerBackup().getOrThrow()
|
||||
|
||||
val create = server.takeRequest()
|
||||
assertEquals("/api/profiles", create.path)
|
||||
assertTrue(create.body.readUtf8().contains(""""mcp_servers":["github","memory"]"""))
|
||||
val backup = server.takeRequest()
|
||||
assertEquals("POST", backup.method)
|
||||
assertEquals("/api/ops/backup", backup.path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getActiveProfileScope_distinguishesStickyDefaultFromDashboardProcess() = runTest {
|
||||
server.enqueue(
|
||||
@@ -834,6 +899,213 @@ 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(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"sessions":[{"id":"same","title":"A","profile":"default"},{"id":"same","title":"B","profile":"work"},{"id":"unsafe"}],"total":3}""",
|
||||
),
|
||||
)
|
||||
|
||||
val sessions = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.listAllProfileSessions()
|
||||
.getOrThrow()
|
||||
|
||||
val url = server.takeRequest().requestUrl!!
|
||||
assertEquals("/api/profiles/sessions", url.encodedPath)
|
||||
assertEquals("all", url.queryParameter("profile"))
|
||||
assertEquals("include", url.queryParameter("archived"))
|
||||
assertEquals(listOf("default", "work"), sessions.map { it.profile })
|
||||
assertEquals(listOf("A", "B"), sessions.map { it.title })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listSessions_pagesAtUpstreamMaximumWhilePreservingTwoHundredRowWindow() = runTest {
|
||||
val firstPage = (0 until 100).joinToString(",") { "{\"id\":\"sess-$it\"}" }
|
||||
@@ -901,11 +1173,45 @@ class DashboardApiClientTest {
|
||||
val url = request.requestUrl!!
|
||||
assertEquals("/api/sessions/sess-a/messages", url.encodedPath)
|
||||
assertEquals("mizu", url.queryParameter("profile"))
|
||||
assertEquals("500", url.queryParameter("limit"))
|
||||
assertEquals("0", url.queryParameter("offset"))
|
||||
assertEquals("oldest", url.queryParameter("order"))
|
||||
assertEquals(2, messages.size)
|
||||
assertEquals("user", messages[0].role)
|
||||
assertEquals("assistant", messages[1].role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSessionMessages_pagesCompleteHistoryAndPreservesProfileScope() = runTest {
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 0, count = 500, returned = 500))
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.getSessionMessages("sess-a", profile = "mizu")
|
||||
.getOrThrow()
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
val second = server.takeRequest().requestUrl!!
|
||||
assertEquals(listOf("0", "500"), listOf(first, second).map { it.queryParameter("offset") })
|
||||
assertEquals(listOf("mizu", "mizu"), listOf(first, second).map { it.queryParameter("profile") })
|
||||
assertEquals((0..500).map(Int::toString), messages.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSessionMessages_latestUsesOneBoundedPage() = runTest {
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 500, count = 500, returned = 500))
|
||||
|
||||
val messages = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.getSessionMessages("sess-a", profile = null, mode = SessionMessageLoadMode.LATEST)
|
||||
.getOrThrow()
|
||||
|
||||
val request = server.takeRequest().requestUrl!!
|
||||
assertEquals("latest", request.queryParameter("order"))
|
||||
assertEquals("0", request.queryParameter("offset"))
|
||||
assertEquals(500, messages.size)
|
||||
assertEquals(1, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseChatDisplaySettings_readsNestedDisplayConfig() {
|
||||
val root = Json.parseToJsonElement(
|
||||
@@ -1286,4 +1592,169 @@ 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(
|
||||
key: String,
|
||||
start: Int,
|
||||
count: Int,
|
||||
returned: Int,
|
||||
): MockResponse {
|
||||
val messages = (start until start + count).joinToString(",") { index ->
|
||||
"""{"id":"$index","role":"user","content":"m$index"}"""
|
||||
}
|
||||
return MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"session_id":"sess-a","$key":[$messages],"pagination":{"limit":500,"offset":$start,"order":"oldest","returned":$returned}}""",
|
||||
)
|
||||
}
|
||||
|
||||
+363
-15
@@ -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(
|
||||
@@ -251,6 +264,8 @@ class GatewayClientHarness(
|
||||
put("status", steerStatus)
|
||||
put("text", (params["text"] as? JsonPrimitive)?.contentOrNull ?: "")
|
||||
}
|
||||
"subagent.steer" -> buildJsonObject { put("status", steerStatus) }
|
||||
"message.react" -> buildJsonObject { put("row_id", 17) }
|
||||
"session.compress" -> compressPayload
|
||||
"slash.exec" -> buildJsonObject {
|
||||
put("output", "legacy compression started")
|
||||
@@ -263,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) }
|
||||
@@ -276,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")
|
||||
@@ -625,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()
|
||||
@@ -677,6 +762,55 @@ class GatewayChatClientTest {
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `global reclaim settles active turn once and next send resumes durable session`() {
|
||||
val first = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
text = "first",
|
||||
newSessionTitle = "first",
|
||||
callbacks = first.callbacks,
|
||||
onPreflightFailure = { first.preflightFailures += it },
|
||||
)
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
val reclaim = harness.eventFrame(
|
||||
"session.reclaimed",
|
||||
buildJsonObject {
|
||||
put("session_id", "live-1")
|
||||
put("stored_session_id", "20260612_120000_abc123")
|
||||
put("reason", "idle_timeout")
|
||||
},
|
||||
null,
|
||||
)
|
||||
serverWs.send(reclaim)
|
||||
serverWs.send(reclaim)
|
||||
|
||||
assertTrue("reclaimed turn never settled", first.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
waitUntil { first.errors.size == 1 }
|
||||
|
||||
val second = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = "20260612_120000_abc123",
|
||||
text = "continue",
|
||||
newSessionTitle = null,
|
||||
callbacks = second.callbacks,
|
||||
onPreflightFailure = { second.preflightFailures += it },
|
||||
)
|
||||
harness.awaitRpc("session.resume")
|
||||
harness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "resumed") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue("resumed turn never completed", second.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(second.errors.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unsolicited assistant turn for resumed session streams without sendTurn`() = runBlocking {
|
||||
val r = Recorder()
|
||||
@@ -1303,6 +1437,22 @@ class GatewayChatClientTest {
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.steer" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `subagent redirect carries exact parent and child identity`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn(null, "delegate", null, recorder.callbacks) { recorder.preflightFailures += it }
|
||||
harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
val result = client.steerSubagent("child-17", "focus on Android")
|
||||
|
||||
assertEquals("queued", (result.getOrThrow()["status"] as? JsonPrimitive)?.contentOrNull)
|
||||
val params = harness.awaitRpc("subagent.steer")
|
||||
assertEquals("live-1", (params["session_id"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("child-17", (params["subagent_id"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("focus on Android", (params["text"] as? JsonPrimitive)?.contentOrNull)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compress session uses dedicated rpc and parses authoritative messages`() {
|
||||
val r = Recorder()
|
||||
@@ -1351,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) ---
|
||||
|
||||
@@ -1639,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)
|
||||
@@ -1648,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
|
||||
@@ -1753,6 +1980,23 @@ class GatewayChatClientTest {
|
||||
|
||||
// --- Pet thumbnails ---
|
||||
|
||||
@Test
|
||||
fun `message reaction targets newest role without guessing a row id`() {
|
||||
client.sendTurn("stored-1", "hi", null, Recorder().callbacks) {}
|
||||
harness.awaitRpc("session.resume")
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
val result = runBlocking { client.reactToNewest("assistant", "👍") }
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
val params = harness.awaitRpc("message.react")
|
||||
assertEquals("live-resumed", (params["session_id"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("assistant", (params["newest_role"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("👍", (params["emoji"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("user", (params["author"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertFalse("row_id" in params)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pet thumbnail connects on demand and sends upstream params`() {
|
||||
client.sessionProfileProvider = { "work" }
|
||||
@@ -2099,7 +2343,7 @@ class GatewayChatClientTest {
|
||||
// --- Edit & regenerate ---
|
||||
|
||||
@Test
|
||||
fun `truncate ordinal rides prompt submit`() {
|
||||
fun `later truncate ordinal carries destructive confirmation only`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
@@ -2111,6 +2355,77 @@ class GatewayChatClientTest {
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(2, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
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()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
text = "replace first message",
|
||||
newSessionTitle = null,
|
||||
callbacks = r.callbacks,
|
||||
truncateBeforeUserOrdinal = 0,
|
||||
onPreflightFailure = { r.preflightFailures += it },
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(0, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
assertEquals(true, (submit["confirm_empty_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `middle truncate ordinal omits empty-history confirmation`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
text = "replace middle message",
|
||||
newSessionTitle = null,
|
||||
callbacks = r.callbacks,
|
||||
truncateBeforeUserOrdinal = 1,
|
||||
onPreflightFailure = { r.preflightFailures += it },
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(1, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
assertFalse(submit.containsKey("confirm_empty_truncate"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2119,6 +2434,8 @@ class GatewayChatClientTest {
|
||||
client.sendTurn(null, "plain", null, r.callbacks) { r.preflightFailures += it }
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertFalse(submit.containsKey("truncate_before_user_ordinal"))
|
||||
assertFalse(submit.containsKey("confirm_truncate"))
|
||||
assertFalse(submit.containsKey("confirm_empty_truncate"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2138,18 +2455,49 @@ class GatewayChatClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session cap rejection surfaces error without preflight fallback`() {
|
||||
val message = "Active session limit reached; close the session held by another client"
|
||||
harness.rpcErrors["prompt.submit"] = 4090 to message
|
||||
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",
|
||||
)
|
||||
|
||||
cases.forEachIndexed { index, (code, message) ->
|
||||
harness.rpcErrors["prompt.submit"] = code to message
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "hello-$code", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
waitUntil { r.errors.isNotEmpty() }
|
||||
assertEquals(listOf(message), r.errors.toList())
|
||||
assertTrue("$code must not trigger SSE fallback", r.preflightFailures.isEmpty())
|
||||
assertEquals(index + 1, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
}
|
||||
}
|
||||
|
||||
@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(null, "hello", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitRpc("prompt.submit")
|
||||
client.sendTurn("oversized-session", "continue", null, r.callbacks) {
|
||||
r.preflightFailures += it
|
||||
}
|
||||
|
||||
waitUntil { r.errors.isNotEmpty() }
|
||||
harness.awaitRpc("session.resume")
|
||||
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertEquals(listOf(message), r.errors.toList())
|
||||
assertTrue("authoritative rejection must not trigger SSE fallback", r.preflightFailures.isEmpty())
|
||||
assertEquals(1, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
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.
|
||||
|
||||
+82
-2
@@ -483,6 +483,23 @@ class GatewayEventMapperTest {
|
||||
assertEquals(listOf("t2" to "completed skill"), standard.toolDones)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `structured tool arguments win over legacy previews`() {
|
||||
val recorder = Recorder()
|
||||
val mapper = mapperWith(recorder)
|
||||
mapper.onEvent(
|
||||
"tool.start",
|
||||
obj(
|
||||
"""{"tool_id":"t3","name":"terminal","args":{"command":"echo live","timeout":30},"args_text":"stale","context":"older"}""",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("t3" to "{\"command\":\"echo live\",\"timeout\":30}"),
|
||||
recorder.toolStartArgs,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tool complete with error routes to failed`() {
|
||||
val r = Recorder()
|
||||
@@ -574,7 +591,7 @@ class GatewayEventMapperTest {
|
||||
fun `subagent lifecycle maps phases and fields`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
mapper.onEvent("subagent.start", obj("""{"goal":"research topic","task_index":1,"task_count":3}"""))
|
||||
mapper.onEvent("subagent.start", obj("""{"goal":"research topic","task_index":1,"task_count":3,"subagent_id":"child-17"}"""))
|
||||
mapper.onEvent("subagent.thinking", obj("""{"goal":"research topic","task_index":1,"task_count":3,"text":"hmm"}"""))
|
||||
mapper.onEvent(
|
||||
"subagent.tool",
|
||||
@@ -600,6 +617,7 @@ class GatewayEventMapperTest {
|
||||
assertEquals(1, start.taskIndex)
|
||||
assertEquals(3, start.taskCount)
|
||||
assertEquals("research topic", start.goal)
|
||||
assertEquals("child-17", start.subagentId)
|
||||
assertEquals("hmm", r.subagentEvents[1].preview)
|
||||
val tool = r.subagentEvents[2]
|
||||
assertEquals("web_search", tool.toolName)
|
||||
@@ -697,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
|
||||
@@ -740,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()
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.SkillListResponse
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
@@ -18,6 +21,48 @@ import org.junit.Test
|
||||
*/
|
||||
class HermesApiClientTest {
|
||||
|
||||
@Test
|
||||
fun getMessages_pagesApiFallbackOldestFirst() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
try {
|
||||
server.enqueue(apiMessagePageResponse(start = 0, count = 500, returned = 500))
|
||||
server.enqueue(apiMessagePageResponse(start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = HermesApiClient(server.url("/").toString(), "test-key")
|
||||
.getMessages("sess-a")
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
val second = server.takeRequest().requestUrl!!
|
||||
assertEquals(listOf("0", "500"), listOf(first, second).map { it.queryParameter("offset") })
|
||||
assertEquals(listOf("oldest", "oldest"), listOf(first, second).map { it.queryParameter("order") })
|
||||
assertEquals((0..500).map(Int::toString), messages.map { it.id })
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getMessages_acceptsLegacyUnpaginatedApiEnvelope() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
try {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"object":"list","data":[{"id":"1","role":"user","content":"hi"}]}""",
|
||||
),
|
||||
)
|
||||
|
||||
val messages = HermesApiClient(server.url("/").toString(), "test-key")
|
||||
.getMessages("sess-a")
|
||||
|
||||
assertEquals(listOf("1"), messages.map { it.id })
|
||||
assertEquals(1, server.requestCount)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolsetInventory_parserPreservesEnabledAndResolvedTools() {
|
||||
val parsed = parseToolsetListBody(
|
||||
@@ -596,3 +641,14 @@ class HermesApiClientTest {
|
||||
assertEquals("http://localhost:8642/api/sessions/sess-789", url)
|
||||
}
|
||||
}
|
||||
|
||||
private fun apiMessagePageResponse(start: Int, count: Int, returned: Int): MockResponse {
|
||||
val messages = (start until start + count).joinToString(",") { index ->
|
||||
"""{"id":"$index","role":"user","content":"m$index"}"""
|
||||
}
|
||||
return MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"object":"list","session_id":"sess-a","data":[$messages],"pagination":{"limit":500,"offset":$start,"order":"oldest","returned":$returned}}""",
|
||||
)
|
||||
}
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessagePagination
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SessionMessagePaginationTest {
|
||||
|
||||
@Test
|
||||
fun `complete history pages oldest first without gaps`() = runTest {
|
||||
val requests = mutableListOf<SessionMessagePageRequest>()
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) { request ->
|
||||
requests += request
|
||||
val count = if (request.offset == 0) 500 else 1
|
||||
Result.success(page(request.offset, count, returned = count))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals((0..500).map(Int::toString), result.map { it.id })
|
||||
assertEquals(listOf(0, 500), requests.map { it.offset })
|
||||
assertEquals(listOf("oldest", "oldest"), requests.map { it.order })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exact 500 requests one terminal page and returns no duplicates`() = runTest {
|
||||
val requests = mutableListOf<SessionMessagePageRequest>()
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) { request ->
|
||||
requests += request
|
||||
val count = if (request.offset == 0) 500 else 0
|
||||
Result.success(page(request.offset, count, returned = count))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(500, result.size)
|
||||
assertEquals(listOf(0, 500), requests.map { it.offset })
|
||||
assertEquals(500, result.mapNotNull { it.id }.distinct().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy envelope is accepted as one complete response`() = runTest {
|
||||
var calls = 0
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
calls++
|
||||
Result.success(page(0, 499, pagination = null))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(499, result.size)
|
||||
assertEquals(1, calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `latest mode makes exactly one bounded latest request`() = runTest {
|
||||
var captured: SessionMessagePageRequest? = null
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.LATEST) { request ->
|
||||
captured = request
|
||||
Result.success(page(500, 500, returned = 500))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(500, result.size)
|
||||
assertEquals("latest", captured?.order)
|
||||
assertEquals(0, captured?.offset)
|
||||
assertEquals(500, captured?.limit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancellation is never converted to an empty transcript`() = runTest {
|
||||
try {
|
||||
loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
throw CancellationException("session switched")
|
||||
}
|
||||
throw AssertionError("expected cancellation")
|
||||
} catch (error: CancellationException) {
|
||||
assertEquals("session switched", error.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `payload safety bound fails clearly before another page`() = runTest {
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
Result.success(
|
||||
SessionMessagePage(
|
||||
messages = emptyList(),
|
||||
pagination = MessagePagination(returned = 0),
|
||||
payloadChars = 32_000_001,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
assertEquals(SessionTranscriptTooLargeException::class, result.exceptionOrNull()?.let { it::class })
|
||||
}
|
||||
|
||||
private fun page(
|
||||
start: Int,
|
||||
count: Int,
|
||||
returned: Int = count,
|
||||
pagination: MessagePagination? = MessagePagination(
|
||||
limit = SESSION_MESSAGE_PAGE_SIZE,
|
||||
offset = start,
|
||||
order = "oldest",
|
||||
returned = returned,
|
||||
),
|
||||
): SessionMessagePage = SessionMessagePage(
|
||||
messages = (start until start + count).map { index ->
|
||||
MessageItem(id = index.toString(), role = "user", content = JsonPrimitive("m$index"))
|
||||
},
|
||||
pagination = pagination,
|
||||
payloadChars = count * 20,
|
||||
)
|
||||
}
|
||||
+37
@@ -94,6 +94,18 @@ class SessionModelsTest {
|
||||
assertTrue(item.archived)
|
||||
}
|
||||
|
||||
@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 +145,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 +301,27 @@ 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,
|
||||
)
|
||||
}
|
||||
|
||||
@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",
|
||||
|
||||
@@ -49,6 +49,34 @@ 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),
|
||||
)
|
||||
}
|
||||
|
||||
@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(
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SessionReferenceTest {
|
||||
@Test
|
||||
fun `references outside code are bounded and parsed`() {
|
||||
val text = """
|
||||
Open @session:research/20260811_abc123.
|
||||
`@session:hidden/inline`
|
||||
```text
|
||||
@session:hidden/fenced
|
||||
```
|
||||
Also @session:default/session-2
|
||||
""".trimIndent()
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
SessionReference("research", "20260811_abc123"),
|
||||
SessionReference("default", "session-2"),
|
||||
),
|
||||
parseSessionReferences(text),
|
||||
)
|
||||
}
|
||||
}
|
||||
+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",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
+29
-2
@@ -63,21 +63,48 @@ class DashboardManageParityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mcpManagePlumbing_usesEffectiveProfileForListAndRowActions() {
|
||||
fun completedOneShotCron_showsOutcomeAndOnlyOffersRunsAndDelete() {
|
||||
val root = Json.parseToJsonElement(
|
||||
"""{"id":"once","name":"One shot","schedule":"@once","state":"completed","enabled":false,"last_status":"error","last_error":"model timeout","last_delivery_error":"phone offline"}""",
|
||||
).jsonObject
|
||||
|
||||
val row = summarizeObjectItem(root, "once")
|
||||
|
||||
assertTrue(row.meta.orEmpty().contains("last: error"))
|
||||
assertTrue(row.meta.orEmpty().contains("error: model timeout"))
|
||||
assertTrue(row.meta.orEmpty().contains("delivery: phone offline"))
|
||||
assertEquals(
|
||||
listOf(DashboardActionKind.ViewCronRuns, DashboardActionKind.DeleteCron),
|
||||
row.actions.map(DashboardItemAction::kind),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun profileScopedManagePlumbing_usesEffectiveProfileForListAndRowActions() {
|
||||
assertEquals(
|
||||
"/api/mcp/servers?profile=work%20profile",
|
||||
dashboardSectionRequestPath("/api/mcp/servers", "work profile"),
|
||||
)
|
||||
assertEquals(
|
||||
"/api/providers/custom-endpoints",
|
||||
"/api/providers/custom-endpoints?profile=work%20profile",
|
||||
dashboardSectionRequestPath("/api/providers/custom-endpoints", "work profile"),
|
||||
)
|
||||
assertEquals(
|
||||
"/api/learning/graph?profile=work%20profile",
|
||||
dashboardSectionRequestPath("/api/learning/graph", "work profile"),
|
||||
)
|
||||
val scoped = scopeDashboardManageItems(
|
||||
"/api/mcp/servers",
|
||||
"work profile",
|
||||
listOf(DashboardSummaryItem(id = "hosted", title = "Hosted")),
|
||||
)
|
||||
assertEquals("work profile", scoped.single().profile)
|
||||
val endpoint = scopeDashboardManageItems(
|
||||
"/api/providers/custom-endpoints",
|
||||
"work profile",
|
||||
listOf(DashboardSummaryItem(id = "local", title = "Local")),
|
||||
)
|
||||
assertEquals("work profile", endpoint.single().profile)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+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,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() })
|
||||
}
|
||||
}
|
||||
+42
@@ -58,6 +58,48 @@ class ChatViewModelCommandCatalogTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseCommandsCatalog_ranksOnlySkillSlotsAndBoundsMetadata() {
|
||||
val catalog = buildJsonObject {
|
||||
put(
|
||||
"pairs",
|
||||
JsonArray(
|
||||
listOf(
|
||||
commandPair("status", "Show status"),
|
||||
commandPair("research", "Research"),
|
||||
commandPair("help", "Show help"),
|
||||
commandPair("work", "Worktree"),
|
||||
),
|
||||
),
|
||||
)
|
||||
put("skills", buildJsonObject {
|
||||
put("/research", buildJsonObject {
|
||||
put("usage", 60)
|
||||
put("origin", "bundled")
|
||||
})
|
||||
put("/work", buildJsonObject {
|
||||
put("usage", 172)
|
||||
put("origin", "local")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
val commands = parseCommandsCatalog(catalog)
|
||||
|
||||
assertEquals(listOf("/status", "/work", "/help", "/research"), commands.map { it.command })
|
||||
assertEquals(172, commands[1].usageRank)
|
||||
assertEquals("local", commands[1].origin)
|
||||
assertEquals(listOf("/status", "/help"), commands.filter { it.usageRank == 0 }.map { it.command })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deferredConfigResult_acceptsCurrentBooleanShapes() {
|
||||
assertTrue(isDeferredConfigResult(buildJsonObject { put("deferred", true) }))
|
||||
assertTrue(isDeferredConfigResult(buildJsonObject { put("deferred", "1") }))
|
||||
assertFalse(isDeferredConfigResult(buildJsonObject { put("deferred", false) }))
|
||||
assertFalse(isDeferredConfigResult(buildJsonObject { }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseDashboardPersonalityConfig_readsWrappedAndDirectConfig() {
|
||||
val config = buildJsonObject {
|
||||
|
||||
+102
@@ -10,6 +10,7 @@ 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.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
@@ -26,6 +27,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
|
||||
@@ -660,6 +662,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")
|
||||
|
||||
+6
-1
@@ -61,6 +61,7 @@ class ChatViewModelStreamRecoveryTest {
|
||||
private lateinit var handler: ChatHandler
|
||||
|
||||
private val messagesRequests = AtomicInteger(0)
|
||||
private val latestMessagesRequests = AtomicInteger(0)
|
||||
private val streamRequests = AtomicInteger(0)
|
||||
|
||||
/** GET /messages body for the [n]-th poll (1-based). */
|
||||
@@ -99,7 +100,10 @@ class ChatViewModelStreamRecoveryTest {
|
||||
}
|
||||
}
|
||||
request.method == "GET" &&
|
||||
path == "/api/sessions/$SESSION_ID/messages" -> {
|
||||
request.requestUrl?.encodedPath == "/api/sessions/$SESSION_ID/messages" -> {
|
||||
if (request.requestUrl?.queryParameter("order") == "latest") {
|
||||
latestMessagesRequests.incrementAndGet()
|
||||
}
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
@@ -184,6 +188,7 @@ class ChatViewModelStreamRecoveryTest {
|
||||
it.role == MessageRole.ASSISTANT && it.content == RECOVERED && !it.isStreaming
|
||||
}
|
||||
}
|
||||
assertTrue("short recovery must poll one bounded latest page", latestMessagesRequests.get() > 0)
|
||||
|
||||
// Stability requires the answer on two consecutive polls, and the
|
||||
// first poll had none — at least 3 polls total.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user